Spaces:
Sleeping
Sleeping
| """ | |
| Authentication utilities and decorators for NeuroSight | |
| """ | |
| from functools import wraps | |
| from flask import redirect, url_for, flash, session | |
| from flask_login import current_user | |
| import re | |
| def login_required_custom(f): | |
| """Custom login required decorator with flash message""" | |
| def decorated_function(*args, **kwargs): | |
| if not current_user.is_authenticated: | |
| flash('Please log in to access this page.', 'warning') | |
| return redirect(url_for('login')) | |
| return f(*args, **kwargs) | |
| return decorated_function | |
| def role_required(*roles): | |
| """Decorator to require specific user roles""" | |
| def decorator(f): | |
| def decorated_function(*args, **kwargs): | |
| if not current_user.is_authenticated: | |
| flash('Please log in to access this page.', 'warning') | |
| return redirect(url_for('login')) | |
| if current_user.role not in roles: | |
| flash('You do not have permission to access this page.', 'danger') | |
| return redirect(url_for('dashboard')) | |
| return f(*args, **kwargs) | |
| return decorated_function | |
| return decorator | |
| def validate_email(email): | |
| """Validate email format""" | |
| pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' | |
| return re.match(pattern, email) is not None | |
| def validate_password(password): | |
| """ | |
| Validate password strength | |
| Requirements: | |
| - At least 8 characters | |
| - Contains uppercase letter | |
| - Contains lowercase letter | |
| - Contains digit | |
| - Contains special character | |
| """ | |
| if len(password) < 8: | |
| return False, "Password must be at least 8 characters long" | |
| if not re.search(r'[A-Z]', password): | |
| return False, "Password must contain at least one uppercase letter" | |
| if not re.search(r'[a-z]', password): | |
| return False, "Password must contain at least one lowercase letter" | |
| if not re.search(r'\d', password): | |
| return False, "Password must contain at least one digit" | |
| if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password): | |
| return False, "Password must contain at least one special character" | |
| return True, "Password is valid" | |
| def sanitize_filename(filename): | |
| """Sanitize filename for safe storage""" | |
| # Remove any path components | |
| filename = filename.split('/')[-1].split('\\')[-1] | |
| # Remove any non-alphanumeric characters except dots, dashes, and underscores | |
| filename = re.sub(r'[^a-zA-Z0-9._-]', '_', filename) | |
| return filename | |