Enhance user experience by implementing password change functionality, adding validation for password strength and matching, and improving error messaging in the change password form.
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<div class="flex justify-center mt-10">
|
||||
<div class="w-full max-w-md">
|
||||
<div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
|
||||
<h2 class="text-2xl font-bold text-irish-green mb-6 text-center">Change Password</h2>
|
||||
|
||||
{% if error %}
|
||||
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
|
||||
{{ error }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if message %}
|
||||
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
|
||||
{{ message }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="POST" action="/auth/change-password" id="password-form" onsubmit="return validateForm()">
|
||||
<div class="mb-4">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="current_password">
|
||||
Current Password
|
||||
</label>
|
||||
<input
|
||||
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
|
||||
id="current_password"
|
||||
name="current_password"
|
||||
type="password"
|
||||
placeholder="Enter your current password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="new_password">
|
||||
New Password
|
||||
</label>
|
||||
<input
|
||||
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
|
||||
id="new_password"
|
||||
name="new_password"
|
||||
type="password"
|
||||
placeholder="Enter your new password"
|
||||
required
|
||||
oninput="checkPasswordStrength()"
|
||||
>
|
||||
<div class="mt-2">
|
||||
<div class="w-full bg-gray-200 rounded-full h-2.5">
|
||||
<div class="bg-red-600 h-2.5 rounded-full" id="password-strength-meter" style="width: 0%"></div>
|
||||
</div>
|
||||
<p class="text-xs mt-1" id="password-strength-text">Password strength: Too weak</p>
|
||||
</div>
|
||||
<ul class="text-xs text-gray-600 mt-2 list-disc pl-5">
|
||||
<li id="length-check" class="text-red-500">At least 8 characters</li>
|
||||
<li id="lowercase-check" class="text-red-500">At least one lowercase letter</li>
|
||||
<li id="uppercase-check" class="text-red-500">At least one uppercase letter</li>
|
||||
<li id="number-check" class="text-red-500">At least one number</li>
|
||||
<li id="special-check" class="text-red-500">At least one special character</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="confirm_password">
|
||||
Confirm New Password
|
||||
</label>
|
||||
<input
|
||||
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
|
||||
id="confirm_password"
|
||||
name="confirm_password"
|
||||
type="password"
|
||||
placeholder="Confirm your new password"
|
||||
required
|
||||
oninput="checkPasswordMatch()"
|
||||
>
|
||||
<p id="password-match" class="text-xs mt-1 hidden text-red-500">Passwords do not match</p>
|
||||
</div>
|
||||
|
||||
<div id="same-password-warning" class="hidden bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded mb-4">
|
||||
New password is the same as your current password. Please choose a different password.
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<button
|
||||
class="bg-irish-green hover:bg-opacity-90 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
|
||||
type="submit"
|
||||
id="submit-button"
|
||||
>
|
||||
Change Password
|
||||
</button>
|
||||
<a
|
||||
class="inline-block align-baseline font-bold text-sm text-irish-green hover:text-irish-green-dark"
|
||||
href="/auth/profile"
|
||||
>
|
||||
Cancel
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function checkPasswordStrength() {
|
||||
const password = document.getElementById('new_password').value;
|
||||
const currentPassword = document.getElementById('current_password').value;
|
||||
const meter = document.getElementById('password-strength-meter');
|
||||
const strengthText = document.getElementById('password-strength-text');
|
||||
const samePasswordWarning = document.getElementById('same-password-warning');
|
||||
|
||||
// Check if new password matches current password
|
||||
if (password && currentPassword && password === currentPassword) {
|
||||
samePasswordWarning.classList.remove('hidden');
|
||||
} else {
|
||||
samePasswordWarning.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Check requirements
|
||||
const hasLength = password.length >= 8;
|
||||
const hasLower = /[a-z]/.test(password);
|
||||
const hasUpper = /[A-Z]/.test(password);
|
||||
const hasNumber = /\d/.test(password);
|
||||
const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
|
||||
|
||||
// Update requirement indicators
|
||||
document.getElementById('length-check').className = hasLength ? 'text-green-500' : 'text-red-500';
|
||||
document.getElementById('lowercase-check').className = hasLower ? 'text-green-500' : 'text-red-500';
|
||||
document.getElementById('uppercase-check').className = hasUpper ? 'text-green-500' : 'text-red-500';
|
||||
document.getElementById('number-check').className = hasNumber ? 'text-green-500' : 'text-red-500';
|
||||
document.getElementById('special-check').className = hasSpecial ? 'text-green-500' : 'text-red-500';
|
||||
|
||||
// Calculate strength percentage (20% for each criteria)
|
||||
let strength = 0;
|
||||
if (hasLength) strength += 20;
|
||||
if (hasLower) strength += 20;
|
||||
if (hasUpper) strength += 20;
|
||||
if (hasNumber) strength += 20;
|
||||
if (hasSpecial) strength += 20;
|
||||
|
||||
// Update meter
|
||||
meter.style.width = `${strength}%`;
|
||||
|
||||
// Set color based on strength
|
||||
if (strength < 40) {
|
||||
meter.className = 'bg-red-600 h-2.5 rounded-full';
|
||||
strengthText.textContent = 'Password strength: Too weak';
|
||||
strengthText.className = 'text-xs mt-1 text-red-600';
|
||||
} else if (strength < 80) {
|
||||
meter.className = 'bg-yellow-500 h-2.5 rounded-full';
|
||||
strengthText.textContent = 'Password strength: Medium';
|
||||
strengthText.className = 'text-xs mt-1 text-yellow-600';
|
||||
} else {
|
||||
meter.className = 'bg-green-500 h-2.5 rounded-full';
|
||||
strengthText.textContent = 'Password strength: Strong';
|
||||
strengthText.className = 'text-xs mt-1 text-green-600';
|
||||
}
|
||||
}
|
||||
|
||||
function checkPasswordMatch() {
|
||||
const password = document.getElementById('new_password').value;
|
||||
const confirmPassword = document.getElementById('confirm_password').value;
|
||||
const matchMessage = document.getElementById('password-match');
|
||||
|
||||
if (confirmPassword) {
|
||||
if (password !== confirmPassword) {
|
||||
matchMessage.classList.remove('hidden');
|
||||
} else {
|
||||
matchMessage.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateForm() {
|
||||
const password = document.getElementById('new_password').value;
|
||||
const confirmPassword = document.getElementById('confirm_password').value;
|
||||
const currentPassword = document.getElementById('current_password').value;
|
||||
|
||||
// Check if passwords match
|
||||
if (password !== confirmPassword) {
|
||||
alert('New passwords do not match.');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if new password is same as current
|
||||
if (password === currentPassword) {
|
||||
alert('New password must be different from your current password.');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check password requirements
|
||||
const hasLength = password.length >= 8;
|
||||
const hasLower = /[a-z]/.test(password);
|
||||
const hasUpper = /[A-Z]/.test(password);
|
||||
const hasNumber = /\d/.test(password);
|
||||
const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
|
||||
|
||||
if (!hasLength || !hasLower || !hasUpper || !hasNumber || !hasSpecial) {
|
||||
alert('Password does not meet the strength requirements.');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Initial check on page load
|
||||
window.onload = function() {
|
||||
if (document.getElementById('new_password').value) {
|
||||
checkPasswordStrength();
|
||||
}
|
||||
if (document.getElementById('confirm_password').value) {
|
||||
checkPasswordMatch();
|
||||
}
|
||||
};
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -2,6 +2,13 @@
|
||||
{% block content %}
|
||||
<div class="max-w-3xl mx-auto my-8">
|
||||
<div class="bg-white p-8 rounded-lg shadow-md">
|
||||
<!-- Display messages if present -->
|
||||
{% if request.query_params.message %}
|
||||
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
|
||||
{{ request.query_params.message }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="flex flex-col md:flex-row items-center md:items-start md:space-x-8">
|
||||
<!-- Profile Image -->
|
||||
<div class="mb-6 md:mb-0">
|
||||
@@ -37,10 +44,9 @@
|
||||
<div class="border-b border-gray-200 pb-4">
|
||||
<h3 class="text-gray-700 font-medium mb-2">Change Password</h3>
|
||||
<p class="text-sm text-gray-600 mb-3">Update your password to keep your account secure.</p>
|
||||
<button class="bg-irish-green text-white py-2 px-4 rounded-md hover:bg-opacity-90 transition" disabled>
|
||||
<a href="/auth/change-password" class="inline-block bg-irish-green text-white py-2 px-4 rounded-md hover:bg-opacity-90 transition">
|
||||
Change Password
|
||||
<span class="text-xs">(Coming Soon)</span>
|
||||
</button>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="pt-4">
|
||||
|
||||
@@ -17,13 +17,14 @@
|
||||
|
||||
<form action="/redeem/apply/{{ ticket.code }}" method="post">
|
||||
<div class="mb-6">
|
||||
<label for="team_id" class="block text-sm font-medium text-gray-700 mb-2">Select Team to Award Points:</label>
|
||||
<label for="team_id" class="block text-sm font-medium text-gray-700 mb-2">Select Your Team to Award Points:</label>
|
||||
<select name="team_id" id="team_id" required class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-irish-green">
|
||||
<option value="">-- Select a team --</option>
|
||||
{% for team in user_teams %}
|
||||
<option value="{{ team.id }}">{{ team.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<p class="text-sm text-gray-500 mt-1">Only teams you are a member of are shown</p>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="w-full bg-irish-green hover:bg-opacity-90 text-white font-bold py-3 px-4 rounded-md transition">
|
||||
@@ -58,7 +59,7 @@
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium">Select Your Team</p>
|
||||
<p class="text-gray-600 text-sm">Choose which team should receive these points.</p>
|
||||
<p class="text-gray-600 text-sm">Choose which of your teams should receive these points.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+157
-6
@@ -5,13 +5,16 @@ from typing import Optional
|
||||
import secrets
|
||||
import os
|
||||
import uuid
|
||||
import re
|
||||
from starlette.status import HTTP_303_SEE_OTHER, HTTP_302_FOUND
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import User
|
||||
from ..auth.oauth import authentik_oauth
|
||||
from ..templates_config import templates
|
||||
from ..security import verify_password, get_password_hash
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
@@ -33,12 +36,53 @@ async def login_post(
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Handle login form submission"""
|
||||
# This is a placeholder - implement real login logic here
|
||||
error = "This login method is not fully implemented yet"
|
||||
return templates.TemplateResponse(
|
||||
"auth/login.html",
|
||||
{"request": request, "error": error, "show_oauth": True, "oauth_provider_name": "Authentik"}
|
||||
)
|
||||
error = None
|
||||
|
||||
# Look up the user by username or email
|
||||
user = db.query(User).filter(
|
||||
(User.username == username) | (User.email == username)
|
||||
).first()
|
||||
|
||||
# Check if user exists and password is correct
|
||||
if not user:
|
||||
error = "Invalid username or email"
|
||||
elif user.is_oauth_user and not user.hashed_password:
|
||||
error = "This account uses OAuth for login. Please use the OAuth login option."
|
||||
elif not verify_password(password, user.hashed_password):
|
||||
error = "Invalid password"
|
||||
elif not user.is_active:
|
||||
error = "This account has been deactivated"
|
||||
|
||||
# If there was an error, re-render the login page
|
||||
if error:
|
||||
return templates.TemplateResponse(
|
||||
"auth/login.html",
|
||||
{
|
||||
"request": request,
|
||||
"error": error,
|
||||
"show_oauth": True,
|
||||
"oauth_provider_name": "Authentik"
|
||||
}
|
||||
)
|
||||
|
||||
# Update the last login timestamp
|
||||
user.last_login = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
# Set session data
|
||||
request.session["user_id"] = user.id
|
||||
request.session["username"] = user.username
|
||||
request.session["is_authenticated"] = True
|
||||
request.session["is_admin"] = user.is_admin
|
||||
|
||||
# If remember me is checked, set session expiry to a longer time (30 days)
|
||||
if remember:
|
||||
# Session middleware handles this through cookies, so we just need to set the flag
|
||||
request.session["remember_me"] = True
|
||||
|
||||
# Redirect to dashboard or previously requested page
|
||||
next_page = request.query_params.get("next", "/dashboard")
|
||||
return RedirectResponse(next_page, status_code=HTTP_303_SEE_OTHER)
|
||||
|
||||
@router.get("/register", response_class=HTMLResponse)
|
||||
async def register_page(request: Request, error: Optional[str] = None):
|
||||
@@ -206,3 +250,110 @@ async def profile_page(request: Request):
|
||||
"auth/profile.html",
|
||||
{"request": request, "user": user}
|
||||
)
|
||||
|
||||
@router.get("/change-password", response_class=HTMLResponse)
|
||||
async def change_password_page(request: Request, error: Optional[str] = None, message: Optional[str] = None):
|
||||
"""Change password page"""
|
||||
# Check if user is logged in
|
||||
user_id = request.session.get("user_id")
|
||||
if not user_id:
|
||||
return RedirectResponse("/auth/login?next=/auth/change-password", status_code=HTTP_303_SEE_OTHER)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": error, "message": message}
|
||||
)
|
||||
|
||||
@router.post("/change-password", response_class=HTMLResponse)
|
||||
async def change_password_post(
|
||||
request: Request,
|
||||
current_password: str = Form(...),
|
||||
new_password: str = Form(...),
|
||||
confirm_password: str = Form(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Handle change password form submission"""
|
||||
# Check if user is logged in
|
||||
user_id = request.session.get("user_id")
|
||||
if not user_id:
|
||||
return RedirectResponse("/auth/login", status_code=HTTP_303_SEE_OTHER)
|
||||
|
||||
# Validate form data
|
||||
if new_password != confirm_password:
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": "New passwords do not match"}
|
||||
)
|
||||
|
||||
# Get user from database
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
request.session.clear()
|
||||
return RedirectResponse("/auth/login", status_code=HTTP_303_SEE_OTHER)
|
||||
|
||||
# Check if this is an OAuth user without a password
|
||||
if user.is_oauth_user and not user.hashed_password:
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": "OAuth users cannot change passwords this way"}
|
||||
)
|
||||
|
||||
# Verify current password
|
||||
if not verify_password(current_password, user.hashed_password):
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": "Current password is incorrect"}
|
||||
)
|
||||
|
||||
# Check if new password is the same as current password
|
||||
if current_password == new_password:
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": "New password must be different from your current password"}
|
||||
)
|
||||
|
||||
# Server-side password strength validation
|
||||
password_validation_error = validate_password_strength(new_password)
|
||||
if password_validation_error:
|
||||
return templates.TemplateResponse(
|
||||
"auth/change_password.html",
|
||||
{"request": request, "error": password_validation_error}
|
||||
)
|
||||
|
||||
# Update password
|
||||
user.hashed_password = get_password_hash(new_password)
|
||||
db.commit()
|
||||
|
||||
# Redirect to profile page with success message
|
||||
return RedirectResponse(
|
||||
"/auth/profile?message=Password+changed+successfully",
|
||||
status_code=HTTP_303_SEE_OTHER
|
||||
)
|
||||
|
||||
def validate_password_strength(password: str) -> Optional[str]:
|
||||
"""
|
||||
Validates password strength based on the following criteria:
|
||||
- At least 8 characters long
|
||||
- Contains at least one lowercase letter
|
||||
- Contains at least one uppercase letter
|
||||
- Contains at least one digit
|
||||
- Contains at least one special character
|
||||
|
||||
Returns error message if validation fails, None if password is valid
|
||||
"""
|
||||
if len(password) < 8:
|
||||
return "Password must be at least 8 characters long"
|
||||
|
||||
if not re.search(r"[a-z]", password):
|
||||
return "Password must contain at least one lowercase letter"
|
||||
|
||||
if not re.search(r"[A-Z]", password):
|
||||
return "Password must contain at least one uppercase letter"
|
||||
|
||||
if not re.search(r"\d", password):
|
||||
return "Password must contain at least one number"
|
||||
|
||||
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
|
||||
return "Password must contain at least one special character"
|
||||
|
||||
return None
|
||||
|
||||
+61
-3
@@ -73,13 +73,43 @@ def redeem_code(code: str, request: Request, db: Session = Depends(get_db)):
|
||||
}
|
||||
)
|
||||
|
||||
# Get all available teams
|
||||
all_teams = db.query(Team).all()
|
||||
# Get only teams the user is a member of, if logged in
|
||||
user_teams = []
|
||||
if user:
|
||||
# Query teams where the user is a member using TeamMembership relation
|
||||
user_teams = (
|
||||
db.query(Team)
|
||||
.join(TeamMembership, Team.id == TeamMembership.team_id)
|
||||
.filter(TeamMembership.user_id == user.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
# If user is not logged in or has no teams, instruct them to log in or join teams
|
||||
if not user:
|
||||
return templates.TemplateResponse(
|
||||
"error.html",
|
||||
{
|
||||
"request": request,
|
||||
"error_title": "Login Required",
|
||||
"error_message": "You must be logged in to redeem QR codes. Please log in and try again.",
|
||||
"user": None
|
||||
}
|
||||
)
|
||||
elif not user_teams:
|
||||
return templates.TemplateResponse(
|
||||
"error.html",
|
||||
{
|
||||
"request": request,
|
||||
"error_title": "No Teams Available",
|
||||
"error_message": "You are not a member of any teams. Please join or create a team before redeeming QR codes.",
|
||||
"user": user
|
||||
}
|
||||
)
|
||||
|
||||
return templates.TemplateResponse("redeem.html", {
|
||||
"request": request,
|
||||
"ticket": qr_code, # Using the same template variable name for compatibility
|
||||
"user_teams": all_teams,
|
||||
"user_teams": user_teams,
|
||||
"has_achievement": bool(qr_code.achievement_name),
|
||||
"base_url": BASE_URL,
|
||||
"user": user # Add user to the context
|
||||
@@ -115,6 +145,16 @@ async def apply_code(
|
||||
user_id = request.session.get("user_id")
|
||||
if user_id:
|
||||
user = db.query(User).get(user_id)
|
||||
else:
|
||||
return templates.TemplateResponse(
|
||||
"error.html",
|
||||
{
|
||||
"request": request,
|
||||
"error_title": "Login Required",
|
||||
"error_message": "You must be logged in to redeem QR codes.",
|
||||
"user": None
|
||||
}
|
||||
)
|
||||
|
||||
# Get form data
|
||||
form_data = await request.form()
|
||||
@@ -168,6 +208,7 @@ async def apply_code(
|
||||
}
|
||||
)
|
||||
|
||||
# Verify the team exists
|
||||
team = db.query(Team).filter_by(id=team_id).first()
|
||||
if not team:
|
||||
return templates.TemplateResponse(
|
||||
@@ -179,6 +220,23 @@ async def apply_code(
|
||||
"user": user # Add user to the context
|
||||
}
|
||||
)
|
||||
|
||||
# Verify the user is a member of the selected team
|
||||
is_team_member = db.query(TeamMembership).filter_by(
|
||||
user_id=user.id,
|
||||
team_id=team.id
|
||||
).first() is not None
|
||||
|
||||
if not is_team_member:
|
||||
return templates.TemplateResponse(
|
||||
"error.html",
|
||||
{
|
||||
"request": request,
|
||||
"error_title": "Not a Team Member",
|
||||
"error_message": "You can only redeem points for teams you are a member of.",
|
||||
"user": user # Add user to the context
|
||||
}
|
||||
)
|
||||
|
||||
# Mark the QR code as redeemed
|
||||
qr_code.redeemed_at_team = team.id
|
||||
|
||||
Reference in New Issue
Block a user