2022-01-19 09:16:22 +01:00
|
|
|
from flask import jsonify, request
|
2021-09-27 12:03:35 +02:00
|
|
|
from flask_jwt_extended import create_access_token
|
|
|
|
from flask_cors import cross_origin
|
2022-01-18 10:48:18 +01:00
|
|
|
from datetime import timedelta
|
2021-09-27 12:03:35 +02:00
|
|
|
|
2021-10-28 16:09:10 +02:00
|
|
|
from areas import api_v1
|
2022-01-18 10:48:18 +01:00
|
|
|
from config import *
|
2022-02-10 13:04:54 +01:00
|
|
|
from helpers import HydraOauth, BadRequest, KratosApi
|
2021-09-27 12:03:35 +02:00
|
|
|
|
|
|
|
|
2022-01-18 10:48:18 +01:00
|
|
|
@api_v1.route("/login", methods=["POST"])
|
2021-09-27 12:03:35 +02:00
|
|
|
@cross_origin()
|
|
|
|
def login():
|
2022-01-18 10:48:18 +01:00
|
|
|
authorization_url = HydraOauth.authorize()
|
|
|
|
return jsonify({"authorizationUrl": authorization_url})
|
|
|
|
|
2021-09-27 12:03:35 +02:00
|
|
|
|
2022-01-18 10:48:18 +01:00
|
|
|
@api_v1.route("/hydra/callback")
|
|
|
|
@cross_origin()
|
|
|
|
def hydra_callback():
|
2022-01-19 09:16:22 +01:00
|
|
|
state = request.args.get("state")
|
2022-01-20 07:40:11 +01:00
|
|
|
code = request.args.get("code")
|
2022-01-19 09:16:22 +01:00
|
|
|
if state == None:
|
|
|
|
raise BadRequest("Missing state query param")
|
|
|
|
|
2022-01-20 07:40:11 +01:00
|
|
|
if code == None:
|
|
|
|
raise BadRequest("Missing code query param")
|
|
|
|
|
|
|
|
token = HydraOauth.get_token(state, code)
|
2022-02-10 09:43:15 +01:00
|
|
|
user_info = HydraOauth.get_user_info()
|
2022-02-10 13:04:54 +01:00
|
|
|
# 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
|
2022-02-10 09:43:15 +01:00
|
|
|
|
2022-01-18 10:48:18 +01:00
|
|
|
access_token = create_access_token(
|
|
|
|
identity=token, expires_delta=timedelta(days=365)
|
|
|
|
)
|
2021-09-27 12:03:35 +02:00
|
|
|
|
2022-02-10 09:43:15 +01:00
|
|
|
return jsonify(
|
|
|
|
{
|
|
|
|
"accessToken": access_token,
|
|
|
|
"userInfo": {
|
2022-02-10 13:04:54 +01:00
|
|
|
"id": identity["id"],
|
2022-02-10 09:43:15 +01:00
|
|
|
"email": user_info["email"],
|
|
|
|
"name": user_info["name"],
|
|
|
|
"preferredUsername": user_info["preferred_username"],
|
|
|
|
},
|
|
|
|
}
|
|
|
|
)
|