dashboard/areas/auth/auth.py
2022-02-10 13:04:54 +01:00

52 lines
1.4 KiB
Python

from flask import jsonify, request
from flask_jwt_extended import create_access_token
from flask_cors import cross_origin
from datetime import timedelta
from areas import api_v1
from config import *
from helpers import HydraOauth, BadRequest, KratosApi
@api_v1.route("/login", methods=["POST"])
@cross_origin()
def login():
authorization_url = HydraOauth.authorize()
return jsonify({"authorizationUrl": authorization_url})
@api_v1.route("/hydra/callback")
@cross_origin()
def hydra_callback():
state = request.args.get("state")
code = request.args.get("code")
if state == None:
raise BadRequest("Missing state query param")
if code == None:
raise BadRequest("Missing code query param")
token = HydraOauth.get_token(state, code)
user_info = HydraOauth.get_user_info()
# Match Kratos identity with Hydra
identities = KratosApi.get("/identities")
identity = None
for i in identities.json():
if i["traits"]["email"] == user_info["email"]:
identity = i
access_token = create_access_token(
identity=token, expires_delta=timedelta(days=365)
)
return jsonify(
{
"accessToken": access_token,
"userInfo": {
"id": identity["id"],
"email": user_info["email"],
"name": user_info["name"],
"preferredUsername": user_info["preferred_username"],
},
}
)