Jun 26 - Implement registration function for user to register account

This commit is contained in:
2026-06-26 13:40:34 -04:00
parent a47335110c
commit adb39a4aa8
7 changed files with 210 additions and 5 deletions
+9
View File
@@ -429,6 +429,15 @@ def initialize_database():
value = IF(value IS NULL OR value = '', VALUES(value), value)""",
(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()
logger.info("app_settings seeded from environment variables (env→DB, blank-only overwrite).")
+29
View File
@@ -267,6 +267,35 @@ def update_user_profile(user_id: int, full_name: str, email: str):
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):
conn = None
try:
+16 -1
View File
@@ -19,8 +19,10 @@ admin_settings_bp = Blueprint("admin_settings", __name__, url_prefix="/admin/set
def settings():
email_settings = get_settings_dict("email.")
groq_settings = get_settings_dict("groq.")
registration_settings = get_settings_dict("registration.")
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"])
@@ -58,6 +60,19 @@ def save_groq():
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_required
def test_email():
+48 -2
View File
@@ -8,8 +8,9 @@ from models import (
authenticate, check_login_allowed, change_password, log_action,
get_user_by_email, create_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.email import send_email
@@ -59,7 +60,52 @@ def login():
else:
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")
+23
View File
@@ -93,6 +93,29 @@
</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>
function testConnection(type) {
var url = type === 'email' ? '/admin/settings/test-email' : '/admin/settings/test-groq';
+6
View File
@@ -37,6 +37,12 @@
<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>
</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>
</body>
+77
View File
@@ -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>