update
This commit was merged in pull request #4.
This commit is contained in:
@@ -1,58 +1,66 @@
|
||||
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
|
||||
import jwt
|
||||
import datetime
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class AuthService(BaseService):
|
||||
class AuthService:
|
||||
@staticmethod
|
||||
def login(data):
|
||||
def login(username, password):
|
||||
"""
|
||||
Process the login request.
|
||||
|
||||
Args:
|
||||
data (dict): Login credentials including username and password.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response with JWT token and user information.
|
||||
Login method that checks for specific credentials and returns a JWT token
|
||||
"""
|
||||
try:
|
||||
# Extract credentials
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
# Define valid credentials for testing
|
||||
valid_credentials = {
|
||||
"digifiuser": "digifipass",
|
||||
"admin": "admin123",
|
||||
"test": "test123"
|
||||
}
|
||||
|
||||
# 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
|
||||
# Check if the provided credentials are valid
|
||||
if username in valid_credentials and password == valid_credentials[username]:
|
||||
# Generate JWT token with 15 minutes expiration
|
||||
payload = {
|
||||
'sub': username, # Subject (typically user ID)
|
||||
'iat': datetime.datetime.utcnow(), # Issued at
|
||||
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15), # Expiration (15 minutes)
|
||||
'role': 'admin' if username == 'admin' else 'user' # Role based on username
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"An error occurred during login: {str(e)}", exc_info=True)
|
||||
return jsonify({
|
||||
"message": "Internal Server Error"
|
||||
}), 500
|
||||
# Get the secret key from config
|
||||
secret_key = current_app.config.get('JWT_SECRET_KEY', 'default-secret-key')
|
||||
|
||||
# Generate the token
|
||||
token = jwt.encode(payload, secret_key, algorithm='HS256')
|
||||
|
||||
# Return the token and user info
|
||||
return {
|
||||
'jwt_token': token,
|
||||
'user': {
|
||||
'username': username,
|
||||
'role': 'admin' if username == 'admin' else 'user'
|
||||
},
|
||||
'expires_in': 900 # 15 minutes in seconds
|
||||
}
|
||||
else:
|
||||
# Return error for invalid credentials
|
||||
return {
|
||||
'error': 'Invalid credentials',
|
||||
'message': 'The username or password is incorrect'
|
||||
}, 401
|
||||
|
||||
@staticmethod
|
||||
def verify_token(token):
|
||||
"""
|
||||
Verify the JWT token
|
||||
"""
|
||||
try:
|
||||
# Get the secret key from config
|
||||
secret_key = current_app.config.get('JWT_SECRET_KEY', 'default-secret-key')
|
||||
|
||||
# Decode the token
|
||||
payload = jwt.decode(token, secret_key, algorithms=['HS256'])
|
||||
return payload
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None # Token has expired
|
||||
except jwt.InvalidTokenError:
|
||||
return None # Invalid token
|
||||
Reference in New Issue
Block a user