def login(request): form = LoginForm(request.POST or None) valueButton = "Se connecter" error = None link = "<a id=\"link\" href=\"register\">Inscrivez-vous</a>" if form.is_valid(): account = form.cleaned_data['account'] password = form.cleaned_data['password'] ## Check if data fits with database user = authenticate(username=account, password=password) if user is not None: [ s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id ] auth_login(request, user) return redirect(reverse("game:home"), permanent=True) ## Check if user wasn't banned by an all mighty admin / moderator ## Not working at moment, should be fixed later # if user_can_authenticate(): # login(request, user) # else: # error="L'utilisateur est banni" else: error = "L'utilisateur n'existe pas" return render(request, 'user/baseForm.html', locals())
def user_login(request): '''username = request.POST.get('username','') password = request.POST.get('password','') user = authenticate(request, username=username, password=password) #current_http = request.META.get('HTTP_REFERER','/') #获得当前网址,'/'为默认的网址,首页 current_http = request.META.get('HTTP_REFERER', reverse('home')) #反向解析home获得home的网址 if user is not None: login(request, user) # Redirect to a success page. return redirect(current_http) else: # Return an 'invalid login' error message. return render(request,'blog/error.html',{'messege':'用户名或密码不正确'})''' if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] login(request, user) # Redirect to a success page. return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() context = {} context['login_form'] = login_form return render(request, 'login.html', context)
def login(request): if request.method == 'GET': return render(request, 'login.html') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): # 通过合理性校验 user = User.objects.filter(username=form.cleaned_data.get('username')).first() if not user: # 用户不存在 return render(request, 'login.html', {'msg1': '该账号不存在'}) flag = check_password(form.cleaned_data.get('pwd'), user.password) if not flag: # 密码错误 return render (request, 'login.html', {'msg2': '密码错误'}) # 向cookie中设置sessionid值 # 向django_session表中存sessionid值 if request.user.id: return render(request, 'login.html', {'msg3': '一个浏览器只能等录一个账号'}) request.session['user_id'] = user.id return HttpResponseRedirect(reverse('goods:index')) else: return render(request, 'login.html', {'errors': form.errors})
def index(request): context = dict() login_form = LoginForm(request.POST or None) context['login_form'] = login_form if login_form.is_valid(): email = login_form.cleaned_data.get("email") password = login_form.cleaned_data.get("password") # if username is not exists throw and error to user try: username = User.objects.get(email=email).username except User.DoesNotExist: messages.info(request, "Kullanıcı Adı Yanlış.") return render(request, "index.html", context) # check username and password are correct user = authenticate(request, username=username, password=password) if user is None: messages.info(request, "Kullanıcı Adı veya Parolanız Yanlış") return render(request, "index.html", context) else: messages.success(request, "Başarıyla Giriş Yaptınız") # start new session for user login(request, user) return redirect("index") return render(request, 'index.html', context)
def account_login(request, **kwargs): template = 'user/login.htm' if request.method == 'GET': return render(request, template) elif request.method == 'POST': context = {'data': request.POST} form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if 'next' in request.GET: return redirect(request.GET.get('next')) else: return redirect(reverse('home')) else: messages.error(request, 'Your account may be deactivated.') return render(request, template, context) else: messages.error(request, 'Your credentials do not match any record.') return render(request, template, context) else: context['errors'] = form.errors return render(request, template, context)
def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', None) pass_word = request.POST.get('password', None) user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) return render(request, 'index.html') # 这里要再加一层验证,因为数据合法的情况下 通不过数据库验证也是白搭 else: return render(request, 'login.html', { 'msg': '用户名或密码错误', 'login_form': login_form }) else: return render(request, 'login.html', {'login_form': login_form}) # # 改用类来处理get post 之类的逻辑 # def user_login(request): # if request.method == 'POST': # user_name = request.POST.get('username', None) # pass_word = request.POST.get('password', None) # user = authenticate(username=user_name, password=pass_word) # if user is not None: # login(request, user) # return render(request, 'index.html') # else: # return render(request, 'login.html', {'msg': '密码错误呀,小哥'}) # elif request.method == 'GET': # return render(request,'login.html')
def login_view(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: token_string = username.join( random.choice(ascii_uppercase + digits) for i in range(20)) token = Token.objects.create(token=token_string, user=user) return HttpResponse(json.dumps({ "status": 0, "token": token_string }), content_type="application/json") else: print("user not found") return HttpResponse(json.dumps({"status": -1}), content_type="application/json") return HttpResponse(json.dumps({"status": -1}), content_type="application/json") print("form not valid") return HttpResponse(json.dumps({"status": -1}), content_type="application/json")
def loginView(request): context = {} user = request.user if user.is_authenticated: return HttpResponseRedirect(reverse('home')) if request.POST: form = LoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(username=email, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('home')) else: form = LoginForm() context['form'] = form return render(request, "user/login.html", context)
def post(self, request): # 类实例化需要一个字典参数dict:request.POST就是一个QueryDict所以直接传入 # POST中的usernamepassword,会对应到form中 login_form = LoginForm(request.POST) # is_valid判断我们字段是否有错执行我们原有逻辑,验证失败跳回login页面 if login_form.is_valid(): # 取不到时为空,username,password为前端页面name值 user_name = request.POST.get("email", "") pass_word = request.POST.get("password", "") # 成功返回user对象,失败返回null user = authenticate(username=user_name, password=pass_word) # 如果不是null说明验证成功 if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) # 即用户未激活跳转登录,提示未激活 else: return render(request, "login.html", {"msg": "用户名或密码错误!"}) # 验证不成功跳回登录页面 # 没有成功说明里面的值是None,并再次跳转回主页面 else: return render(request, "login.html", {"login_form": login_form})
def user_login(request): if request.method == 'GET': lform = LoginForm() return render(request, '../../Web/templates/login.html', context={'form': lform}) # else: # lform = LoginForm(request.POST) # if lform.is_valid(): # data = lform.cleaned_data # user = User.objects.filter(username=data.get('username')).first() # # # password = lform.cleaned_data.get('password') # # user = User.objects.filter(username=username).first() # flag = check_password(data.get('password'), user.password) # if user and user.is_active: # flag = check_password(data.get('password'), user.password) # if flag: # # token 令牌 # # uid = uuid.uuid4() # # token = str(uid).replace('-', '') # # print("++++++++>token :", token) # # cache.set(token, user, timeout=60 * 30) # # # 创建response对象 # # request.session['username'] = username # # return redirect('user:index', context={'form': lform}) # # return HttpResponseRedirect('/') # # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '用户名或者密码有误!'}) # username = lform.cleaned_data.get('username') # request.session['username'] = username # return HttpResponseRedirect('/') # else: # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '请检查用户名或者用户没有激活!'}) # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '用户名或者密码有误!'}) else: lform = LoginForm(request.POST) if lform.is_valid(): username = lform.cleaned_data.get('username') password = lform.cleaned_data.get('password') user = User.objects.filter(username=username).first() flag = check_password(password, user.password) if flag: # 保存session信息 username = lform.cleaned_data.get('username') request.session['username'] = username return HttpResponseRedirect('/') else: return render(request, '../../Web/templates/login.html', context={ 'form': lform, 'msg': '请检查用户名或者用户没有激活!' }) return render(request, '../../Web/templates/login.html', context={ 'form': lform, 'msg': '用户名或者密码有误!' })
def user_login(request): context = {} if request.method == "GET": form = LoginForm() context['form'] = form return render(request, "user/login.html", context=context) else: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") # 方式一: 没有继承AbstractUser的用户使用这种方法 """ # 进行数据库查询 user = UserProfile.objects.filter(username=username).first() # 判断密码是否正确 flag = check_password(password, user.password) if flag: # 保存登录的session信息 request.session['username'] = username # 跳转到主页 """ context.update(get_index_info()) context["msg"] = 'loginSuccess' # 方式二: 继承了AbstractUser的用户 可以使用 user = authenticate(username=username, password=password) if user: login(request, user) # 将用户对象保存到底层的request中(session) return render(request, "index.html", context=context) return render(request, "user/login.html", context={ "form": form, "msg": "login_error" })
def login_view(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = authenticate(username=form.cleaned_data["username"], password=form.cleaned_data["password"]) if user is not None and user.is_confirmed != "NOT_CONFIRMED": login(request, user) return redirect(reverse('root')) else: return render( request, "login.html", { "form": form, "errors": [ "Incorrect login or password or you need to confirm your account" ] }) else: return render(request, "login.html", {"form": form}) else: if request.user.is_authenticated: return redirect(reverse('profile')) form = LoginForm() return render(request, "login.html", {"form": form})
def user_login(request): if request.method == 'GET': return render(request, 'user/login.html') else: lform = LoginForm(request.POST) if lform.is_valid(): username = lform.cleaned_data.get('username') password = lform.cleaned_data.get('password') #进行数据库的查询 user = UserProfile.objects.filter(username=username).first() # if user: # flag=check_password(password,user.password) # if flag: # # 保存session信息 # request.session['username']=username #方式二 前提是继承了AbstractUser user = authenticate(username=username, password=password) if user: print(user) res = login(request, user) # # 将用户对象保存在底层的request中 (session) print(res) return redirect(reverse('index')) # return render(request, 'user/login.html', context={'errors': lform.errors})
def login_view(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): cd = login_form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user: # request.session["info"] = "infomation" '''用户登陆后,Django会自动调用默认的session应用, 将用户的id存至session中,通常情况下,login与authenticate 配合使用''' login(request, user) # request.session.set_expiry(0) # 关闭浏览器自动退出登录 return HttpResponseRedirect(reverse('file:file')) else: return render( request, 'user/login.html', { "form": login_form, 'status': 'ERROR Incorrect username or password' }) else: return render(request, 'user/login.html', { "form": login_form, 'status': '输入不合法' }) elif request.method == "GET": if request.user.is_authenticated: return HttpResponseRedirect(reverse('file:file')) else: login_form = LoginForm() return render(request, 'user/login.html', {"form": login_form})
def login(request): """username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(request, username=username, password=password) # 发送此请求的网站 referer = request.META.get('HTTP_REFERER', reverse('home')) if user is not None: auth.login(request, user) # 跳转到首页 return redirect(referer) else: return render(request, 'error.html', {'message': '用户名或密码不正确', 'redirect_to': referer})""" if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data.get('user') auth.login(request, user) # 跳转到来源页 return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() context = {'login_form': login_form} return render(request, 'user/login.html', context)
def loginUser(request): form = LoginForm(request.POST or None) context = {'form': form} if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) # bir değişkene atama yaptık ve bu veriler databasede kayıtlımı diye sorgulanıyor. if user is None: messages.info(request, 'Invalid User Name / Password') return render(request, 'login.html', context) # giriş başarısız, tekrar login sayfasına döndürdü messages.success(request, username.capitalize() + ', login successful') # if bloğuna girmedi yani giriş başarılı login(request, user) # user değişkenine atanan veriler ile login fonk. sayesinde giriş yapıldı return redirect('/zak/zakgeld') # giriş başarılı ana sayfaya yönlendiriliyor return render(request, 'login.html', context)
def user_login(request): if request.method == 'GET': lform = LoginForm() return render(request, 'login.html', context={'form': lform}) else: lform = LoginForm(request.POST) if lform.is_valid(): data = lform.cleaned_data user = User.objects.filter(username=data.get('username')).first() if user and user.is_active: flag = check_password(data.get('password'), user.password) if flag: # token 令牌 uid = uuid.uuid4() token = str(uid).replace('-', '') print("++++++++>token :", token) cache.set(token, user, timeout=60 * 30) # 创建response对象 res = HttpResponse('用户登录成功') res.set_cookie('token_', token) return res else: return render(request, 'login.html', context={ 'form': lform, 'msg': '请检查用户名或者用户没有激活!' }) return render(request, 'login.html', context={ 'form': lform, 'msg': '用户名或者密码有误!' })
def login_account(request): try: args={} form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = cd['username'] password = cd['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: # update last login in database result = User.objects.filter(username=username).update(last_login=datetime.datetime.now()) login(request, user) #Django buildin login method # request.session['bookserviceUser'] = username # response = HttpResponse() # response.set_cookie('bookserviceLogin', 'True') return HttpResponseRedirect('/test/') else: messages.add_message(request, messages.INFO, 'This account has been disabled.') else: messages.add_message(request, messages.INFO, 'Invalid Username and Password') else: args['form'] = form return render(request, 'user/login.html', args) else: return render(request, 'user/login.html', {'form':form}) except: messages.add_message(request, messages.ERROR, sys.exc_info()[1]) return render(request, 'user/login.html', {'form':form})
def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') user = check(username=user_name, password=pass_word) if user is not None: if user.is_active: login(request, user) blog_lists = BlogInfo.objects.all().order_by('-add_time') try: page = request.GET.get('page', 1) except: page = 1 p = Paginator(blog_lists, 5, request=request) lists = p.page(page) cate_list = Category.objects.all()[:8] return render(request, 'blog_list.html', { 'blog_list': lists, 'page': p, 'cate_list': cate_list }) else: return render(request, 'login_user.html', {'msg': "用户没有激活"}) else: return render(request, 'login_user.html', {'msg': "用户不存在或密码错误"}) else: user_name = request.POST.get('username', '') return render(request, 'login_user.html', { 'username': user_name, 'login_form': login_form })
def user_login(request): context = dict() form = LoginForm(request.POST or None) context["form"] = form if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") # if username is not exists throw and error to user try: username = User.objects.get(email=email).username except User.DoesNotExist: messages.info(request, "Username is wrong.") return render(request, "user/login.html", context) # check username and password are correct user = authenticate(request, username=username, password=password) if user is None: messages.info(request, "Username or password is wrong") return render(request, "user/login.html", context) else: messages.success(request, "You have successfully logged in.") # start new session for user login(request, user) return redirect("index") return render(request, "user/login.html", context)
def login(request): # Creamos el formulario de autenticación vacío form = LoginForm() if request.method == "POST": # Añadimos los datos recibidos al formulario form = LoginForm(data=request.POST) # Si el formulario es válido... if form.is_valid(): # Recuperamos las credenciales validadas username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Verificamos las credenciales del usuario user = authenticate(username=username, password=password) # Si existe un usuario con ese nombre y contraseña if user is not None: # Hacemos el login manualmente do_login(request, user) # Y le redireccionamos a la portada return redirect('/') form.add_error('username','El nombre de usuario o la contraseña no existen') # Si llegamos al final renderizamos el formulario return render(request, "login.html", {'form': form})
def login(request): if request.user.is_authenticated: return redirect('/home/') elif request.method == "GET": return render(request, 'account/pages/login.html') elif request.method == "POST": username = request.POST['username'] password = request.POST['password'] p_error=None u_error=None error="Sorry! Username and Password didn't match, Please try again ! " if len(username) < 5: u_error='Username must have atlest 5 characters' if len(password) < 8: p_error='Password must have atlest 8 characters' if p_error==None and u_error==None: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(request,user) error= None return JsonResponse({'p_error':p_error,'u_error':u_error,'error':error})
def test_login(self): form = LoginForm(data = { 'username' : '', 'password' : '' }) self.assertFalse(form.is_valid()) self.assertEquals(len(form.errors), 2)
def loginUser(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): messages.success(request, 'Successfully Logged in') username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return redirect("index") else: context = { "form": form } return render(request, "login.html", context) else: form = LoginForm() context = { "form": form } return render(request, "login.html", context)
def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') # remember = request.POST.get('remember') types = request.POST.get('types') if types == 'member': is_staff = 0 else: is_staff = 1 # print(remember) user = authenticate(username=username, password=password) # login(request, user) # 调用login方法登陆账号 # return render(request, "index.html") # else: # return render(request, "login.html", {"msg": u"用户未激活"}) if user.is_active: # if user.is_active: login(request, user) request.session['passport_id'] = user.id if user.is_staff == 1: return render(request, 'main.html', {'res': 0}) else: return render(request, 'index.html', {'res': 1}) return render(request, 'login.html', {'error': '用户未激活'}) return render(request, 'login.html', {'login_form': login_form}) # 用户注册
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): identifier = login_form.cleaned_data['identifier'] password = login_form.cleaned_data['password'] user = authenticate(request, username=identifier, password=password) if user != None: login_user(request, user) return redirect('main-page') else: context_dict = { 'form': login_form, 'invalid_credentials': True } return render(request, 'user/login.html', context_dict) else: context_dict = {'form': login_form, 'invalid_credentials': True} return render(request, 'user/login.html', context_dict) else: login_form = LoginForm() context_dict = {'form': login_form, 'invalid_credentials': False} return render(request, 'user/login.html', context_dict)
def login(request): # if not request.user.is_anonymous: # django_logout(request) # redirect_to = request.REQUEST.get('next', '') # if not redirect_to: # redirect_to = "/simorgh/home/" # # # # forgetForm = ForgotForm() message = "" if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: findeduser = User.objects.get(pk=user.id) my_user = MyUser.objects.get(user=findeduser) if findeduser.is_active: if Employee.objects.filter(user=my_user).count() > 0: emp = Employee.objects.get(user=my_user) if Cook.objects.filter(cook_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/cook.html") elif DeliveryMan.objects.filter(delivery_man_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/deliveryman.html") elif Clerk.objects.filter(clerk_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/clerk.html") elif Waiter.objects.filter(waiter_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/waiter.html") elif WarehouseMan.objects.filter(warehouse_man_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/warehouseman.html") elif ParkingMan.objects.filter(parking_man_id=emp).count() > 0: django_login(request, user) return render(request, template_name="employee/parkingman.html") else: django_login(request, user) return redirect('/restaurant/') else: form = LoginForm() # raise forms.ValidationError('.حساب کاربری شما غیرفعال است.') message = ".حساب کاربری شما غیرفعال است." else: form = LoginForm() # print("pass or username wrong") # raise forms.ValidationError('نام کاربری یا گذرواژه شما اشتباه است..') message = "نام کاربری یا گذرواژه شما اشتباه است." else: form = LoginForm() return render(request, "user/login.html", {'form': form, 'message': message})
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() return render(request, 'login/login.html', {'login_form': login_form})
def login_for_modal(request): login_form = LoginForm(request.POST) data = {} if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) data['status'] = 'SUCCESS' else: data['status'] = 'ERROR' return JsonResponse(data)
def login_for_modal(request): login_form = LoginForm(request.POST) data = {} if login_form.is_valid(): user = login_form.cleaned_data.get('user') auth.login(request, user) data['status'] = 'success' else: data['status'] = 'error' return JsonResponse(data)
def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user, passed = form.chk_password() if passed: request.session['uid'] = user.id return redirect('/post/home/') else: return render(request, 'login.html', {'errors': form.errors}) return render(request, 'login.html')
def login(request): if request.method == 'POST': rst = json.loads(request.body.decode("utf-8")) uf = LoginForm(rst) if uf.is_valid(): email = uf.cleaned_data['email'] pwd = (uf.cleaned_data['password'] + keyPwd).encode("utf-8") password = hashlib.sha1(pwd).hexdigest() #获取的表单数据与数据库进行比较 user = User.objects.filter(email__exact = email,password__exact = password).first() if user: data = {"status" : 'success', 'msg' : "Login success" } #将username写入浏览器cookie,失效时间为3600 * 24 * 30 token = hashlib.sha1((user.random + keyToken + str(int(time.time() / (24 * 3600)))).encode("utf-8")).hexdigest() cookieOpt = {'expires' : int(time.time()) + 3600 * 24 * 30} data['cookies'] = { 'email' : { 'value' : base64.b64encode(email.encode('utf-8')).decode("utf-8"), 'opt' : cookieOpt }, 'token' : { 'value' : token, 'opt' : cookieOpt } } response = HttpResponse(json.dumps(data), content_type="application/json") return response else: #比较失败,还在login data = {"status" : 'error', 'msg' : "email or password is error" } return HttpResponse(json.dumps(data), content_type="application/json") else: data = {"status" :'error', 'msg' : "login form is error" } return HttpResponse(json.dumps(data), content_type="application/json") else: data = {"status" : 'error', 'msg' : "login only post method" } return HttpResponse(json.dumps(data), content_type="application/json")