def login(request): if request.user.is_authenticated(): return redirect('index') context = dict() return_path = request.META.get('HTTP_REFERER', '/') shortcut = lambda: render(request, 'login.html', context) if request.method == 'GET': if 'code' in request.GET: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, reverse('login')) except vkontakte.AuthError as e: messages.warning(request, 'Ошибка авторизации') return shortcut() try: user = User.objects.get(vkuserid=user_id) backend = auth.get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) auth.login(request, user) try: next = request.GET.__getitem__('next') return redirect(next) except KeyError: print return_path.rsplit('/', 1)[1] if return_path.rsplit('/', 1)[1] != 'login': return redirect(return_path) else: return redirect('index') except User.DoesNotExist: messages.warning(request, 'Такой пользователь не найден') return shortcut() if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): email, password = form.cleaned_data['email'], form.data['password'] user = auth.authenticate(username=email, password=password) if not user: messages.warning(request, "Пользователь не найден!") context['form'] = form return shortcut() else: auth.login(request, user) try: next = request.GET.__getitem__('next') return redirect(next) except KeyError: if return_path.rsplit('/', 1)[1] != 'login': return redirect(return_path) else: return redirect('index') else: messages.warning(request, "Введенные данные некорректны!") context['form'] = form return shortcut() context['form'] = UserLoginForm return shortcut()
def user_update_view(request): user = User.objects.get(email=request.user.email) form = UserUpdateForm(request.POST or None, instance=user) if 'code' in request.GET: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, reverse('user_update_view')) except vkontakte.AuthError as e: messages.warning(request, u'Ошибка OAUTH авторизации {}'.format(e), extra_tags='integration') return redirect('user_update_view') try: user = User.objects.get(vkuserid=user_id) messages.warning(request, 'Этот аккаунт ВКонтакте уже связан с профилем', extra_tags='integration') return redirect('user_update_view') except User.DoesNotExist: user = User.objects.get(email=request.user.email) user.vkuserid = user_id user.save() messages.success(request, "Профиль ВКонтакте прикреплен", extra_tags='integration') return redirect('user_update_view') elif request.POST: if form.is_valid(): form.save() messages.success(request, "Успешно сохранено!", extra_tags='info') return redirect('user_update_view') else: messages.warning(request, "Некорректные данные", extra_tags='info') return render(request, 'user_update.html', {'form': form, 'pass_form': ChangePasswordForm})
def login_view(request): if request.user.is_authenticated(): return redirect('index_view') shortcut = lambda: render(request, 'login.html', {"form": form}) return_path = request.META.get('HTTP_REFERER', '/') # regular email auth if request.method == "POST": form = UserLoginForm(request.POST or None) if form.is_valid: email = request.POST.get('email', '') password = request.POST.get('password', '') user = auth.authenticate(username=email, password=password) if user: if user.is_active: auth.login(request, user) return redirect(return_path) else: messages.warning(request, "Ваш профиль не активен, проверьте почтовый ящик!") return shortcut() else: messages.warning(request, "Введенные данные неверны!") return shortcut() else: messages.warning(request, "Введенные данные некорректны!") return shortcut() # vk return to this page with code elif 'code' in request.GET: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, reverse('login_view')) except vkontakte.AuthError as e: messages.warning(request, u'Ошибка OAUTH авторизации {}'.format(e)) return redirect(return_path) try: user = User.objects.get(vkuserid=user_id) user.last_login = timezone.now() user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' auth.login(request, user) return redirect(return_path) except User.DoesNotExist: messages.warning(request, 'Такой пользователь не найден') return redirect(return_path) else: form = UserLoginForm(request) return shortcut()
def login_view(request): if request.user.is_authenticated(): return redirect('index_view') shortcut = lambda: render(request, 'login.html', {"form": form}) return_path = request.META.get('HTTP_REFERER', '/') if request.method == "POST": form = UserLoginForm(request.POST or None) if form.is_valid: email = request.POST.get('email', '') password = request.POST.get('password', '') user = auth.authenticate(username=email, password=password) # TODO: добавить условия, при которых юзер не может залогиниться if user: if not user.banned: auth.login(request, user) return redirect(return_path) else: messages.warning(request, "Ваш профиль забанен!") return shortcut() else: messages.warning(request, "Введенные данные неверны!") return shortcut() else: messages.warning(request, "Введенные данные некорректны!") return shortcut() elif 'code' in request.GET: try: state = request.GET['state'] source = 'facebook' except KeyError: source = 'vkontakte' code = request.GET['code'] form = UserLoginForm(request.POST or None) if source == 'vkontakte': try: access_token, user_id = vkontakte.auth_code(code, reverse('login_view')) except vkontakte.AuthError as e: messages.warning(request, u'Ошибка OAUTH авторизации {}'.format(e)) return shortcut() try: user = User.objects.get(vkuserid=user_id) # Bug fix user.last_login = timezone.now() user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' auth.login(request, user) return redirect(return_path) except User.DoesNotExist: messages.warning(request, 'Такой пользователь не найден') return shortcut() elif source == 'facebook': try: access_token = facebook.auth_code(code, reverse('login_view')) print(access_token) user_id = facebook.user_id(access_token) print(user_id) except vkontakte.AuthError as e: messages.warning(request, u'Ошибка OAUTH авторизации {}'.format(e), extra_tags='integration') return shortcut() try: user = User.objects.get(fbuserid=user_id) except User.DoesNotExist: messages.warning(request, 'Такой пользователь не найден') return shortcut() user.last_login = timezone.now() user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' auth.login(request, user) return redirect(return_path) else: form = UserLoginForm(request) return shortcut()
def vk_reg(request): if 'code' in request.GET: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, reverse('vk_reg')) except vkontakte.AuthError as e: messages.warning(request, u'Ошибка OAUTH авторизации {}'.format(e), extra_tags='integration') return redirect('reg_view') try: user = User.objects.get(vkuserid=user_id) user.last_login = timezone.now() user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' auth.login(request, user) return redirect('user_update_view') except User.DoesNotExist: vkuser = vkontakte.api(access_token, 'users.get', fields=['sex', 'bdate', 'city', 'photo_max', 'contacts'])[0] vkdata = dict() vkdata['vkuserid'] = user_id vkdata['first_name'] = vkuser['first_name'] vkdata['last_name'] = vkuser['last_name'] if 'mobile_phone' in vkuser: vkdata['phone'] = vkuser['mobile_phone'] elif 'home_phone' in vkuser: vkdata['phone'] = vkuser['home_phone'] else: vkdata['phone'] = None if vkuser['sex']: if vkuser['sex'] == 2: vkdata['sex'] = 'm' elif vkuser['sex'] == 1: vkdata['sex'] = 'f' else: vkdata['sex'] = None if 'bdate' in vkuser: if len(vkuser['bdate']) >= 8: vkdata['bdate'] = vkuser['bdate'] elif vkuser['bdate'] != '': messages.warning(request, 'Неполная дата') vkdata['bdate'] = vkuser['bdate'] else: vkdata['bdate'] = '' # TODO: set vkontakteavatar # if 'photo_max' in vkuser: # url = vkuser['photo_max'] # response = urlopen(url) # io = BytesIO(response.read()) # file = File(io) # vkdata['avatar'] = file initial = {'sex': vkdata['sex'], 'first_name': vkdata['first_name'], 'last_name': vkdata['last_name'], 'phone': vkdata['phone'], 'bdate': vkdata['bdate'], 'vkuserid': user_id } form = UserRegistrationForm(initial=initial) return render(request, 'reg.html', {'form': form})
def reg(request, token): if request.user.is_authenticated(): return render(request, 'index.html') else: try: activation = Activation.objects.get(token=token) except Activation.DoesNotExist: raise Exception("Неверный код") if activation.status == activation.REGISTERED: return render(request, 'login.html') elif activation.status == activation.EMAIL_SENT: raise Exception("Сначала подтвердите емейл") context = dict() email = Activation.objects.get(token=token).email shortcut = lambda: render(request, 'reg.html', context) if 'code' in request.GET and not 'vkuserid' in request.POST: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, request.path) except vkontakte.AuthError as e: messages.warning(request, 'Ошибка авторизации') context['form'] = UserRegistrationForm(request.POST) return shortcut() if User.objects.filter(vkuserid=user_id).count() == 0: vkuser = vkontakte.api(access_token, 'users.get', fields=['sex', 'bdate', 'city', 'photo_max', 'contacts'])[0] vkdata = dict() vkdata['vkuserid'] = user_id vkdata['first_name'] = vkuser['first_name'] vkdata['last_name'] = vkuser['last_name'] if 'mobile_phone' in vkuser: vkdata['phone'] = vkuser['mobile_phone'] elif 'home_phone' in vkuser: vkdata['phone'] = vkuser['home_phone'] else: vkdata['phone'] = None if vkuser['sex']: if vkuser['sex'] == 2: vkdata['sex'] = 'm' elif vkuser['sex'] == 1: vkdata['sex'] = 'f' else: vkdata['sex'] = None if 'bdate' in vkuser: if len(vkuser['bdate']) >= 8: vkdata['bdate'] = vkuser['bdate'] elif vkuser['bdate'] != '': messages.warning(request, 'Неполная дата') vkdata['bdate'] = vkuser['bdate'] else: vkdata['bdate'] = '' if 'photo_max' in vkuser: url = vkuser['photo_max'] vkdata['avatar'] = url context['avatar_url'] = url context['vkdata'] = vkdata context['vkuserid'] = user_id initial = {'email': email, 'sex': vkdata['sex'], 'first_name': vkdata['first_name'], 'last_name': vkdata['last_name'], 'phone': vkdata['phone'], 'bdate': vkdata['bdate'], 'vkuserid': user_id, 'avatar': vkdata['avatar'] } context['form'] = UserRegistrationForm(initial=initial) return shortcut() else: messages.warning(request, 'Такой пользователь уже зарегестрирован в системе') if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): print form.cleaned_data user = form.save(commit=False) user.set_password(user.password) activation = Activation.objects.get(email=user.email) activation.status = activation.REGISTERED activation.save() user.save() newuser = auth.authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password']) auth.login(request, newuser) return redirect('index') else: context['form'] = form messages.success(request, "Form is not valid!") return shortcut() context['form'] = UserRegistrationForm(initial={'email': email}) return shortcut()