Jun 26 - Implement registration function for user to register account
This commit is contained in:
@@ -429,6 +429,15 @@ def initialize_database():
|
|||||||
value = IF(value IS NULL OR value = '', VALUES(value), value)""",
|
value = IF(value IS NULL OR value = '', VALUES(value), value)""",
|
||||||
(k, v),
|
(k, v),
|
||||||
)
|
)
|
||||||
|
# Seed non-env defaults (INSERT IGNORE so existing values are never overwritten)
|
||||||
|
default_seeds = [
|
||||||
|
("registration.enabled", "0"),
|
||||||
|
]
|
||||||
|
for k, v in default_seeds:
|
||||||
|
cursor.execute(
|
||||||
|
"INSERT IGNORE INTO app_settings (key_name, value) VALUES (%s, %s)",
|
||||||
|
(k, v),
|
||||||
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
logger.info("app_settings seeded from environment variables (env→DB, blank-only overwrite).")
|
logger.info("app_settings seeded from environment variables (env→DB, blank-only overwrite).")
|
||||||
|
|
||||||
|
|||||||
@@ -267,6 +267,35 @@ def update_user_profile(user_id: int, full_name: str, email: str):
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def register_user(username: str, password: str, full_name: str = "", email: str = None):
|
||||||
|
"""Self-service registration. Role is always 'user'. Raises ValueError on duplicates."""
|
||||||
|
conn = None
|
||||||
|
try:
|
||||||
|
conn = get_connection()
|
||||||
|
cur = conn.cursor(dictionary=True)
|
||||||
|
cur.execute("SELECT id FROM users WHERE username=%s", (username,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise ValueError("Username is already taken.")
|
||||||
|
if email:
|
||||||
|
cur.execute("SELECT id FROM users WHERE email=%s", (email,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise ValueError("An account with that email address already exists.")
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO users (username, password, role, full_name, email) VALUES (%s,%s,'user',%s,%s)",
|
||||||
|
(username, _hash_password(password), full_name or username, email or None),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
new_id = cur.lastrowid
|
||||||
|
cur.close()
|
||||||
|
log_action(None, "REGISTER", "users", new_id,
|
||||||
|
f"New user self-registered: '{username}'.")
|
||||||
|
return new_id
|
||||||
|
finally:
|
||||||
|
if conn:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def create_user(admin_id, username, password, role, full_name, email=None):
|
def create_user(admin_id, username, password, role, full_name, email=None):
|
||||||
conn = None
|
conn = None
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -17,10 +17,12 @@ admin_settings_bp = Blueprint("admin_settings", __name__, url_prefix="/admin/set
|
|||||||
@admin_settings_bp.route("/")
|
@admin_settings_bp.route("/")
|
||||||
@admin_required
|
@admin_required
|
||||||
def settings():
|
def settings():
|
||||||
email_settings = get_settings_dict("email.")
|
email_settings = get_settings_dict("email.")
|
||||||
groq_settings = get_settings_dict("groq.")
|
groq_settings = get_settings_dict("groq.")
|
||||||
|
registration_settings = get_settings_dict("registration.")
|
||||||
return render_template("admin/settings.html",
|
return render_template("admin/settings.html",
|
||||||
email=email_settings, groq=groq_settings)
|
email=email_settings, groq=groq_settings,
|
||||||
|
registration=registration_settings)
|
||||||
|
|
||||||
|
|
||||||
@admin_settings_bp.route("/email", methods=["POST"])
|
@admin_settings_bp.route("/email", methods=["POST"])
|
||||||
@@ -58,6 +60,19 @@ def save_groq():
|
|||||||
return redirect(url_for("admin_settings.settings"))
|
return redirect(url_for("admin_settings.settings"))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_settings_bp.route("/registration", methods=["POST"])
|
||||||
|
@admin_required
|
||||||
|
def save_registration():
|
||||||
|
admin = session["user"]
|
||||||
|
enabled = "1" if request.form.get("registration_enabled") == "1" else "0"
|
||||||
|
set_setting("registration.enabled", enabled)
|
||||||
|
log_action(admin["id"], "UPDATE_REGISTRATION_SETTINGS", "app_settings", None,
|
||||||
|
f"User self-registration {'enabled' if enabled == '1' else 'disabled'}.")
|
||||||
|
flash(f"Registration {'enabled' if enabled == '1' else 'disabled'} successfully.", "success")
|
||||||
|
logger.info(f"Registration setting set to '{enabled}' by admin_id={admin['id']}.")
|
||||||
|
return redirect(url_for("admin_settings.settings"))
|
||||||
|
|
||||||
|
|
||||||
@admin_settings_bp.route("/test-email", methods=["POST"])
|
@admin_settings_bp.route("/test-email", methods=["POST"])
|
||||||
@admin_required
|
@admin_required
|
||||||
def test_email():
|
def test_email():
|
||||||
|
|||||||
+48
-2
@@ -8,8 +8,9 @@ from models import (
|
|||||||
authenticate, check_login_allowed, change_password, log_action,
|
authenticate, check_login_allowed, change_password, log_action,
|
||||||
get_user_by_email, create_password_reset_token,
|
get_user_by_email, create_password_reset_token,
|
||||||
get_password_reset_user, consume_password_reset_token,
|
get_password_reset_user, consume_password_reset_token,
|
||||||
purge_expired_reset_tokens, update_user_profile,
|
purge_expired_reset_tokens, update_user_profile, register_user,
|
||||||
)
|
)
|
||||||
|
from config import get_setting
|
||||||
from utils.decorators import login_required
|
from utils.decorators import login_required
|
||||||
from utils.email import send_email
|
from utils.email import send_email
|
||||||
|
|
||||||
@@ -59,7 +60,52 @@ def login():
|
|||||||
else:
|
else:
|
||||||
error = "Invalid username or password."
|
error = "Invalid username or password."
|
||||||
|
|
||||||
return render_template("login.html", error=error)
|
reg_enabled = get_setting("registration.enabled", "0") == "1"
|
||||||
|
return render_template("login.html", error=error, reg_enabled=reg_enabled)
|
||||||
|
|
||||||
|
|
||||||
|
@auth_bp.route("/register", methods=["GET", "POST"])
|
||||||
|
def register():
|
||||||
|
if "user" in session:
|
||||||
|
return redirect(url_for("index"))
|
||||||
|
|
||||||
|
if get_setting("registration.enabled", "0") != "1":
|
||||||
|
flash("Registration is currently disabled. Contact your administrator.", "warning")
|
||||||
|
return redirect(url_for("auth.login"))
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
return render_template("register.html")
|
||||||
|
|
||||||
|
username = request.form.get("username", "").strip()
|
||||||
|
full_name = request.form.get("full_name", "").strip()
|
||||||
|
email = request.form.get("email", "").strip().lower()
|
||||||
|
password = request.form.get("password", "")
|
||||||
|
confirm = request.form.get("confirm_password", "")
|
||||||
|
|
||||||
|
errors = []
|
||||||
|
if not username or len(username) < 3:
|
||||||
|
errors.append("Username must be at least 3 characters.")
|
||||||
|
if len(password) < 8:
|
||||||
|
errors.append("Password must be at least 8 characters.")
|
||||||
|
if password != confirm:
|
||||||
|
errors.append("Passwords do not match.")
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
return render_template("register.html", errors=errors,
|
||||||
|
username=username, full_name=full_name, email=email)
|
||||||
|
try:
|
||||||
|
new_id = register_user(username, password, full_name, email or None)
|
||||||
|
logger.info(f"New user registered: '{username}' id={new_id}.")
|
||||||
|
flash("Account created successfully. You can now sign in.", "success")
|
||||||
|
return redirect(url_for("auth.login"))
|
||||||
|
except ValueError as e:
|
||||||
|
return render_template("register.html", errors=[str(e)],
|
||||||
|
username=username, full_name=full_name, email=email)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"register error: {e}")
|
||||||
|
return render_template("register.html",
|
||||||
|
errors=["An unexpected error occurred. Please try again."],
|
||||||
|
username=username, full_name=full_name, email=email)
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/logout")
|
@auth_bp.route("/logout")
|
||||||
|
|||||||
@@ -93,6 +93,29 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Registration Settings -->
|
||||||
|
<div class="card mt-4">
|
||||||
|
<div class="card-header"><h2 class="card-title">👤 User Registration</h2></div>
|
||||||
|
<form method="post" action="{{ url_for('admin_settings.save_registration') }}">
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label">Allow Self-Registration</label>
|
||||||
|
<select class="form-control" name="registration_enabled">
|
||||||
|
<option value="0" {{ 'selected' if registration.get('registration.enabled') != '1' }}>Disabled (default)</option>
|
||||||
|
<option value="1" {{ 'selected' if registration.get('registration.enabled') == '1' }}>Enabled</option>
|
||||||
|
</select>
|
||||||
|
<small class="text-muted" style="display:block;margin-top:.35rem">
|
||||||
|
When enabled, a "Create Account" link appears on the login page.
|
||||||
|
New accounts are always created with the <strong>User</strong> role.
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button class="btn btn-primary" type="submit">Save</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
function testConnection(type) {
|
function testConnection(type) {
|
||||||
var url = type === 'email' ? '/admin/settings/test-email' : '/admin/settings/test-groq';
|
var url = type === 'email' ? '/admin/settings/test-email' : '/admin/settings/test-groq';
|
||||||
|
|||||||
@@ -37,6 +37,12 @@
|
|||||||
<p style="text-align:center;margin-top:1rem;font-size:.875rem">
|
<p style="text-align:center;margin-top:1rem;font-size:.875rem">
|
||||||
<a href="{{ url_for('auth.forgot_password') }}" style="color:var(--accent)">Forgot password?</a>
|
<a href="{{ url_for('auth.forgot_password') }}" style="color:var(--accent)">Forgot password?</a>
|
||||||
</p>
|
</p>
|
||||||
|
{% if reg_enabled %}
|
||||||
|
<p style="text-align:center;margin-top:.5rem;font-size:.875rem">
|
||||||
|
Don't have an account?
|
||||||
|
<a href="{{ url_for('auth.register') }}" style="color:var(--accent)">Create one</a>
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Create Account — Website Checker</title>
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||||
|
</head>
|
||||||
|
<body class="login-wrap">
|
||||||
|
<div class="login-box">
|
||||||
|
|
||||||
|
<div class="login-logo">
|
||||||
|
<span class="brand-icon">🌐</span>
|
||||||
|
<h1>Website Checker</h1>
|
||||||
|
<p>Create Account</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if errors %}
|
||||||
|
{% for err in errors %}
|
||||||
|
<div class="alert alert-danger mb-2">{{ err }}</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="{{ url_for('auth.register') }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username">Username</label>
|
||||||
|
<input type="text" id="username" name="username"
|
||||||
|
value="{{ username or '' }}"
|
||||||
|
autocomplete="username" autofocus required minlength="3">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="full_name">Full Name <span class="text-muted" style="font-weight:400">(optional)</span></label>
|
||||||
|
<input type="text" id="full_name" name="full_name"
|
||||||
|
value="{{ full_name or '' }}"
|
||||||
|
autocomplete="name">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="email">Email <span class="text-muted" style="font-weight:400">(optional)</span></label>
|
||||||
|
<input type="email" id="email" name="email"
|
||||||
|
value="{{ email or '' }}"
|
||||||
|
autocomplete="email">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<input type="password" id="password" name="password"
|
||||||
|
autocomplete="new-password" required minlength="8"
|
||||||
|
placeholder="Minimum 8 characters">
|
||||||
|
<div class="pw-strength-wrap">
|
||||||
|
<div class="pw-strength-bar"><div class="pw-strength-fill" id="pw-fill"></div></div>
|
||||||
|
<small class="pw-strength-label" id="pw-label"></small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="confirm_password">Confirm Password</label>
|
||||||
|
<input type="password" id="confirm_password" name="confirm_password"
|
||||||
|
autocomplete="new-password" required placeholder="Repeat password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button class="btn btn-primary w-full" type="submit">Create Account</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p style="text-align:center;margin-top:1rem;font-size:.875rem">
|
||||||
|
Already have an account?
|
||||||
|
<a href="{{ url_for('auth.login') }}" style="color:var(--accent)">Sign in</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<script src="{{ url_for('static', filename='js/pw-strength.js') }}"></script>
|
||||||
|
<script>attachPasswordStrength('password', 'pw-fill', 'pw-label');</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user