oauth_utils.py 1012 Bytes
Newer Older
Martin Lehoux's avatar
Martin Lehoux committed
1
import requests
Martin Lehoux's avatar
Martin Lehoux committed
2
from core.models import User
Martin Lehoux's avatar
Martin Lehoux committed
3 4 5


def find_or_create_user(access_token, access_token_payload):
Martin Lehoux's avatar
Martin Lehoux committed
6
    data = access_token_payload['user']
Martin Lehoux's avatar
Martin Lehoux committed
7
    try:
8 9 10 11 12
        user = User.objects.get(username=data['login'])
    except User.DoesNotExist:
        data = requests.get("https://auth.viarezo.fr/api/user/show/me", headers={
            'Authorization': "Bearer {access_token}".format(access_token=access_token)
        }).json()
Martin Lehoux's avatar
Martin Lehoux committed
13 14
        if data['personType'] not in ['STUDENT_SUPELEC', 'STUDENT_CENTRALE', 'STUDENT_CENTRALESUPELEC']:
            raise Exception('Permission denied')
15 16 17 18
        user = User(
            username=data['login'],
            first_name=data['firstName'],
            last_name=data['lastName'],
Martin Lehoux's avatar
typo  
Martin Lehoux committed
19
            promo=data['promo'],
20
            photoPath="https://auth.viarezo.fr/media/"+data['photo']
Martin Lehoux's avatar
Martin Lehoux committed
21 22
        )
        user.save()
Martin Lehoux's avatar
Martin Lehoux committed
23 24 25 26
        if "ViaRézo(wo)man" in data['roles']:
            user.is_staff = True
            user.is_superuser = True
            user.save()
Martin Lehoux's avatar
Martin Lehoux committed
27
    return user