def post(self, request): """ 登录页面post访问,接受登录表单提交 表单验证成功则重定向到主页,否则重定向到登录页面的get 登录成功会在session中存储student_id,存储后将通过student_login_require拦截器验证 :param request:HttpRequest对象 :return: 返回HttpResponse对象获取,render() """ login_form = LoginForm(request.POST) if login_form.is_valid(): user = UserModel.objects.filter( name=login_form.cleaned_data.get('name'))[0] if user.is_superuser: auth.login(request, user) my_print('用户:{:}登录'.format(user.name)) request.session['success_info'] = '登录成功' return redirect(reverse('cms:index')) else: my_print('权限控制,禁止{:}访问'.format(user.name)) request.session['error_info'] = '您没有访问的权限' return redirect(reverse('cms:login')) error = login_form.get_first_error() win32api.MessageBox(0, u'您没有访问的权限', u'提示', win32con.MB_OK) request.session['error_info'] = error return redirect(reverse('cms:login'))
def post(self, request, *args, **kwargs): form = LoginForm(request.POST) next = request.GET.get('next') message = '' if form.is_valid(): auth_field = form.cleaned_data['auth_field'] password = form.cleaned_data['password'] try: user_obj = User.objects.get( Q(email__exact=auth_field) | Q(username__exact=auth_field) | Q(mobile__exact=auth_field)) except ObjectDoesNotExist: message = 'There is no such user' else: user = authenticate(username=user_obj.username, password=password) if user: if user.is_active: login(request, user) if next: return redirect(next) else: return redirect('index') else: message = 'User is deactivate' else: message = 'email or password is invalid' return render(request, 'user/login.html', {'form': form, 'message': message})
def indexPage(request): if request.method == "POST": # trae el formulario Loginform desde el template log_in = LoginForm(request.POST) model_username = request.POST.get('username') # trae el campo model_password = request.POST.get('password') if (model_username != None) and (model_password != None): # pregunta se no son vacios try: # solo trata el error de contraseña if log_in.is_valid(): # verifica el formulario traido con respecto al modelo en forms.py user = authenticate(username=model_username, password=model_password) # logea login(request, user) # este lo agrega al request # mensaje de usuario logeado messages.success(request, 'User name is: '+model_username) current_user = request.user # trae de la request el usuario actual logeado # trae de la base de datos el usuario user = User.objects.get(username=model_username) if login: # si loguin es correcto # direcciona a la funcion return mostrar_notas(request) else: return redirect('index') # direcciona al index else: # mensaje de no validado messages.success(request, 'data error :') return redirect('index') except AttributeError: return redirect('index') else: return redirect('index') # trae el form registre user del template newUser = registerUser(request.POST) model = User # tra el molde User if newUser.is_valid(): # valida el formulario # limpia el username que es afectado al validar model.username = newUser.cleaned_data["username"] model.email = newUser.cleaned_data["email"] model.password1 = newUser.cleaned_data["password1"] model.password2 = newUser.cleaned_data["password2"] if (type(model.password1) != int) and (model.password1 != model.email) and (model.password1 != model.username) and (len(model.password1) > 7) and (model.password1 == model.password2): # verifica la contraseña grabar = User(username=model.username, email=model.email, password=model.password1) # instancia un User grabar.save() # graba # busca en la base de datos el useario recien registrado user = User.objects.get(username=model.username) user.is_staff = True # lo agrega como usuario staff user.is_active = True # lo agrega como usuario activo user.set_password(model.password1) # codifica el pass user.save() # graba las lineas anteriores messages.success( request, 'New user create whit name '+model.username) # mensaje de usuario creado # envia al index return render(request, 'login/index.html', {'newUser': newUser, "log_in": log_in}) else: print("error en el formulario") # error en la contraseña else: newUser = registerUser() # envia el formulario de forms.py al template log_in = LoginForm() # envia el formulario login de forms.py al template # recarga index return render(request, 'login/index.html', {'newUser': newUser, "log_in": log_in})
def post(self, request): form = LoginForm(request.POST) if form.is_valid(): user = User.objects.get(user_name=form.cleaned_data['user_name']) user.login_status = True user.save() return render(request, 'user/my_profile.html', {'user': user}) return render(request, 'user/login_form.html', {'form': form})
def indexPage(request): if request.method == "POST": log_in = LoginForm(request.POST) model_username = request.POST.get('username') model_password = request.POST.get('password') if (model_username != None) and (model_password != None): logemail = User.POST.get(email=model_username) try: user = authenticate(username=logemail.username, password=model_password) login(request, user) except: if log_in.is_valid(): user = authenticate(username=model_username, password=model_password) login(request, user) current_user = request.user user = User.objects.get(username=model_username) # messages.success(request, 'User name is: '+model_username) return mostrar_notas(request) else: # messages.success(request, 'data error :') return redirect('index') newUser = registerUser(request.POST) model = User if newUser.is_valid(): model.username = newUser.cleaned_data["username"] model.email = newUser.cleaned_data["email"] model.password1 = newUser.cleaned_data["password1"] model.password2 = newUser.cleaned_data["password2"] grabar = User(username=model.username, email=model.email, password=model.password1) if (model.password1 == model.password2): grabar.save() user = User.objects.get(username=model.username) user.is_staff = True user.is_active = True user.set_password(model.password1) user.save() username = newUser.cleaned_data.get('username') password = newUser.cleaned_data.get('password1') user = authenticate(request, username=username, password=password) if user: login(request, user) return mostrar_notas(request) # messages.success(request, 'New user create whit name '+model.username) else: newUser = registerUser() log_in = LoginForm() return render(request, 'login/index.html', { 'newUser': newUser, "log_in": log_in })
async def post(self, *args, **kwargs): r_data = {} params = self.request.body.decode("utf-8") params = json.loads(params) form = LoginForm.from_json(params) if form.validate(): mobile = form.mobile.data password = form.password.data try: user = await self.application.objects.get(User, mobile=mobile) if not user.verify_password(password): self.set_status(400) r_data["non_fields"] = "用户名或密码错误" else: # 成功登录 # RESTFul 无法设置cookies,另外前后端分离很可能跨域 token = user.generate_auth_token() r_data["id"] = user.id r_data["token"] = token r_data["nickname"] = (user.nickname if user.nickname is not None else user.mobile) except User.DoesNotExist as e: self.set_status(400) r_data["mobile"] = "用户不存在" self.finish(r_data)
def get(self, request): """ 登录页面get访问 :param request:HttpRequest对象 :return: 返回HttpResponse对象或者render() """ login_form = LoginForm() context = {'form': login_form} return render(request, 'front/login.html', context=context)
def post(self, request, *args, **kwargs): # 表单验证 login_form = LoginForm(request.POST) if login_form.is_valid(): # 从页面获取信息 user_name = login_form.changed_data["username"] password = login_form.changed_data["password"] # 进行验证,判断user_name和password是否存在 user = authenticate(username=user_name, password=password) if user is not None: # 查询到用户 login(request, user) # 登录成功后,要返回页面 return HttpResponseRedirect(reverse("index")) else: # 未查询到用户 return render(request, "login.html", {"msg":"用户名或密码错误"}) else: return render(request, "login.html", {"msg": "用户名或密码错误"})
def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): identity = request.POST.get('identity', '') user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') if identity == 'admin': #管理员登录 user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) return HttpResponse('{"status":"success","url":"/"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"用户名或者密码错误"}', content_type='application/json') elif identity == 'teacher': #教师登录 user = authenticate(username=user_name, password=pass_word) if user is not None and user.is_teacher: login(request, user) return HttpResponse('{"status":"success","url":"/"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"用户名或者密码错误"}', content_type='application/json') elif identity == 'student': #学生登录 user = authenticate(username=user_name, password=pass_word) if user is not None and user.is_student: login(request, user) return HttpResponse('{"status":"success","url":"/"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"用户名或者密码错误"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"用户名或者密码格式不正确"}', content_type='application/json')
async def post(self): # 返回的数据 ret_data = {} loginForm = LoginForm(self.request.arguments) if loginForm.validate(): username = loginForm.username.data password = loginForm.password.data try: user = await self.application.objects.get(User, username=username) if not user.password.check_password(password): # 密码验证错误 self.set_status(400) ret_data['non_fields'] = "用户名或密码错误" else: # 登录成功 # 生成json web token payload = { "id": user.id, "username": user.username, "exp": datetime.now() } token = jwt.encode(payload, self.settings['secret_key'], algorithm='HS256') ret_data['username'] = user.username ret_data['token'] = token.decode("utf8") except User.DoesNotExist as e: self.set_status(400) ret_data["mobile"] = "用户不存在" return self.finish(ret_data)
def indexPage(request): if request.method == "POST": log_in = LoginForm(request.POST) model_username = request.POST.get('username') model_password = request.POST.get('password') if (model_username != None) and (model_password != None): try: if log_in.is_valid(): user = authenticate(username=model_username, password=model_password) login(request, user) messages.success(request, 'User name is: ' + model_username) current_user = request.user user = User.objects.get(username=model_username) if login: return mostrar_notas(request) else: return redirect('index') else: messages.success(request, 'data error :') return redirect('index') except AttributeError: return redirect('index') else: print("") return redirect('index') newUser = registerUser(request.POST) model = User if newUser.is_valid(): model.username = newUser.cleaned_data["username"] model.email = newUser.cleaned_data["email"] model.password1 = newUser.cleaned_data["password1"] model.password2 = newUser.cleaned_data["password2"] print("entro") if (model.password1 != model.email ) and (model.password1 != model.username) and (len( model.password1) > 7) and (model.password1 == model.password2): grabar = User(username=model.username, email=model.email, password=model.password1) grabar.save() print("grabo") user = User.objects.get(username=model.username) user.is_staff = True user.is_active = True user.set_password(model.password1) user.save() return render(request, 'login/index.html', { 'newUser': newUser, "log_in": log_in }) messages.success(request, 'New user create whit name ' + model.username) else: print("error en el formulario") else: newUser = registerUser() log_in = LoginForm() return render(request, 'login/index.html', { 'newUser': newUser, "log_in": log_in })
def get(self, request): form = LoginForm() return render(request, 'user/login_form.html', {'form': form})
def login(self, request): form = LoginForm(request, data = request.POST if request.POST else None) if form.is_valid(): return HttpResponseRedirect(request.GET.get('back', '/blog/')) return {'form': form}