nopaque/app/api/auth.py

50 lines
1.3 KiB
Python
Raw Normal View History

2022-09-02 11:24:14 +00:00
from flask import current_app
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
2022-09-02 11:24:14 +00:00
from werkzeug.exceptions import Forbidden, Unauthorized
from app.models import User
basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth()
2022-09-02 11:24:14 +00:00
auth_error_responses = {
Unauthorized.code: Unauthorized.description,
Forbidden.code: Forbidden.description
}
@basic_auth.verify_password
def verify_password(email_or_username, password):
2022-09-02 11:24:14 +00:00
user = User.query.filter((User.email == email_or_username.lower()) | (User.username == email_or_username)).first()
if user is not None and user.verify_password(password):
return user
@basic_auth.error_handler
def basic_auth_error(status):
2022-09-02 11:24:14 +00:00
error = (Forbidden if status == 403 else Unauthorized)()
return {
'code': error.code,
'message': error.name,
'description': error.description,
}, error.code, {'WWW-Authenticate': 'Form'}
@token_auth.verify_token
def verify_token(token):
2022-09-02 11:24:14 +00:00
return User.verify_access_token(token) if token else None
@token_auth.error_handler
def token_auth_error(status):
2022-09-02 11:24:14 +00:00
error = (Forbidden if status == 403 else Unauthorized)()
return {
'code': error.code,
'message': error.name,
'description': error.description,
}, error.code
@basic_auth.get_user_roles
@token_auth.get_user_roles
def get_user_roles(user):
return [user.role.name]