from django.contrib.auth import login from requests import post, get from BaseLib.BaseView import BaseView from Platform import settings from web.models import CustomUser class YandexAuthView(BaseView): required_login = False endpoint = "yandex_auth" def get(self): code = self.request.GET['code'] response = post('https://oauth.yandex.ru/token', data={ 'client_id': '2c5235f2ce5b4665856d15f70aa876f2', 'client_secret': settings.YANDEX_SERVICE_TOKEN, 'grant_type': 'authorization_code', 'code': code }) if response.status_code != 200: raise Exception("Cant access, json: " + str(response.json())) return '/welcome' access_token = response.json().get('access_token') if access_token is None: raise Exception('no access token') return '/welcome' info_response = get('https://login.yandex.ru/info', headers={ 'Authorization': f'OAuth {access_token}' }) if info_response.status_code != 200: raise Exception("Cant access, json: " + str(response.json())) return '/welcome' data = info_response.json() yandex_id = data['id'] if self.request.user.is_authenticated: self.logger.warning('Got yandex_id %s writing to db', yandex_id) self.request.user.yandex_id = yandex_id self.request.user.save() else: self.logger.warning('Got yandex_id %s logging in', yandex_id) user = CustomUser.objects.filter(yandex_id=yandex_id).first() if user is not None: login(self.request, user) return '/profile'