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/>.
|
|
|
|
|
2017-11-13 17:38:51 +00:00
|
|
|
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()
|
2017-11-14 12:56:44 +00:00
|
|
|
matches = usermodel.objects.filter(icy_id=user_info['uuid'])
|
2017-11-13 17:38:51 +00:00
|
|
|
match = None
|
|
|
|
|
|
|
|
if not len(matches):
|
|
|
|
user = usermodel.objects.create_user(
|
|
|
|
username = user_info['username'],
|
|
|
|
email = user_info['email'],
|
2017-11-14 12:56:44 +00:00
|
|
|
icy_id = user_info['uuid'],
|
|
|
|
display_name = user_info['display_name']
|
2017-11-13 17:38:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
if 'privilege' in user_info:
|
|
|
|
priv = user_info['privilege']
|
|
|
|
user.is_superuser = (priv == 5)
|
|
|
|
user.is_staff = (priv > 0)
|
|
|
|
|
|
|
|
user.save()
|
2017-11-14 12:56:44 +00:00
|
|
|
|
2017-11-13 17:38:51 +00:00
|
|
|
match = user
|
|
|
|
else:
|
|
|
|
match = matches[0]
|
|
|
|
|
|
|
|
match.access_token = resp_json['access_token']
|
|
|
|
|
|
|
|
return match
|
|
|
|
return None
|