This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
Episodes.Community/LandingPage/backends.py
Evert 9f725b4c46
Authentication - Made Django use a custom User model
WARNING! This commit requires you to re-migrate the database from the beginning, because AUTH_USER_MODEL can only be set before the initial migration.
2017-11-14 14:56:44 +02:00

61 lines
1.9 KiB
Python

import requests
import hashlib
import json
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class OAuthBackend(ModelBackend):
def authenticate(self, code=None):
resp = requests.post(
settings.AUTH_TOKEN_ENDPOINT+"token",
data={
'grant_type':'authorization_code',
'code':code,
'redirect_uri':settings.AUTH_REDIRECT_URL,
'client_id':settings.AUTH_CLIENT_ID
},
headers = {
'Authorization':'Basic %s'%settings.AUTH_B64
}
)
resp_json = resp.json()
if 'error' in resp_json:
logging.warn('OAuth server returned an error: %s'%json.dumps(resp_json))
else:
user_info = requests.get(
settings.AUTH_TOKEN_ENDPOINT+"user",
headers = {
'Authorization': 'Bearer ' + resp_json['access_token']
}
).json()
usermodel = get_user_model()
matches = usermodel.objects.filter(icy_id=user_info['uuid'])
match = None
if not len(matches):
user = usermodel.objects.create_user(
username = user_info['username'],
email = user_info['email'],
icy_id = user_info['uuid'],
display_name = user_info['display_name']
)
if 'privilege' in user_info:
priv = user_info['privilege']
user.is_superuser = (priv == 5)
user.is_staff = (priv > 0)
user.save()
match = user
else:
match = matches[0]
match.access_token = resp_json['access_token']
return match
return None