Coverage for apps/comments_views/journal/auth.py: 91%

20 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-05-19 19:20 +0000

1from mozilla_django_oidc.auth import OIDCAuthenticationBackend 

2 

3from .models import OIDCUser 

4 

5 

6class customOIDCAuthenticationBackend(OIDCAuthenticationBackend): 

7 """ 

8 Override the default OIDC authentication backend provided by mozilla-django-oidc. 

9 We create an OIDCUser object on the fly, without persisting it in the database. 

10 """ 

11 

12 def get_user(self, user_id): 

13 """Returns a dummy OIDCUser object.""" 

14 return OIDCUser(id=-1, pk=-1, username="temp_username", password="***") 

15 

16 def filter_users_by_claims(self, claims): 

17 # This method is used to match incoming OIDC claims to the user DB. 

18 # We force the creation of a new user object when connecting with OIDC. 

19 return self.UserModel.objects.none() 

20 

21 def create_user(self, claims): 

22 # We don't use the `create_user` method of the OIDCAuthenticationBackend 

23 # because it automatically creates and saves a new user in database. 

24 # user = super().create_user(claims) 

25 # Instead we create a custom User object 

26 user = OIDCUser(id=-1, pk=-1, username="temp_username", password="***") 

27 user.populate_fields(claims) 

28 

29 # For user connecting through OIDC, we set a specific (small) session age. 

30 # We do this because we don't want to check regularly that the delivered 

31 # ID token is still valid (proper way to do things in OIDC configuration). 

32 # We will just force the user to authenticate again after the below time 

33 # in seconds has passed. 

34 self.request.session.set_expiry(8 * 60 * 60) 

35 

36 # Store the meaningful user data (claims) directly in the session 

37 self.request.session["oidc_user_data"] = claims 

38 

39 return user 

40 

41 # This should never be called as we don't persist the user in the database. 

42 # The user object should be created on every request with the above method. 

43 def update_user(self, user: OIDCUser, claims): 

44 user.populate_fields(claims) 

45 # Store the meaningful user data (claims) directly in the session 

46 if "oidc_user_data" in self.request.session: 46 ↛ 51line 46 didn't jump to line 51, because the condition on line 46 was never false

47 self.request.session["oidc_user_data"].update(claims) 

48 self.request.session.save() 

49 # Should not happen ? 

50 else: 

51 self.request.session["oidc_user_data"] = claims 

52 

53 return user