nalodeni.pirati.cz/keycloak_oidc/auth.py

58 lines
1.5 KiB
Python

import os
import requests
from django.conf import settings
from openid_connect import connect, connect_url
from openid_connect._oidc import OpenIDClient, TokenResponse
class OpenIDClientCustom(OpenIDClient):
def refresh_session(self, refresh_token):
r = requests.post(self.token_endpoint, auth=self.auth, data=dict(
grant_type="refresh_token",
refresh_token=refresh_token
), headers={'Accept': 'application/json'})
if r.status_code != 200:
#r.raise_for_status()
return None
resp = TokenResponse(r.json(), self)
if "scope" in resp._data:
resp.scope = set(self.translate_scope_out(set(resp._data["scope"].split(" "))))
if not hasattr(resp, "scope") or "openid" in resp.scope:
resp.id = self.get_id(resp)
return resp
server = None
def get_server_orig():
global server
if server is not None:
return server
AUTH_URL = os.environ.get("AUTH_URL")
if AUTH_URL:
server = connect_url(AUTH_URL)
else:
server = connect(settings.AUTH_SERVER, settings.AUTH_CLIENT_ID,
settings.AUTH_CLIENT_SECRET,
getattr(settings, 'AUTH_PROTOCOL', None))
return server
def get_server():
global server
if server is not None:
return server
server = OpenIDClientCustom( settings.AUTH_SERVER, settings.AUTH_CLIENT_ID,
settings.AUTH_CLIENT_SECRET)
return server