48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
from flask import request, session
|
|
from requests_oauthlib import OAuth2Session
|
|
from oauthlib.oauth2 import BackendApplicationClient
|
|
from requests.auth import HTTPBasicAuth
|
|
|
|
from config import *
|
|
from helpers import HydraError
|
|
|
|
|
|
class HydraOauth:
|
|
SESSION_KEY = "oauth_state"
|
|
|
|
@staticmethod
|
|
def authorize():
|
|
try:
|
|
hydra = OAuth2Session(HYDRA_CLIENT_ID)
|
|
authorization_url, state = hydra.authorization_url(
|
|
HYDRA_AUTHORIZATION_BASE_URL
|
|
)
|
|
|
|
# State is used to prevent CSRF, keep this for later.
|
|
session[HydraOauth.SESSION_KEY] = state
|
|
|
|
return authorization_url
|
|
except Exception as err:
|
|
raise HydraError(str(err), 500)
|
|
|
|
@staticmethod
|
|
def get_token(state, code):
|
|
try:
|
|
auth = HTTPBasicAuth(HYDRA_CLIENT_ID, HYDRA_CLIENT_SECRET)
|
|
client = BackendApplicationClient(client_id=HYDRA_CLIENT_ID)
|
|
hydra = OAuth2Session(client=client, state=state)
|
|
# hydra = OAuth2Session(
|
|
# client_id=HYDRA_CLIENT_ID,
|
|
# state=state,
|
|
# )
|
|
token = hydra.fetch_token(
|
|
token_url=TOKEN_URL,
|
|
auth=auth,
|
|
code=code,
|
|
client_secret=HYDRA_CLIENT_SECRET,
|
|
)
|
|
|
|
session["hydra_token"] = token
|
|
return token
|
|
except Exception as err:
|
|
raise HydraError(str(err), 500)
|