66 lines
2.3 KiB
Python
66 lines
2.3 KiB
Python
import jwt
|
|
import datetime
|
|
from flask import current_app
|
|
|
|
|
|
class AuthService:
|
|
@staticmethod
|
|
def login(username, password):
|
|
"""
|
|
Login method that checks for specific credentials and returns a JWT token
|
|
"""
|
|
# Define valid credentials for testing
|
|
valid_credentials = {
|
|
"digifiuser": "digifipass",
|
|
"admin": "admin123",
|
|
"test": "test123"
|
|
}
|
|
|
|
# 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
|
|
}
|
|
|
|
# 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 |