Overview
Location:services/auth.py
This module handles:
- Secure password hashing using bcrypt
- Password verification against stored hashes
- User authentication with username and password
- Session token generation
Functions
hash_password
Generates a bcrypt hash from a plain text password.The plain text password to hash
str - The bcrypt-hashed password as a UTF-8 string
This function uses bcrypt with automatic salt generation for secure password hashing. Never store plain text passwords.
verify_password
Verifies a plain text password against a stored bcrypt hash.The plain text password to verify
The stored bcrypt hash to compare against
bool - True if the password matches, False otherwise
get_user_by_username
Retrieves a user record from the database by username.SQLAlchemy database session
The username to search for
Optional[User] - The User model instance or None if not found
authenticate
Authenticates a user with username and password credentials.SQLAlchemy database session
The username to authenticate
The plain text password to verify
Optional[Dict] - User information dictionary or None if authentication fails
The returned dictionary contains:
id(int): User IDusername(str): Usernamerole(str): User role (admin, assistant, artist)artist_id(Optional[int]): Associated artist ID if applicable
Authentication Flow
Validation checks
The function verifies:
- User exists in the database
- User account is active (
is_active = True) - Password matches the stored hash
Security Considerations
Password hashing strength
Password hashing strength
The service uses bcrypt with automatic salt generation. Bcrypt is designed to be slow, making brute-force attacks computationally expensive. Each password gets a unique salt, preventing rainbow table attacks.
Timing attacks
Timing attacks
Be aware that the authentication function may be vulnerable to timing attacks. Consider implementing constant-time comparison or rate limiting to prevent username enumeration.
Inactive users
Inactive users
The
authenticate() function explicitly checks for active users. Inactive users cannot log in even with correct credentials, providing a soft-delete mechanism.Related
Permissions Service
Role-based access control and authorization
User Model
User data model and schema