1717logger = logging .getLogger (__name__ )
1818
1919
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+
2026def store_tokens (session , access_token , id_token , refresh_token ):
2127 """Store tokens in the session if enabled in settings."""
2228 if import_from_settings ("OIDC_STORE_ACCESS_TOKEN" , False ):
@@ -25,8 +31,7 @@ def store_tokens(session, access_token, id_token, refresh_token):
2531 if import_from_settings ("OIDC_STORE_ID_TOKEN" , False ):
2632 session ["oidc_id_token" ] = id_token
2733
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 )
3035
3136
3237class OIDCAuthenticationBackend (MozillaOIDCAuthenticationBackend ):
@@ -36,6 +41,40 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
3641 in the User and Identity models, and handles signed and/or encrypted UserInfo response.
3742 """
3843
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+
3978 def get_userinfo (self , access_token , id_token , payload ):
4079 """Return user details dictionary.
4180
0 commit comments