You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
3.1 KiB

  1. from authlib.integrations.base_client import OAuthError
  2. from authlib.integrations.django_client import OAuth
  3. from authlib.oauth2.rfc6749 import OAuth2Token
  4. from django.shortcuts import redirect
  5. from django.utils.deprecation import MiddlewareMixin
  6. from foerderbarometer import settings
  7. from input import views
  8. from input import models
  9. class OAuthMiddleware(MiddlewareMixin):
  10. def __init__(self, get_response=None):
  11. super().__init__(get_response)
  12. self.oauth = OAuth()
  13. def process_request(self, request):
  14. if settings.OAUTH_URL_WHITELISTS is not None:
  15. for w in settings.OAUTH_URL_WHITELISTS:
  16. if request.path.startswith(w):
  17. return self.get_response(request)
  18. def update_token(token, refresh_token, access_token):
  19. request.session['token'] = token
  20. print('oioi')
  21. print('oi token', token)
  22. return None
  23. sso_client = self.oauth.register(
  24. settings.OAUTH_CLIENT_NAME, overwrite=True, **settings.OAUTH_CLIENT, update_token=update_token
  25. )
  26. if request.path.startswith('/oauth/callback'):
  27. print('oi')
  28. self.clear_session(request)
  29. request.session['token'] = sso_client.authorize_access_token(request)
  30. # print('blub', request.session['token'])
  31. models.Extern.username = self.get_current_user(sso_client, request)['username']
  32. if self.get_current_user(sso_client, request) is not None:
  33. redirect_uri = request.session.pop('redirect_uri', None)
  34. if redirect_uri is not None:
  35. return redirect(redirect_uri)
  36. return redirect(views.ExternView)
  37. if request.session.get('token', None) is not None:
  38. current_user = self.get_current_user(sso_client, request)
  39. if current_user is not None:
  40. return self.get_response(request)
  41. # remember redirect URI for redirecting to the original URL.
  42. request.session['redirect_uri'] = request.path
  43. return sso_client.authorize_redirect(request, settings.OAUTH_CLIENT['redirect_uri'])
  44. # fetch current login user info
  45. # 1. check if it's in cache
  46. # 2. fetch from remote API when it's not in cache
  47. @staticmethod
  48. def get_current_user(sso_client, request):
  49. token = request.session.get('token', None)
  50. if token is None or 'access_token' not in token:
  51. return None
  52. if not OAuth2Token.from_dict(token).is_expired() and 'user' in request.session:
  53. return request.session['user']
  54. try:
  55. res = sso_client.get(settings.OAUTH_CLIENT['userinfo_endpoint'], token=OAuth2Token(token))
  56. print('json oi oi' , res.json())
  57. if res.ok:
  58. request.session['user'] = res.json()
  59. return res.json()
  60. except OAuthError as e:
  61. print(e)
  62. return None
  63. @staticmethod
  64. def clear_session(request):
  65. try:
  66. del request.session['user']
  67. del request.session['token']
  68. except KeyError:
  69. pass
  70. def __del__(self):
  71. print('destroyed')