def verify_telegram_authentication(bot_token, request_data): # Taken from https://github.com/dmytrostriletskyi/django-telegram-login/blob/develop/django_telegram_login/authentication.py # https://core.telegram.org/widgets/login#checking-authorization request_data = request_data.copy() received_hash = request_data['hash'] auth_date = request_data['auth_date'] request_data.pop('hash', None) request_data_alphabetical_order = sorted(request_data.items(), key=lambda x: x[0]) data_check_string = [] for data_pair in request_data_alphabetical_order: key, value = data_pair[0], data_pair[1] data_check_string.append(key + '=' + value) data_check_string = '\n'.join(data_check_string) secret_key = hashlib.sha256(bot_token.encode()).digest() _hash = hmac.new(secret_key, msg=data_check_string.encode(), digestmod=hashlib.sha256).hexdigest() unix_time_now = int(time.time()) unix_time_auth_date = int(auth_date) if unix_time_now - unix_time_auth_date > ONE_DAY_IN_SECONDS: raise AuthForbidden( 'Authentication data is outdated. Authentication was received more than day ago.' ) if _hash != received_hash: raise AuthForbidden( 'This is not a Telegram data. Hash from recieved authentication data does not match' 'with calculated hash based on bot token.' )
def save_user_profile(backend, user, response, *args, **kwargs): print(response) if backend.name == "google-oauth2": if 'gender' in response.keys(): if response['gender'] == 'male': user.shopuserprofile.gender = ShopUserProfile.MALE else: user.shopuserprofile.gender = ShopUserProfile.FEMALE if 'tagline' in response.keys(): user.shopuserprofile.tagline = response['tagline'] if 'aboutMe' in response.keys(): user.shopuserprofile.aboutMe = response['aboutMe'] if 'picture' in response.keys(): pass if 'ageRange' in response.keys(): minAge = response['ageRange']['min'] if int(minAge) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') user.save() elif backend.name == 'vk-oauth2': api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about')), access_token=response['access_token'], v='5.92')), None ) ) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data.get('sex'): user.shopuserprofile.gender = \ ShopUserProfile.MALE if data['sex'] == 2 else ShopUserProfile.FEMALE if data.get('about'): user.shopuserprofile.aboutMe = data['about'] if data.get('bdate'): bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.save()
def downcast_social_user(backend, user=None, *args, **kwargs): """Pipeline function to be used with PSA""" if user is None: # Only allow users who have been previously added to db raise AuthForbidden(backend) downcasted_user = downcast_user_type(user) if downcasted_user == user: raise AuthForbidden(backend) # Don't allow CustomUser base model users return {"user": downcasted_user}
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = f"https://api.vk.com/method/users.get?fields=bdate,sex,about,photo_max&v=5.131&access_token={response['access_token']}" vk_response = requests.get(api_url) if vk_response != 200: return vk_data = vk_response.json()['response'][0] if vk_data['sex']: if vk_data['sex'] == 2: user.userprofile.gender = UserProfile.MALE elif vk_data['sex'] == 1: user.userprofile.gender = UserProfile.FEMALE if vk_data['about']: user.userprofile.about_me = vk_data['about'] if vk_data['bdate']: b_date = datetime.strptime(vk_data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - b_date.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode( OrderedDict(fields=','.join(('bdate', 'sex', 'about')), access_token=response['access_token'], v='5.92')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex']: user.shopuserprofile.gender = ShopUserProfile.MALE if data[ 'sex'] == 2 else ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 100: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.save()
def save_profile(backend, user, response, *args, **kwargs): print(response['picture']) if backend.name == "google-oauth2": if 'gender' in response.keys(): if response['gender'] == 'male': user.growuserprofile.gender = GrowUserProfile.MALE else: user.growuserprofile.gender = GrowUserProfile.FEMALE if 'scope' in response.keys(): user.growuserprofile.url_user = response['scope'] if 'locale' in response.keys(): user.growuserprofile.language_user = response['locale'] if 'picture' in response.keys(): url = response['picture'] user.avatar_user = url if 'ageRange' in response.keys(): minAge = response['ageRange']['min'] if int(minAge) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') else: user.growuserprofile.user_age = response['ageRange']['min'] user.save() # user.growuserprofile.save()
def save_user_profile(backend, user, response, *args, **kwargs): print(response) if backend.name == "google-oauth2": if 'gender' in response.keys(): if response['gender'] == 'male': user.shopclientprofile.gender = ShopClientProfile.MALE else: user.shopclientprofile.gender = ShopClientProfile.FEMALE if 'tagline' in response.keys(): user.shopclientprofile.tagline = response['tagline'] if 'aboutMe' in response.keys(): user.shopclientprofile.aboutMe = response['aboutMe'] if 'picture' in response.keys(): if not user.avatar: url = response['picture'] user.avatar.save(f'avatar_{user.username}.jpg', ContentFile(urlopen(url).read())) if 'ageRange' in response.keys(): min_age = response['ageRange']['min'] if int(min_age) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = f"https://api.vk.com/method/users.get?fields=bdate,sex,about,city,photo_max_orig&access_token={response['access_token']}&v=5.92" resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] print(data) if data['sex']: if data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE elif data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE if data['about']: user.shopuserprofile.about_me = data['about'] if data['bdate']: bdate = datetime.datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = datetime.datetime.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') if data['photo_max_orig']: photo = requests.get(data['photo_max_orig']) if photo.status_code == 200: photoname = f'/users_avatars/{user.pk}.jpg' with open(f'media/{photoname}', 'wb') as avatar: avatar.write(photo.content) user.avatar = photoname user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name == 'google-oauth2': keys = response.keys() if 'gender' in keys: if response['gender'] == 'male': user.profile.gender = ShopUserProfile.MALE else: user.profile.gender = ShopUserProfile.FEMALE if 'tagline' in keys: user.profile.tags_line = response['tagline'] if 'aboutMe' in keys: user.profile.tags_line = response['aboutMe'] if 'ageRange' in keys: min_age = response['ageRange']['min'] if int(min_age) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') # else: # raise AuthForbidden('social_core.backends.google.GoogleOAuth2') if 'picture' in keys: img = request.urlopen(response['picture']) io = BytesIO(img.read()) user.avatar.save(f'{user.username}_avatar.jpg', File(io)) user.save()
def has_existing_account(backend, details, response, *args, **kwargs): user, email = (kwargs.get('user', None), details.get('email', None)) # Associations for anonymous user must match an existing email if user is None and not get_user_model().objects.filter(email=email).exists(): raise AuthForbidden(backend)
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name == "google-oauth2": print(f'GOOGLE answer: {response.keys()}') print(f'profile:{response["profile"]}') print(f'picture:{response["picture"]}') if 'gender' in response.keys(): if response['gender'] == 'male': user.shopuserprofile.gender = ShopUserProfile.MALE else: user.shopuserprofile.gender = ShopUserProfile.FEMALE if 'tagline' in response.keys(): user.shopuserprofile.tagline = response['tagline'] if 'aboutMe' in response.keys(): user.shopuserprofile.about_me = response['aboutMe'] if 'ageRange' in response.keys(): minAge = response['ageRange']['min'] if int(minAge) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') user.save() return
def save_user_profile(backend, user, response, *args, **kwargs): print(backend.name) if backend.name == "google-oauth2": # print(response.keys()) for key, val in response.items(): print(f'{key}: {val}') if 'gender' in response.keys(): if response['gender'] == 'male': user.shopuserprofile.gender = 'M' else: user.shopuserprofile.gender = 'W' print(response['gender']) if 'tagline' in response.keys(): print(response['tagline']) user.shopuserprofile.tagline = response['tagline'] if 'aboutMe' in response.keys(): print(response['aboutMe']) user.shopuserprofile.aboutMe = response['aboutMe'] if 'ageRange' in response.keys(): minAge = response['ageRange']['min'] print(response['ageRange']) if int(minAge) < 18: user.delete() raise AuthForbidden('social_core.backends.google.GoogleOAuth2') user.save() return
def check_user_exists(backend, details, uid, user=None, *args, **kwargs): email = details.get('email', '') exists = get_user_model().objects.filter(email=email, is_staff=True).exists() if not exists: raise AuthForbidden(backend)
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name == "google-oauth2": if 'gender' in response.keys(): if response['gender'] == 'male': user.userprofile.gender = 'M' else: user.userprofile.gender = 'W' if 'tagline' in response.keys(): user.userprofile.tag = response['tagline'] if 'url' in response.keys(): user.userprofile.about = response['url'] if 'language' in response.keys(): if user.userprofile.about: user.userprofile.about += ('\n' + response['language']) else: user.userprofile.about = response['language'] if 'ageRange' in response.keys(): minAge = response['ageRange']['min'] print(minAge) if int(minAge) < 18: user.delete() raise AuthForbidden( 'social_core.backends.google.GoogleOAuth2') user.save() return
def auth_allowed(strategy, details, backend, user=None, *args, **kwargs): email = details.get("email") if email: if not OrganizationDomain.objects.filter( domain=email.split("@", 1)[1].lower() ).exists(): raise AuthForbidden(backend)
def check_verified_email(strategy, is_signup, backend, **kwargs): if is_signup: account_verified_email = strategy.session_get('account_verified_email', None) if account_verified_email is None: msg = _("Can not sign up without verified email") raise AuthForbidden(backend, msg) else: return {'account_verified_email': account_verified_email}
def user_role(backend, user, response, *args, **kwargs): from social_core.exceptions import AuthForbidden token = response.get('access_token') url = settings.SOCIAL_AUTH_ARCGIS_URL target = GIS(url=url, token=token) if target.properties.user.role == settings.ARCGIS_USER_ROLE: return {'is_new': True} else: raise AuthForbidden(backend)
def refuse_alliance_id(backend, uid, *args, **kwargs): if settings.VALID_ALLIANCE_IDS is None: return data = requests.get( 'https://esi.tech.ccp.is/latest/characters/%d/?datasource=tranquility' % uid).json() if data.get('alliance_id', -1) not in settings.VALID_ALLIANCE_IDS: raise AuthForbidden(backend, 'Forbidden alliance ID.')
def nflrc_auth_allowed(backend, details, response, *args, **kwargs): """ If auth_allowed returns a user object, set the user variable for the pipeline. A valid user variable is processed to determine if a social (google) association needs to be created. See nflrc_social for the next op in the pipeline. """ nflrc_user = auth_allowed(response, details) if not nflrc_user: raise AuthForbidden(backend) else: return {'user': nflrc_user}
def save_user_profile_vk(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = urlunparse(('https', 'api.vk.com', '/method/users.get', None, urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about', 'photo_200', 'domain')), access_token=response['access_token'], v='5.124')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex']: if data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE elif data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE if data['about']: user.shopuserprofile.about_me = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.age = age if data['photo_200']: get_photo = requests.get(data['photo_200']) with open(f'{BASE_DIR}/media/users_avatars/{user.id}.jpg', 'wb') as photo: photo.write(get_photo.content) user.avatar = f'users_avatars/{user.id}.jpg' if data['domain']: user.shopuserprofile.social_page = f"https://vk.com/{data['domain']}" # api_request = get_api_vk(response, 'account.getInfo', 'fields') # print(api_request) # resp = requests.get(api_request) # print(resp) # if data_lang['lang']: # user.shopuserprofile.localization = data_lang['lang'] user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return # print(response) """ response {'access_token': 'aa8e63b982e3a5dc60', 'expires_in': 86400, 'user_id': 111111, 'email': '*****@*****.**', 'first_name': 'name', 'id': 11111, 'last_name': 'surname', 'screen_name': 'soloninin_anton', 'nickname': '', 'photo': 'url', 'user_photo': 'url'} """ # access_token = response['access_token'] # api_url = f"https://api.vk.com/method/users.get/?fields=bdate,about,sex&access_token={access_token}&v=5.92" api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode( OrderedDict(fields=','.join(('bdate', 'sex', 'about')), access_token=response['access_token'], v='5.92')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json() # print(data) """ data = {'response': [{'first_name': 'name', 'id': 1111, 'last_name': 'sur name', 'can_access_closed': True, 'is_closed': False, 'sex': 2, 'bdate': '23.02.2000', 'about': '1'}]} """ data = data['response'][0] user.email = response['email'] if data['sex']: if data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE elif data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return print(f'============response=============>>>>>>>>{response}<<<<<<<<<') # api_url = f"https://api.vk.com/method/users.get/fields=bdate, sex, about,sex&access_token={response['access_token']}" api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode( OrderedDict(fields=','.join( ('bdate', 'sex', 'about', 'photo_400_orig')), access_token=response['access_token'], v='5.92')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE elif data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.datetime.strptime(data['bdate'], '%d.%m.%Y').date() if data['photo_400_orig']: result = urllib.request.urlretrieve( data['photo_400_orig'], os.path.join(BASE_DIR + '/media/users_avatars', f'{user.pk}.jpg')) print(f'=======result======{result}==') # user.avatar='/media/users_avatars/' + result[0].rsplit('/', 1)[-1] user.avatar = f'/media/users_avatars/{user.pk}.jpg' user.save() print(f'=====----==user.avatar======{user.avatar}==') # result = urlretrieve(self.image_url, os.path.join(BASE_DIR + '/media/users_avatars',f'{user.pk}.jpg')) # self.original = '/media/users_avatars/' + result[0].rsplit('/', 1)[-1] # self.save() # (data['photo_400_orig'],f'/media/users_avatars/{user.pk}.jpg') print(data['photo_400_orig']) age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.save()
def create_user_if_allowed(strategy, details, backend, user=None, *args, **kwargs): """Create new Users if the domain of the email address is whitelisted.""" if user is None: if not email_address_is_whitelisted(details.get('email')): # TODO: Create a middleware to gracefully handle this. raise AuthForbidden(backend) return create_user(strategy, details, backend, *args, **kwargs)
def save_user_profile(backend, user, response, *args, **kwargs): languages = { '0': 'русский', '1': 'украинский', '2': 'белорусский', '3': 'английский', '4': 'испанский', '5': 'финский', '6': 'немецкий', '7': 'итальянский', } if backend.name != 'vk-oauth2': return api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode( OrderedDict(fields=','.join( ('bdate', 'sex', 'about', 'lang', 'domain')), access_token=response['access_token'], v='5.92')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex']: user.shopuserprofile.gender = ShopUserProfile.MALE if data[ 'sex'] == 2 else ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year user.age = age if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') if data['domain']: user.shopuserprofile.vk_addr = f'https://vk.com/{data["domain"]}' if data['language'] and data['language'] in languages.keys(): user.shopuserprofile.vk_lang = languages[data['language']] user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name == 'vk-oauth2': api_url = urlunparse( ('https', 'api.vk.com', '/method/users.get', None, urlencode( OrderedDict(fields=','.join(('bdate', 'sex', 'about')), access_token=response['access_token'], v='5.92')), None)) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] print(data) if data['sex']: user.shopuserprofile.gender = ShopUserProfile.MALE if data[ 'sex'] == 2 else ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() # TODO # месяц тоже нужно учитывать, при этом учитывать страну # так как в некоторых странах первым идет месяц затем день 12.24.1985 - 24 декабря # по хорошему день тоже нужно проверять # вроде как страну не всегда можно узнать, значит принимаем по дефолтку дд.мм.гг. age = timezone.now().date().year - bdate.year if age < 1800: user.delete() # raise AuthForbidden('social_core.backends.vk.VKOAuth2') error_msg = AuthForbidden("social_core.backends.vk.VKOAuth2") person = data["first_name"] return HttpResponse(f'<h3>Dear {person}:</h3>' f'<h4>{error_msg}</h4>') else: # явное лучше неявного user.age = age user.save() elif backend.name == 'google-oauth2': pass return
def enforce_slack_team(user, response, backend, details, *args, **kwargs): """ If using slack sign in, make sure users are logging in using the specified slack team. """ # TODO: make this a generic check for all the supported social # sign in methods if backend.name == "slack": slack_team = response.get('team', {}) slack_team_id = slack_team.get('id') if not slack_team or not slack_team_id: return if slack_team_id != settings.SOCIAL_AUTH_SLACK_TEAM: raise AuthForbidden(backend)
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = f"https://api.vk.com/method/users.get?fields=bdate,sex,about,photo_max&access_token={response['access_token']}&v=5.92" # api_url = urlunparse(('https', # 'api.vk.com', # '/method/users.get', # None, # urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about')), access_token=response['access_token'], v='5.92')), # None # )) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] print(data) if data['sex']: if data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE elif data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE if data['about']: user.shopuserprofile.about_me = data['about'] if data['photo_max']: # url = data['photo_max'] # img = urllib.request.urlopen(url).read() photo = requests.get(data['photo_max']) if photo.status_code == 200: photo_name = f"/users_avatars/{user.username}.jpg" with open(f"media/{photo_name}", "wb") as avatar: avatar.write(photo.content) user.avatar = photo_name if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = int((date.today() - bdate).days / 365) if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') else: user.shopuserprofile.user.age = age user.save()
def _check_entitlements(self, idp, attributes): """ Check if we require the presence of any specific eduPersonEntitlement. raise AuthForbidden if the user should not be authenticated, or do nothing to allow the login pipeline to continue. """ if "requiredEntitlements" in idp.conf: entitlements = attributes.get(OID_EDU_PERSON_ENTITLEMENT, []) for expected in idp.conf['requiredEntitlements']: if expected not in entitlements: log.warning( "SAML user from IdP %s rejected due to missing eduPersonEntitlement %s", idp.name, expected) raise AuthForbidden(self)
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = urlunparse(('https', 'api.vk.com', '/method/users.get', None, urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about', 'country', 'photo_200')), access_token=response['access_token'], v='5.92')), None )) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE elif data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') data_country = data['country'] if data_country['title'] == 'Россия': # и так далее с другими языками user.shopuserprofile.language = 'Русский' if data['id']: user.shopuserprofile.url_address = f'https://vk.com/id{data["id"]}' if data['photo_200']: urllib.request.urlretrieve( data['photo_200'], os.path.join(settings.MEDIA_ROOT, 'users_avatars', f'{user.pk}.jpg') ) user.avatar = os.path.join('users_avatars', f'{user.pk}.jpg') user.save()
def save_user_profile(backend, user, response, *args, **kwargs): if backend.name != 'vk-oauth2': return api_url = urlunparse(('https', 'api.vk.com', '/method/users.get', None, urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about', 'photo_200_orig')), access_token=response['access_token'], v='5.92' )), None, )) resp = requests.get(api_url) if resp.status_code != 200: return data = resp.json()['response'][0] if data['sex']: if data['sex'] == 2: user.shopuserprofile.gender = ShopUserProfile.MALE elif data['sex'] == 1: user.shopuserprofile.gender = ShopUserProfile.FEMALE if data['about']: user.shopuserprofile.aboutMe = data['about'] if data['bdate']: bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date() age = timezone.now().date().year - bdate.year if age < 18: user.delete() raise AuthForbidden('social_core.backends.vk.VKOAuth2') user.age = age if data['photo_200_orig']: url = data['photo_200_orig'] response = requests.get(url, stream=True) print(url) print(response) with open(f'{settings.MEDIA_ROOT}/user_avatars/{user.id}.png', 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) user.avatar = f'{settings.MEDIA_ROOT}/user_avatars/{user.id}.png' user.save()