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 from .models import ExternalUser 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(externaluser__icy_id=user_info['uuid']) match = None if not len(matches): user = usermodel.objects.create_user( username = user_info['username'], email = user_info['email'], ) if 'privilege' in user_info: priv = user_info['privilege'] user.is_superuser = (priv == 5) user.is_staff = (priv > 0) user.save() user.externaluser = ExternalUser( user = user, icy_id = user_info['uuid'], display_name = user_info['display_name'] ) user.externaluser.save() match = user else: match = matches[0] match.access_token = resp_json['access_token'] return match return None