Files
FirstCore/app/api/services/auth_service.py
T
Azeez Muibi aafb9a9b41 User
2025-04-15 16:43:39 +01:00

58 lines
1.8 KiB
Python

from flask import jsonify
from app.utils.logger import logger
from app.api.services.base_service import BaseService
from app.models.user import User
from flask_jwt_extended import create_access_token
from datetime import timedelta
class AuthService(BaseService):
@staticmethod
def login(data):
"""
Process the login request.
Args:
data (dict): Login credentials including username and password.
Returns:
dict: A standardized response with JWT token and user information.
"""
try:
# Extract credentials
username = data.get('username')
password = data.get('password')
# Validate input
if not username or not password:
return jsonify({
"message": "Username and password are required"
}), 400
# Get user by username
user = User.get_user_by_username(username)
# Check if user exists and password is correct
if not user or not user.check_password(password):
return jsonify({
"message": "Invalid username or password"
}), 401
# Create JWT token with 15 minute expiration
access_token = create_access_token(
identity=user.username,
expires_delta=timedelta(minutes=15),
additional_claims={"name": user.name}
)
# Return token and user information
return {
"jwt_token": access_token,
"name": user.name
}
except Exception as e:
logger.error(f"An error occurred during login: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}), 500