98 lines
2.6 KiB
Python
98 lines
2.6 KiB
Python
"""
|
|
Authentication and authorization services.
|
|
"""
|
|
from typing import Optional, Dict, Any
|
|
from django.contrib.auth.models import User
|
|
from django.contrib.auth import authenticate
|
|
from django.utils import timezone
|
|
from backend.core.models import Profile
|
|
from backend.core.repositories.profiles.profiles import ProfileRepository
|
|
|
|
|
|
class AuthService:
|
|
"""
|
|
Service for authentication and authorization operations.
|
|
"""
|
|
|
|
@staticmethod
|
|
def authenticate_user(username: str, password: str) -> Optional[User]:
|
|
"""
|
|
Authenticate a user with username and password.
|
|
|
|
Args:
|
|
username: Username
|
|
password: Password
|
|
|
|
Returns:
|
|
User object if authenticated, None otherwise
|
|
"""
|
|
return authenticate(username=username, password=password)
|
|
|
|
@staticmethod
|
|
def get_user_profile(user_id: int) -> Optional[Profile]:
|
|
"""
|
|
Get a user's profile.
|
|
|
|
Args:
|
|
user_id: User ID
|
|
|
|
Returns:
|
|
Profile object or None if not found
|
|
"""
|
|
try:
|
|
user = User.objects.get(id=user_id)
|
|
return ProfileRepository.get_by_user(user)
|
|
except User.DoesNotExist:
|
|
return None
|
|
|
|
@staticmethod
|
|
def check_permission(user: User, permission: str) -> bool:
|
|
"""
|
|
Check if a user has a specific permission.
|
|
|
|
Args:
|
|
user: User object
|
|
permission: Permission string (e.g., 'core.add_customer')
|
|
|
|
Returns:
|
|
True if user has permission, False otherwise
|
|
"""
|
|
return user.has_perm(permission)
|
|
|
|
@staticmethod
|
|
def log_login(user: User) -> None:
|
|
"""
|
|
Log a user login.
|
|
|
|
Args:
|
|
user: User object
|
|
"""
|
|
user.last_login = timezone.now()
|
|
user.save(update_fields=['last_login'])
|
|
|
|
@staticmethod
|
|
def create_user(user_data: Dict[str, Any], profile_data: Dict[str, Any]) -> User:
|
|
"""
|
|
Create a new user with profile.
|
|
|
|
Args:
|
|
user_data: User data (username, email, password, etc.)
|
|
profile_data: Profile data
|
|
|
|
Returns:
|
|
Created User object
|
|
"""
|
|
# Create the user
|
|
user = User.objects.create_user(
|
|
username=user_data['username'],
|
|
email=user_data.get('email', ''),
|
|
password=user_data['password'],
|
|
first_name=user_data.get('first_name', ''),
|
|
last_name=user_data.get('last_name', '')
|
|
)
|
|
|
|
# Create the profile
|
|
profile_data['user'] = user
|
|
ProfileRepository.create(profile_data)
|
|
|
|
return user |