Coverage for benefits/core/admin/users.py: 98%

40 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-30 22:14 +0000

1import logging 

2 

3from django.conf import settings 

4from django.contrib.auth.models import Group 

5 

6import requests 

7 

8from benefits.core import models 

9 

10 

11logger = logging.getLogger(__name__) 

12 

13 

14GOOGLE_USER_INFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo" 

15 

16 

17def add_google_sso_userinfo(user, request): 

18 token = request.session.get("google_sso_access_token") 

19 if token: 

20 headers = { 

21 "Authorization": f"Bearer {token}", 

22 } 

23 

24 # Request Google user info to get name and email 

25 response = requests.get(GOOGLE_USER_INFO_URL, headers=headers, timeout=settings.REQUESTS_TIMEOUT) 

26 user_data = response.json() 

27 logger.debug(f"Updating user data from Google for user with email: {user_data['email']}") 

28 

29 user.first_name = user_data["given_name"] 

30 user.last_name = user_data["family_name"] 

31 user.username = user_data["email"] 

32 user.email = user_data["email"] 

33 user.save() 

34 else: 

35 logger.warning("google_sso_access_token not found in session.") 

36 

37 

38def add_staff_user_to_group(user, request): 

39 if user.email in settings.GOOGLE_SSO_STAFF_LIST: 

40 staff_group = Group.objects.get(name=settings.STAFF_GROUP_NAME) 

41 staff_group.user_set.add(user) 

42 

43 

44def add_transit_agency_staff_user_to_group(user, request): 

45 user_sso_domain = user.email.split("@")[1] 

46 if user_sso_domain: 46 ↛ exitline 46 didn't return from function 'add_transit_agency_staff_user_to_group' because the condition on line 46 was always true

47 agency = models.TransitAgency.objects.filter(sso_domain=user_sso_domain).first() 

48 if agency is not None and agency.staff_group: 

49 agency.staff_group.user_set.add(user) 

50 

51 

52def is_staff_member(user): 

53 """Determine if a user is a member of the staff group of Benefits 

54 

55 The staff group of Benefits is also called the 'Cal-ITP' group (defined in settings.STAFF_GROUP_NAME) 

56 and it is not to be confused with Django's concept of 'staff' which simply means users that can log in to the admin. 

57 """ 

58 

59 staff_group = Group.objects.get(name=settings.STAFF_GROUP_NAME) 

60 return staff_group.user_set.contains(user) 

61 

62 

63def is_staff_member_or_superuser(user): 

64 """Determine if a user is a member of the staff group of Benefits or if it is a superuser.""" 

65 return user.is_superuser or is_staff_member(user) 

66 

67 

68def pre_login_user(user, request): 

69 logger.debug(f"Running pre-login callback for user: {user.username}") 

70 add_google_sso_userinfo(user, request) 

71 add_staff_user_to_group(user, request) 

72 add_transit_agency_staff_user_to_group(user, request)