TIF_E41253310/Backend/app/controllers/auth.py

69 lines
2.5 KiB
Python

from sqlalchemy.orm import Session
from app.services.auth import AuthService
from app.schemas.user import UserCreate, UserUpdate
from app.utils.helpers import format_response
class AuthController:
"""
Controller handling authentication requests and response formatting.
Conforms to HTTP-specific patterns.
"""
@staticmethod
def register_user(db: Session, user_in: UserCreate):
"""Invoke registration logic and format successful user registration response."""
new_user = AuthService.register(db, user_in)
data = {
"id": new_user.id,
"username": new_user.username,
"nama": new_user.nama,
"email": new_user.email,
"role": new_user.role,
"kode_prodi": new_user.kode_prodi,
"is_active": new_user.is_active
}
return format_response(True, "Pengguna berhasil ditambahkan", data)
@staticmethod
def login_user(db: Session, username: str, password: str):
"""Invoke login logic, retrieve JWT token, and format login response."""
token_data = AuthService.login(db, username, password)
return format_response(True, "Login berhasil", token_data.model_dump())
@staticmethod
def get_users(db: Session):
users = AuthService.get_all_users(db)
data = [
{
"id": u.id,
"username": u.username,
"nama": u.nama or u.username,
"email": u.email,
"role": u.role or "admin",
"kode_prodi": u.kode_prodi,
"is_active": u.is_active,
"created_at": u.created_at.strftime("%Y-%m-%d %H:%M") if u.created_at else None
}
for u in users
]
return format_response(True, "Data pengguna berhasil diambil", data)
@staticmethod
def update_user(db: Session, user_id: int, user_in: UserUpdate):
user = AuthService.update_user(db, user_id, user_in)
data = {
"id": user.id,
"username": user.username,
"nama": user.nama,
"email": user.email,
"role": user.role,
"kode_prodi": user.kode_prodi,
"is_active": user.is_active
}
return format_response(True, "Data pengguna berhasil diperbarui", data)
@staticmethod
def delete_user(db: Session, user_id: int):
AuthService.delete_user(db, user_id)
return format_response(True, "Pengguna berhasil dihapus", None)