17
17
logger = logging .getLogger (__name__ )
18
18
19
19
20
+ def store_oidc_refresh_token (session , refresh_token ):
21
+ """Store the OIDC refresh token in the session if enabled in settings."""
22
+ if import_from_settings ("OIDC_STORE_REFRESH_TOKEN" , False ):
23
+ session ["oidc_refresh_token" ] = refresh_token
24
+
25
+
20
26
def store_tokens (session , access_token , id_token , refresh_token ):
21
27
"""Store tokens in the session if enabled in settings."""
22
28
if import_from_settings ("OIDC_STORE_ACCESS_TOKEN" , False ):
@@ -25,8 +31,7 @@ def store_tokens(session, access_token, id_token, refresh_token):
25
31
if import_from_settings ("OIDC_STORE_ID_TOKEN" , False ):
26
32
session ["oidc_id_token" ] = id_token
27
33
28
- if import_from_settings ("OIDC_STORE_REFRESH_TOKEN" , False ):
29
- session ["oidc_refresh_token" ] = refresh_token
34
+ store_oidc_refresh_token (session , refresh_token )
30
35
31
36
32
37
class OIDCAuthenticationBackend (MozillaOIDCAuthenticationBackend ):
@@ -36,6 +41,40 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
36
41
in the User and Identity models, and handles signed and/or encrypted UserInfo response.
37
42
"""
38
43
44
+ def __init__ (self , * args , ** kwargs ):
45
+ """
46
+ Initialize the OIDC Authentication Backend.
47
+
48
+ Adds an internal attribute to store the token_info dictionary.
49
+ The purpose of `self._token_info` is to not duplicate code from
50
+ the original `authenticate` method.
51
+ This won't be needed after https://github.com/mozilla/mozilla-django-oidc/pull/377
52
+ is merged.
53
+ """
54
+ super ().__init__ (* args , ** kwargs )
55
+ self ._token_info = None
56
+
57
+ def get_token (self , payload ):
58
+ """
59
+ Return token object as a dictionary.
60
+
61
+ Store the value to extract the refresh token in the `authenticate` method.
62
+ """
63
+ self ._token_info = super ().get_token (payload )
64
+ return self ._token_info
65
+
66
+ def authenticate (self , request , ** kwargs ):
67
+ """Authenticates a user based on the OIDC code flow."""
68
+ user = super ().authenticate (request , ** kwargs )
69
+
70
+ if user is not None :
71
+ # Then the user successfully authenticated
72
+ store_oidc_refresh_token (
73
+ request .session , self ._token_info .get ("refresh_token" )
74
+ )
75
+
76
+ return user
77
+
39
78
def get_userinfo (self , access_token , id_token , payload ):
40
79
"""Return user details dictionary.
41
80
0 commit comments