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

77 lines
2.7 KiB
Python
Raw Normal View History

2017-12-28 10:39:02 +00:00
# Episodes.Community - Community-Driven TV Show Episode Link Sharing Site
# Copyright (C) 2017 Evert "Diamond" Prants <evert@lunasqu.ee>, Taizo "Tsa6" Simpson <taizo@tsa6.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
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