2022-07-27 16:03:14 +02:00
|
|
|
# -*- coding: UTF-8 -*
|
|
|
|
|
|
|
|
"""app.auth.logic.py
|
|
|
|
"""
|
|
|
|
import http
|
|
|
|
|
|
|
|
import flask
|
|
|
|
from flask import g, redirect, request, url_for
|
|
|
|
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
|
|
|
|
import flask_login
|
|
|
|
from app import login
|
2022-08-07 19:56:25 +02:00
|
|
|
from app.scodoc.sco_utils import json_error
|
2022-07-27 16:03:14 +02:00
|
|
|
from app.auth.models import User
|
|
|
|
|
|
|
|
basic_auth = HTTPBasicAuth()
|
|
|
|
token_auth = HTTPTokenAuth()
|
|
|
|
|
|
|
|
|
|
|
|
@basic_auth.verify_password
|
|
|
|
def verify_password(username, password):
|
|
|
|
"""Verify password for this user
|
|
|
|
Appelé lors d'une demande de jeton (normalement via la route /tokens)
|
|
|
|
"""
|
|
|
|
user: User = User.query.filter_by(user_name=username).first()
|
|
|
|
if user and user.check_password(password):
|
|
|
|
g.current_user = user
|
|
|
|
# note: est aussi basic_auth.current_user()
|
|
|
|
return user
|
|
|
|
|
|
|
|
|
|
|
|
@basic_auth.error_handler
|
|
|
|
def basic_auth_error(status):
|
|
|
|
"error response (401 for invalid auth.)"
|
|
|
|
return error_response(status)
|
|
|
|
|
|
|
|
|
|
|
|
@login.user_loader
|
|
|
|
def load_user(uid: str) -> User:
|
|
|
|
"flask-login: accès à un utilisateur"
|
|
|
|
return User.query.get(int(uid))
|
|
|
|
|
|
|
|
|
|
|
|
@token_auth.verify_token
|
|
|
|
def verify_token(token) -> User:
|
|
|
|
"""Retrouve l'utilisateur à partir du jeton.
|
|
|
|
Si la requête n'a pas de jeton, token == "".
|
|
|
|
"""
|
|
|
|
user = User.check_token(token) if token else None
|
|
|
|
if user is not None:
|
|
|
|
flask_login.login_user(user)
|
|
|
|
g.current_user = user
|
|
|
|
return user
|
|
|
|
|
|
|
|
|
|
|
|
@token_auth.error_handler
|
|
|
|
def token_auth_error(status):
|
|
|
|
"Réponse en cas d'erreur d'auth."
|
|
|
|
return error_response(status)
|
|
|
|
|
|
|
|
|
|
|
|
@token_auth.get_user_roles
|
|
|
|
def get_user_roles(user):
|
|
|
|
return user.roles
|
|
|
|
|
|
|
|
|
|
|
|
@login.request_loader
|
|
|
|
def load_user_from_request(req: flask.Request) -> User:
|
|
|
|
"""Custom Login using Request Loader"""
|
|
|
|
# Try token
|
|
|
|
try:
|
|
|
|
auth_type, token = req.headers["Authorization"].split(None, 1)
|
|
|
|
except (ValueError, KeyError):
|
|
|
|
# The Authorization header is either empty or has no token
|
|
|
|
return None
|
|
|
|
if auth_type == "Bearer" and token:
|
|
|
|
return verify_token(token)
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
@login.unauthorized_handler
|
|
|
|
def unauthorized():
|
|
|
|
"flask-login: si pas autorisé, redirige vers page login, sauf si API"
|
|
|
|
if request.blueprint == "api" or request.blueprint == "apiweb":
|
2022-08-07 19:56:25 +02:00
|
|
|
return json_error(http.HTTPStatus.UNAUTHORIZED, "Non autorise (logic)")
|
2022-07-27 16:03:14 +02:00
|
|
|
return redirect(url_for("auth.login"))
|