def api_login(request): data = request.POST username = data.get('username') password = data.get('password') is_cookie = data.get('is_login') if username is not None and password is not None: is_av = is_login(username, password) if is_av is not None: res = HttpResponseRedirect('/user/home/') if is_cookie == 'on': res.set_cookie("uid", is_av, max_age=3600) res.set_cookie("username", username, max_age=3600) res.set_signed_cookie("password", password, max_age=3600) else: res.set_cookie("uid", is_av) res.set_cookie("username", username) res.set_signed_cookie("password", password) print(res.cookies) return res else: return render(request, template_name='error.html', context={'msg': '用户名或密码都错误'}) else: return render(request, template_name='error.html', context={'msg': '用户名、密码必填'})
def post(self, request): form = LoginForm(request.POST) response = HttpResponseRedirect(reverse('index_view')) context = {'form': None, 'loginresult': None} if form.is_valid(): cd = form.cleaned_data username = cd['username'] # email = cd['email'] password = cd['password'] context['form'] = form try: instance = User.objects.get(username=username, password=password) context['loginresult'] = 'Login Success!' response.set_signed_cookie('username', username, salt=settings.COOKIE_SALT_VALUE, expires=settings.COOKIE_EXPIRE_TIME) except User.DoesNotExist: try: instance = User.objects.get(username=username) context['loginresult'] = 'Wrong Password!' return render(request, self.template_name, context) except User.DoesNotExist: # print(self.context['loginresult']) context[ 'loginresult'] = 'Wrong Username, Email or Password!' return render(request, self.template_name, context) return response
def login(request): if request.method == 'GET': # user is logged in already s = get_session(request) if s is not None: return HttpResponseRedirect('/') return render(request, 'login.html', {}) elif request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') u = models.User.get_by_id(email, parent=globalKey()) if u is None: return render(request, 'login.html', {'error': 'Invalid email! You might want to signup first!'}) if u.password == encode_password(password): # valid user # create a session s = models.HSession(parent=globalKey()) s.user = u.key s.sessionid = randomString(15) s.put() response = HttpResponseRedirect('/rooms') response.set_signed_cookie('hsession', s.sessionid) return response else: return render(request, 'login.html', {'error': 'Invalid password for this email!', 'email': email}) else: # unsupported raise 404 ?! pass
def post(self, request): username = request.POST.get('doctoruser', '').strip() # 取不到,返回空 password = request.POST.get('doctorpwd', '').strip() # 取不到,返回空 flag = request.POST.get('flag', '').strip() # 取不到,返回空 print(username, password, flag) doctorList = Doctor.objects.filter(dusername=username, dpassword=password) # 判断 if username and password: if doctorList.count() == 1: # .objects.filter()取得匹配结果 response = HttpResponseRedirect('/doctor/operate/') request.session['onlineuser'] = doctorList[0] if flag: # 不加盐 response.set_cookie("doctoruser", username, max_age=30 * 24 * 60 * 60, path="/doctor/login/") # 加盐 response.set_signed_cookie("doctorpwd", password, salt="xyt", max_age=30 * 24 * 60 * 60, path="/doctor/login/") return response # else: # response = HttpResponseRedirect('/doctor/login/', reverse('error:error')) # response.delete_cookie("doctoruser", path="/doctor/login/") # response.delete_cookie("doctorpwd", path="/doctor/login/") # response.content="登录失败" # return response return render(request, 'login.html', {"errors": "登录失败"})
def login(request): if request.method == 'POST': username = request.POST.get('username', None) password = request.POST.get('password', None) if username and password: if len(username) >= 5: if search_user(username, password): http_response = HttpResponseRedirect( '/demo/home/?user=%s' % username) #利用session重定向,传递数据 # request.session['username'] = username # request.session.set_expiry(0) # http_response = HttpResponseRedirect('/demo/home/') if request.POST.get('isSave', '0') == '1': http_response.set_cookie('user', username, max_age=30) http_response.set_signed_cookie('pwd', password, salt="jkkll", max_age=30) return http_response else: response = u'用户名或密码错误' else: response = u'username必须大于5位' else: response = u'缺少必要参数:username、password' else: response = u'该接口只支持POST请求' return HttpResponseRedirect('/demo/error/?info=%s' % response)
def login_view(request) -> HttpResponse: user_id = request.POST["ID"] user_password = request.POST['pwd'] next_url = request.GET.get("next") try: user = User.objects.get(ID=user_id) except User.DoesNotExist: user = None if user: if user.pwd == user_password: if next_url: ret = redirect(next_url) else: ret = redirect('/') ret.set_signed_cookie('signed_in', '1', salt=SALT, max_age=10000) ret.set_cookie('user_id', str(user.ID)) else: print('Wrong password') ret = HttpResponseRedirect('/signin?hint=wrong_password') ret.set_signed_cookie('signed_in', '0', salt=SALT) else: print("User not exist") ret = HttpResponseRedirect('/signin?hint=user_not_found') ret.set_signed_cookie('signed_in', '0', salt=SALT) return ret
def login_view(request): if request.method == 'POST': userform = UserForm(request.POST) del userform.fields['email'] if userform.is_valid(): username = userform.cleaned_data['username'] password = userform.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: # request.session['username']=username request.session.set_expiry( 0) #logout automatically when closing the browser login(request, user) response = HttpResponseRedirect('/') # 仅使用了加盐的cookie来保持登陆 response.set_signed_cookie( 'username', username, salt=settings.COOKIE_SALT, expires=settings.SESSION_COOKIE_AGE) return response else: return HttpResponse('您的账户已被冻结') else: return HttpResponse('用户名/密码错误或未注册,请重新登录') else: return HttpResponse('表单输入不合法') else: userform = UserForm() del userform.fields['email'] return render_to_response('login.html', {'userform': userform})
def api_login(request): username = request.POST.get('username') password = request.POST.get('password') is_cookie = request.POST.get('is_login') print(is_cookie) # auth.authenticate(username=username,password=password) if username is not None and password is not None: is_av = is_login(username, password) if is_av is not None: res = HttpResponseRedirect('/user/home/') # HttpResponseRedirect重定向 # res = render(request, 'home.html', context={"username": username}) if is_cookie == 'on': res.set_cookie("uid", is_av, max_age=86400) res.set_cookie("username", username, max_age=86400) res.set_signed_cookie("pwd", password, max_age=86400) return res else: res.set_cookie("uid", is_av) res.set_cookie("username", username) res.set_signed_cookie("pwd", password) return res else: return render(request, 'error.html', context={"msg": "账号或者密码错误"}) else: return render(request, 'error.html', context={"msg": "账号或者密码必填"})
def post(self, request): context = {'user_form': None, 'registrationresult': None} response = HttpResponseRedirect(reverse('index_view')) user_form = UserRegistrationForm(request.POST) context['user_form'] = user_form if user_form.is_valid(): cd = user_form.cleaned_data username = cd['username'] email = cd['mail'] password = user_form.clean_password2() try: userinstance = User.objects.get(username=username) context['registrationresult'] = 'the UserName has been used' return render(request, self.template_name, context) except User.DoesNotExist: try: userinstance = User.objects.get(mail=email) context['registrationresult'] = 'the E-Mail has been used' return render(request, self.template_name, context) except User.DoesNotExist: new_user = User.objects.create(username=username, mail=email, password=password) print(new_user.id) # launch asychronous task user_registered.delay(new_user.id) response.set_signed_cookie( 'username', username, salt=settings.COOKIE_SALT_VALUE, expires=settings.COOKIE_EXPIRE_TIME) return response
def form_valid(self, form): token = form.use_token() valid_token.send(sender=self.__class__, request=self.request, token=token) response = HttpResponseRedirect(settings.LOGIN_URL) response.set_signed_cookie('invite', token.token, max_age=None) return response
def do_login(request): uname = request.POST.get('uname') # response =HttpResponse('登陆成功') response = HttpResponseRedirect(reverse('app:mine')) # 设置cookie #response.set_cookie('uname',uname,max_age=60) # 设置加盐cookie response.set_signed_cookie('content',uname,'Rock') return response
def login(request): username = request.POST.get('username', '').strip() password = request.POST.get('password', '').strip() if username and password and username == password: response = HttpResponseRedirect('/') response.set_signed_cookie('user', username) return response else: return HttpResponse('Username and password did not match')
def get(self, request, *args, **kwargs): signer = Signer() pk = signer.unsign(self.kwargs['signature']) map_inst = get_object_or_404(Map, pk=pk) url = map_inst.get_absolute_url() response = HttpResponseRedirect(url) key, value = map_inst.signed_cookie_elements response.set_signed_cookie(key, value) return response
def start_exam_callback(request, attempt_code): # pylint: disable=unused-argument """ A callback endpoint which is called when SoftwareSecure completes the proctoring setup and the exam should be started. This is an authenticated endpoint and the attempt_code is passed in as part of the URL path IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending this endpoint """ attempt = get_exam_attempt_by_code(attempt_code) if not attempt: log.warning(u"Attempt code %r cannot be found.", attempt_code) return HttpResponse( content='You have entered an exam code that is not valid.', status=404 ) proctored_exam_id = attempt['proctored_exam']['id'] attempt_status = attempt['status'] user_id = attempt['user']['id'] if attempt_status in [ProctoredExamStudentAttemptStatus.created, ProctoredExamStudentAttemptStatus.download_software_clicked]: mark_exam_attempt_as_ready(proctored_exam_id, user_id) # if a user attempts to re-enter an exam that has not yet been submitted, submit the exam if ProctoredExamStudentAttemptStatus.is_in_progress_status(attempt_status): update_attempt_status(proctored_exam_id, user_id, ProctoredExamStudentAttemptStatus.submitted) else: log.warning(u"Attempted to enter proctored exam attempt {attempt_id} when status was {attempt_status}" .format( attempt_id=attempt['id'], attempt_status=attempt_status, )) if switch_is_active(RPNOWV4_WAFFLE_NAME): # pylint: disable=illegal-waffle-usage course_id = attempt['proctored_exam']['course_id'] content_id = attempt['proctored_exam']['content_id'] exam_url = '' try: exam_url = reverse('jump_to', args=[course_id, content_id]) except NoReverseMatch: log.exception(u"BLOCKING ERROR: Can't find course info url for course %s", course_id) response = HttpResponseRedirect(exam_url) response.set_signed_cookie('exam', attempt['attempt_code']) return response template = loader.get_template('proctored_exam/proctoring_launch_callback.html') return HttpResponse( template.render({ 'platform_name': settings.PLATFORM_NAME, 'link_urls': settings.PROCTORING_SETTINGS.get('LINK_URLS', {}) }) )
def form_valid(self, form): token = form.use_token() valid_token.send(sender=self.__class__, request=self.request, token=token) response = HttpResponseRedirect(settings.LOGIN_URL) response.set_signed_cookie('invite', token.token, max_age=None) return response
def form_valid(self, form): self.token.uses -= 1 self.token.save(update_fields=('uses',)) valid_token.send(sender=self.__class__, request=self.request, token=self.token) response = HttpResponseRedirect(settings.LOGIN_URL) response.set_signed_cookie('invite', token.token, max_age=None) return response
def login(request): msg = "" if request.method == "POST": if request.POST.get("password") == "21111122": redirect = HttpResponseRedirect(reverse("home")) redirect.set_signed_cookie("hifish_login", "OK", max_age=86400) return redirect else: msg = "Incorrect username or password." return render(request, "login.html", {"msg": msg})
def create_cookie(request): """ The flag view is called after a successful user login. Since we use Nginx, which does a subrequest to check authorization of workspace access, we need a way to identify the user there. So we bypass here to create a signed cookie for that purpose. """ response = HttpResponseRedirect(reverse('dashboard')) response.set_signed_cookie(settings.AUTH_COOKIE_NAME, request.user.username, httponly=True) return response
def form_valid(self, form): self.token.uses -= 1 self.token.save(update_fields=('uses', )) valid_token.send(sender=self.__class__, request=self.request, token=self.token) response = HttpResponseRedirect(settings.LOGIN_URL) response.set_signed_cookie('invite', token.token, max_age=None) return response
def login(request): scope = 'playlist-modify-public playlist-modify-private user-library-read' state = utils.generateRandomString(16) query = urlencode({ 'response_type': 'code', 'client_id': CLIENT_ID, 'scope': scope, 'redirect_uri': request.build_absolute_uri(REDIRECT_URI), 'state': state }) response = HttpResponseRedirect('https://accounts.spotify.com/authorize?' + query) response.set_signed_cookie(STATE_KEY, state) return response
def start_exam_callback(request, attempt_code): # pylint: disable=unused-argument """ A callback endpoint which is called when SoftwareSecure completes the proctoring setup and the exam should be started. This is an authenticated endpoint and the attempt_code is passed in as part of the URL path IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending this endpoint """ attempt = get_exam_attempt_by_code(attempt_code) if not attempt: log.warning("Attempt code %r cannot be found.", attempt_code) return HttpResponse( content='You have entered an exam code that is not valid.', status=404 ) if attempt['status'] in [ProctoredExamStudentAttemptStatus.created, ProctoredExamStudentAttemptStatus.download_software_clicked]: mark_exam_attempt_as_ready(attempt['proctored_exam']['id'], attempt['user']['id']) else: log.warning("Attempted to enter proctored exam attempt {attempt_id} when status was {attempt_status}" .format( attempt_id=attempt['id'], attempt_status=attempt['status'], )) log.info("Exam %r has been marked as ready", attempt['proctored_exam']['id']) if switch_is_active(RPNOWV4_WAFFLE_NAME): course_id = attempt['proctored_exam']['course_id'] content_id = attempt['proctored_exam']['content_id'] exam_url = '' try: exam_url = reverse('jump_to', args=[course_id, content_id]) except NoReverseMatch: log.exception("BLOCKING ERROR: Can't find course info url for course %s", course_id) response = HttpResponseRedirect(exam_url) response.set_signed_cookie('exam', attempt['attempt_code']) return response template = loader.get_template('proctored_exam/proctoring_launch_callback.html') return HttpResponse( template.render({ 'platform_name': settings.PLATFORM_NAME, 'link_urls': settings.PROCTORING_SETTINGS.get('LINK_URLS', {}) }) )
def start_exam_callback(request, attempt_code): # pylint: disable=unused-argument """ A callback endpoint which is called when SoftwareSecure completes the proctoring setup and the exam should be started. This is an authenticated endpoint and the attempt_code is passed in as part of the URL path IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending this endpoint """ attempt = get_exam_attempt_by_code(attempt_code) if not attempt: log.warning('attempt_code={attempt_code} cannot be found.'.format( attempt_code=attempt_code)) return HttpResponse( content='You have entered an exam code that is not valid.', status=404) attempt_status = attempt['status'] if attempt_status in [ ProctoredExamStudentAttemptStatus.created, ProctoredExamStudentAttemptStatus.download_software_clicked ]: mark_exam_attempt_as_ready(attempt['id']) # if a user attempts to re-enter an exam that has not yet been submitted, submit the exam if ProctoredExamStudentAttemptStatus.is_in_progress_status(attempt_status): update_attempt_status(attempt['id'], ProctoredExamStudentAttemptStatus.submitted) else: log.warning( 'Attempted to enter proctored exam attempt_id={attempt_id} when status={attempt_status}' .format( attempt_id=attempt['id'], attempt_status=attempt_status, )) course_id = attempt['proctored_exam']['course_id'] content_id = attempt['proctored_exam']['content_id'] exam_url = '' try: exam_url = reverse('jump_to', args=[course_id, content_id]) except NoReverseMatch: log.exception( "BLOCKING ERROR: Can't find course info url for course_id=%s", course_id) response = HttpResponseRedirect(exam_url) response.set_signed_cookie('exam', attempt['attempt_code']) return response
def get(self, request, *args, **kwargs): signer = Signer() try: pk = signer.unsign(self.kwargs['signature']) except BadSignature: return HttpResponseForbidden('Bad Signature') else: map_inst = get_object_or_404(Map, pk=pk) url = map_inst.get_absolute_url() response = HttpResponseRedirect(url) if not map_inst.owner: key, value = map_inst.signed_cookie_elements response.set_signed_cookie(key, value) return response
def form_valid(self, form): obj = form.save() response = HttpResponseRedirect(self.get_success_url(obj)) if form.cleaned_data.get('name'): response.set_signed_cookie( 'name', form.cleaned_data.get('name'), max_age=settings.CSRF_COOKIE_AGE, httponly=True, ) return response
def get(self, request, *args, **kwargs): signer = Signer() try: pk = signer.unsign(self.kwargs['signature']) except BadSignature: return HttpResponseForbidden('Bad Signature') else: map_inst = get_object_or_404(Map, pk=pk) url = map_inst.get_absolute_url() response = HttpResponseRedirect(url) if not map_inst.owner: key, value = map_inst.signed_cookie_elements response.set_signed_cookie(key=key, value=value, max_age=ANONYMOUS_COOKIE_MAX_AGE) return response
def dologin(request): uname = request.POST.get('uname') #因为cookie默认不支持中文, 所以在接收到输入中文时先转码存 uname = str(base64.b64encode(uname.encode("utf-8")), "utf-8") #反向解析到mine response = HttpResponseRedirect(reverse('app:mine')) #max_age设置cookie过期时间 max_age=60代表1分钟后过期 # response.set_cookie('uname', uname, max_age=60) response.set_signed_cookie('uname', uname, salt="Rock", max_age=10) return response
def checkout(request): if not view_data.is_logged_in(request): response = HttpResponseRedirect("/Login/") response.set_signed_cookie("redirect", "/Cart/Checkout/", salt="dog") return response billing_form = None shipping_form = None cc_form = None #print "checkout customer user = "******"shipping_form":shipping_form,"cc_form":cc_form}.items()) #print dictionary return render(request, 'checkout2.html', dictionary)
def api_login(request): username = request.POST.get('username') password = request.POST.get('password') is_login = request.POST.get('is_login') if username is not None and password is not None: if username == 'admin' and password == 'admin': res = HttpResponseRedirect('/user/home/') res.set_cookie('uid', '1', httponly=True) res.set_cookie('username', 'admin') res.set_signed_cookie('password', 'admin', salt='123') return res else: return render(request, 'error.html', context={"msg": "用户名或密码错误!"}) else: return render(request, 'error.html', context={"msg": '用户名、密码不能为空!'})
def middleware(request): if request.user.is_authenticated: set_user_name("user-%d-%s" % (request.user.id, request.user.get_short_name())) activate(request.user.language) return get_response(request) set_user_name("user-0-anonymous") if request.path.startswith(settings.LOGIN_REQUIRED_EXEMPT): return get_response(request) messages.info(request, _("Please authenticate.")) response = HttpResponseRedirect(reverse("login")) response.set_signed_cookie("next", request.get_full_path(), salt="next") return response
def login(request): username = request.POST['username'] password = request.POST['password'] if str(request.POST['code']).lower() == str( request.session['code']).lower(): if username == 'fan' and password == '123': red = HttpResponseRedirect('/Novel/homepage') red.set_signed_cookie(key='username', value=username, max_age=3600) request.session['login_state'] = True if request.POST.getlist('true'): red.set_signed_cookie('password', password, max_age=3600) return red else: request.session['login_state'] = False red = HttpResponseRedirect('/Novel/go_login') return red else: red = HttpResponseRedirect('/Novel/go_login') request.session['login_state'] = False return red
def authenticate_user(request): csrf_request = {} csrf_request.update(csrf(request)) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. response = HttpResponseRedirect(reverse('game.views.main')) response.set_signed_cookie('inagame', 'False') #set default platform to x86 response.set_signed_cookie('platform', get_request_param(request, 'platform', 'x86')) return response else: # Return a 'disabled account' error message return HttpResponse("Account disabled, hit back on your browser to try again") else: # Return an 'invalid login' error message. return HttpResponse("Invalid Login, hit back on your browser to try again")
def post(self, req): password = req.POST.get('password', '') if not password: if not req.path.startswith('/zh-hans'): return render(req, 'password.html', {'msg': "Please input a password."}) return render(req, 'password.html', {'msg': "请输入密码"}) else: if password == 'cpchain2019': # return redirect('faucet') response = HttpResponseRedirect('/faucet') response.set_signed_cookie('faucet', 'login', salt="cpc", max_age=60 * 30, httponly=True) return response else: if not req.path.startswith('/zh-hans'): return render(req, 'password.html', {'msg': "Incorrect password."}) return render(req, 'password.html', {'msg': "密码错误"})
def create_user(request): username = get_request_param(request,'new_username', '') password = get_request_param(request,'new_password', '') platform = get_request_param(request,'platform', 'x86') if(password != '' and username != ''): if(len(User.objects.filter(username=username)) == 0): new_user = User(username=username) new_user.set_password(password) new_user.save() user = authenticate(username=username, password=password) login(request, user) response = HttpResponseRedirect(reverse('game.views.main')) response.set_signed_cookie('inagame', 'False') #set default platform to x86 response.set_signed_cookie('platform', get_request_param(request, 'platform', 'x86')) print "at end of create_user" return response else: return HttpResponse('Username taken! Be More original!') else: return HttpResponse('no entry given!!')
def login_page(request): if request.method == "GET": template = get_template('admin/login.html') context = {'website': get_website_config()} return HttpResponse(template.render(context, request)) if request.method == "POST": login_name = request.POST.get("login_name") password = request.POST.get("password") user = User.objects.filter(login_name=login_name).first() password = md5.encrypt_user_password(password) if user.password != password: template = get_template('admin/login.html') context = { 'website': get_website_config(), 'error_msg': '用户名或密码错误!' } return HttpResponse(template.render(context, request)) user.token = md5.encrypt(str(uuid.uuid1())) user.save() resp = HttpResponseRedirect("index.html") resp.set_signed_cookie("token", user.token) return resp
def dologin(request): uname = request.POST.get('uname') response = HttpResponseRedirect(reverse('app:mine')) # response.set_cookie('uname', uname, max_age=60) response.set_signed_cookie('content', uname, "Rock") return response
def django_tests(): from django.http import HttpResponse from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseBadRequest, HttpResponseNotModified, HttpResponseNotFound, HttpResponseForbidden, HttpResponseNotAllowed, HttpResponseGone, HttpResponseServerError response = HttpResponse() response.set_cookie("C1", "world") # Noncompliant response.set_cookie("C2", "world", secure=None) # Noncompliant response.set_cookie("C3", "world", secure=False) # Noncompliant response.set_cookie("C4", "world", secure=True) response2 = HttpResponseRedirect() response2.set_cookie("C5", "world") # Noncompliant response2.set_cookie("C5", "world", None, None, "/", None, True) # OK response2.set_signed_cookie("C5", "world") # Noncompliant response2.set_signed_cookie("C5", "world", secure=True) # OK response2.set_signed_cookie("C5", "world", other=False, secure=True) # OK response2.set_signed_cookie("C5", "world", secure=False) # Noncompliant response2.set_signed_cookie("C5", "world", secure=None) # Noncompliant response2.set_signed_cookie("C5", "", "world", None, None, "/", None, True) # OK kwargs = {secure: True} response2.set_signed_cookie("C5", "world", **kwargs) # OK kwargs = {secure: False} response2.set_signed_cookie("C5", "world", **kwargs) # FN get_cookie().set_cookie("C3", "world", secure=False) response3 = HttpResponsePermanentRedirect() response3.set_cookie("C6", "world") # Noncompliant response4 = HttpResponseNotModified() response4.set_cookie("C7", "world") # Noncompliant response5 = HttpResponseBadRequest() response5.set_cookie("C8", "world") # Noncompliant response6 = HttpResponseNotFound() response6.set_cookie("C9", "world") # Noncompliant response7 = HttpResponseForbidden() response7.set_cookie("C10", "world") # Noncompliant response8 = HttpResponseNotAllowed() response8.set_cookie("C11", "world") # Noncompliant response9 = HttpResponseGone() response9.set_cookie("C12", "world") # Noncompliant response10 = HttpResponseServerError() response10.set_cookie("C13", "world") # Noncompliant
def verify_computer(request, template_name='two_factor/verify_computer.html', redirect_field_name=REDIRECT_FIELD_NAME, computer_verification_form=ComputerVerificationForm, current_app=None, extra_context=None): redirect_to = request.REQUEST.get(redirect_field_name, '') netloc = urlparse.urlparse(redirect_to)[1] # Use default setting if redirect_to is empty if not redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL # Heavier security check -- don't allow redirection to a different # host. elif netloc and netloc != request.get_host(): redirect_to = settings.LOGIN_REDIRECT_URL try: user = User.objects.get(pk=signer.unsign(request.GET.get('user'))) except (User.DoesNotExist, BadSignature): return HttpResponseRedirect(settings.LOGIN_URL) if request.method == 'POST': form = computer_verification_form(user=user, data=request.POST) if form.is_valid(): # Okay, security checks complete. Log the user in. auth_login(request, user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() response = HttpResponseRedirect(redirect_to) # set computer verification if form.cleaned_data['remember']: vf = user.verifiedcomputer_set.create( verified_until=now() + timedelta(days=30), last_used_at=now(), ip=request.META['REMOTE_ADDR']) response.set_signed_cookie('computer', vf.id, path=reverse('tf:verify'), max_age=30*86400, httponly=True) return response else: form = computer_verification_form(request, user) # has this computer been verified? try: computer_id = request.get_signed_cookie('computer', None) user = authenticate(user=user, computer_id=computer_id) if user and user.is_active: # Okay, security checks complete. Log the user in. auth_login(request, user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) except VerifiedComputer.DoesNotExist: pass token = user.token if token.method in ('call', 'sms'): #todo use backup phone #todo resend message + throttling generated_token = totp(token.seed) if token.method == 'call': call(to=token.phone, request=request, token=generated_token) elif token.method == 'sms': send(to=token.phone, request=request, token=generated_token) current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app)