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.

87 lines
3.3 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. # added this if clause to get the landing page before oauth
  15. if request.path == '/':
  16. return self.get_response(request)
  17. if settings.OAUTH_URL_WHITELISTS is not None:
  18. for w in settings.OAUTH_URL_WHITELISTS:
  19. if request.path.startswith(w):
  20. return self.get_response(request)
  21. def update_token(token, refresh_token, access_token):
  22. request.session['token'] = token
  23. print('oioi')
  24. print('oi token', token)
  25. return None
  26. sso_client = self.oauth.register(
  27. settings.OAUTH_CLIENT_NAME, overwrite=True, **settings.OAUTH_CLIENT, update_token=update_token
  28. )
  29. if request.path.startswith('/oauth/callback'):
  30. print('oi')
  31. self.clear_session(request)
  32. request.session['token'] = sso_client.authorize_access_token(request)
  33. # print('blub', request.session['token'])
  34. models.Extern.username = self.get_current_user(sso_client, request)['username']
  35. if self.get_current_user(sso_client, request) is not None:
  36. redirect_uri = request.session.pop('redirect_uri', None)
  37. if redirect_uri is not None:
  38. return redirect(redirect_uri)
  39. return redirect(views.ExternView)
  40. if request.session.get('token', None) is not None:
  41. current_user = self.get_current_user(sso_client, request)
  42. if current_user is not None:
  43. return self.get_response(request)
  44. # remember redirect URI for redirecting to the original URL.
  45. request.session['redirect_uri'] = request.path
  46. return sso_client.authorize_redirect(request, settings.OAUTH_CLIENT['redirect_uri'])
  47. # fetch current login user info
  48. # 1. check if it's in cache
  49. # 2. fetch from remote API when it's not in cache
  50. @staticmethod
  51. def get_current_user(sso_client, request):
  52. token = request.session.get('token', None)
  53. if token is None or 'access_token' not in token:
  54. return None
  55. if not OAuth2Token.from_dict(token).is_expired() and 'user' in request.session:
  56. return request.session['user']
  57. try:
  58. res = sso_client.get(settings.OAUTH_CLIENT['userinfo_endpoint'], token=OAuth2Token(token))
  59. print('json oi oi' , res.json())
  60. if res.ok:
  61. request.session['user'] = res.json()
  62. return res.json()
  63. except OAuthError as e:
  64. print(e)
  65. return None
  66. @staticmethod
  67. def clear_session(request):
  68. try:
  69. del request.session['user']
  70. del request.session['token']
  71. except KeyError:
  72. pass
  73. def __del__(self):
  74. print('destroyed')