password reset

This commit is contained in:
2025-06-19 16:11:42 +02:00
parent efdb6d50c3
commit 7092167001
20 changed files with 680 additions and 72 deletions

111
test_password_reset.py Normal file
View File

@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""
Test script for password reset functionality
Run this script to test the password reset feature
"""
import os
import sys
from datetime import datetime, timedelta
# Add the current directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import create_app
from models import db, User, PasswordResetToken
from utils import create_notification
from utils.notification import generate_mail_from_notification
def test_password_reset():
"""Test the password reset functionality"""
app = create_app()
with app.app_context():
print("Testing password reset functionality...")
# Check if we have a test user
test_user = User.query.filter_by(email='test@example.com').first()
if not test_user:
print("Creating test user...")
test_user = User(
username='testuser',
email='test@example.com',
last_name='Test User',
is_active=True
)
test_user.set_password('oldpassword123!')
db.session.add(test_user)
db.session.commit()
print(f"Created test user: {test_user.email}")
# Test 1: Create a password reset token
print("\n1. Testing password reset token creation...")
from routes.auth import forgot_password
import secrets
token = secrets.token_urlsafe(32)
reset_token = PasswordResetToken(
user_id=test_user.id,
token=token,
expires_at=datetime.utcnow() + timedelta(hours=1),
ip_address='127.0.0.1'
)
db.session.add(reset_token)
db.session.commit()
print(f"Created password reset token: {token[:20]}...")
# Test 2: Create notification
print("\n2. Testing notification creation...")
notif = create_notification(
notif_type='password_reset',
user_id=test_user.id,
details={
'message': 'You requested a password reset. Click the link below to reset your password.',
'reset_link': f'http://localhost:5000/reset-password/{token}',
'expiry_time': (datetime.utcnow() + timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S UTC'),
'ip_address': '127.0.0.1',
'timestamp': datetime.utcnow().isoformat()
}
)
print(f"Created notification: {notif.id}")
# Test 3: Generate email
print("\n3. Testing email generation...")
try:
mail = generate_mail_from_notification(notif)
if mail:
print(f"Generated email: {mail.subject}")
print(f"Email body preview: {mail.body[:100]}...")
else:
print("No email template found for password reset")
except Exception as e:
print(f"Error generating email: {e}")
# Test 4: Validate token
print("\n4. Testing token validation...")
stored_token = PasswordResetToken.query.filter_by(token=token).first()
if stored_token and stored_token.is_valid():
print("Token is valid")
else:
print("Token is invalid or expired")
# Test 5: Simulate password reset
print("\n5. Testing password reset...")
if stored_token and stored_token.is_valid():
test_user.set_password('newpassword123!')
stored_token.used = True
db.session.commit()
print("Password reset successful")
# Verify password change
if test_user.check_password('newpassword123!'):
print("Password verification successful")
else:
print("Password verification failed")
else:
print("Cannot reset password - token invalid")
print("\nPassword reset test completed!")
if __name__ == '__main__':
test_password_reset()