Give Django admin privileges to a user who login via GitHub and belong to a specific team. The parameters are as per python-social-auth docs https://python-social-auth.readthedocs.io/en/latest/pipeline.html#extending-the-pipeline
Parameters:
Name
Type
Description
Default
uid
int
user id
required
response
Dict
request dictionary
required
details
Dict
user details generated by the backend
required
user
User
Django user model object
required
social
UserSocialAuth
Social auth user model object
required
Returns:
Type
Description
Dict
return a dictionary with the Django User object in it or empty if
defcreate_admin_user(uid:int,response:Dict,details:Dict,user:User,social:UserSocialAuth,*args,**kwargs)->Dict:""" Give Django admin privileges to a user who login via GitHub and belong to a specific team. The parameters are as per python-social-auth docs https://python-social-auth.readthedocs.io/en/latest/pipeline.html#extending-the-pipeline Args: uid: user id response: request dictionary details: user details generated by the backend user: Django user model object social: Social auth user model object Returns: return a dictionary with the Django User object in it or empty if no action are taken """# assume github-org backend, add <if backend.name == 'github-org'># if other backend are implementedadmin_team=settings.SOCIAL_AUTH_GITHUB_ADMIN_TEAMusr=response.get('login','')if(usr!=''andadmin_team!=''anduserandnotuser.is_staffandnotuser.is_superuser):logger.info('Trying to add Django admin privileges to user')# check if github user belong to admin teamorg=settings.SOCIAL_AUTH_GITHUB_ORG_NAMEheader={'Authorization':f"token {response.get('access_token','')}"}url=(f'https://api.github.com/orgs/{org}/teams/{admin_team}'f'/memberships/{usr}')resp=requests.get(url,headers=header)ifresp.ok:# add user to adminuser.is_superuser=Trueuser.is_staff=Trueuser.save()logger.info('Django admin privileges successfully added to user')return{'user':user}logger.info(f'GitHub request failed, reason: {resp.reason}')return{}return{}
defload_github_avatar(response:Dict,social:UserSocialAuth,*args,**kwargs)->Dict:""" Add GitHub avatar url to the extra data stored by social_django app Args: response: request dictionary social: Social auth user model object *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: return a dictionary with the Social auth user object in it or empty if no action are taken """# assume github-org backend, add <if backend.name == 'github-org'># if other backend are implemented# if social and social.get('extra_data', None)# print(vars(social))if'avatar_url'notinsocial.extra_data:logger.info('Adding GitHub avatar url to user extra data')social.extra_data['avatar_url']=response['avatar_url']social.save()return{'social':social}return{}