| """
|
| Authentication Module
|
| =====================
|
| User authentication logic for Pharma K platform.
|
| """
|
|
|
| import hashlib
|
| import re
|
| from typing import Optional, Tuple
|
| from utils.database import (
|
| create_user, get_user_by_email, update_last_login,
|
| get_all_users, get_default_llm_config, set_default_llm_config
|
| )
|
|
|
|
|
| def hash_password(password: str) -> str:
|
| """Hash password using SHA256 (simple, no bcrypt dependency)."""
|
| return hashlib.sha256(password.encode()).hexdigest()
|
|
|
|
|
| def verify_password(password: str, password_hash: str) -> bool:
|
| """Verify password against hash."""
|
| return hash_password(password) == password_hash
|
|
|
|
|
| def validate_email(email: str) -> bool:
|
| """Validate email format."""
|
| pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
| return bool(re.match(pattern, email))
|
|
|
|
|
| def validate_password(password: str) -> Tuple[bool, str]:
|
| """
|
| Validate password strength.
|
| Returns (is_valid, error_message)
|
| """
|
| if len(password) < 6:
|
| return False, "密码长度至少6位"
|
| return True, ""
|
|
|
|
|
| def register_user(email: str, password: str) -> Tuple[bool, str]:
|
| """
|
| Register a new user.
|
| Returns (success, message)
|
| """
|
|
|
| if not validate_email(email):
|
| return False, "邮箱格式不正确"
|
|
|
|
|
| is_valid, error_msg = validate_password(password)
|
| if not is_valid:
|
| return False, error_msg
|
|
|
|
|
| if get_user_by_email(email):
|
| return False, "该邮箱已被注册"
|
|
|
|
|
| password_hash = hash_password(password)
|
| if create_user(email, password_hash):
|
| return True, "注册成功!请登录"
|
| else:
|
| return False, "注册失败,请重试"
|
|
|
|
|
| def login_user(email: str, password: str) -> Tuple[bool, str, Optional[dict]]:
|
| """
|
| Login user.
|
| Returns (success, message, user_info)
|
| """
|
| user = get_user_by_email(email)
|
|
|
| if not user:
|
| return False, "用户不存在", None
|
|
|
| if not verify_password(password, user['password_hash']):
|
| return False, "密码错误", None
|
|
|
|
|
| update_last_login(email)
|
|
|
| return True, "登录成功", {
|
| 'id': user['id'],
|
| 'email': user['email'],
|
| 'role': user['role']
|
| }
|
|
|
|
|
| def is_admin(user: dict) -> bool:
|
| """Check if user is admin."""
|
| return user and user.get('role') == 'admin'
|
|
|
|
|
|
|
| __all__ = [
|
| 'register_user',
|
| 'login_user',
|
| 'is_admin',
|
| 'get_all_users',
|
| 'get_default_llm_config',
|
| 'set_default_llm_config',
|
| 'validate_email'
|
| ]
|
|
|