def register(request): """注册接口""" cookie = request.COOKIES print(cookie) if request.method == "POST": # 忽略参数为空的情况 username = request.POST.get("username", "") if not username: return JsonResponse({"error": "请输入用户名"}) password = request.POST.get("password", "") phone = request.POST.get("phone", "") address = request.POST.get("address", "") email = request.POST.get("email", "") # 新建用户 user = UserModel() user.username = username # 密码加密后存储 user.password = make_password(password) user.phone = phone user.address = address user.email = email user.save() return JsonResponse({"user": "******"}) return render(request, "user/register.html")
def regist(request): """注册接口""" cookie = request.COOKIES print(cookie) if request.method == 'POST': # 格式验证在前端 username = request.POST.get('username','') password = request.POST.get('password','') phone = request.POST.get('phone','') address = request.POST.get('address','') email = request.POST.get('email','') # 保存到数据库 user = UserModel() user.username = username # 密码加密后存储 user.password = make_password(password) user.phone = phone user.address = address user.email = email user.save() return JsonResponse({'user':'******'}) return render(request,'user/regist.html')
def mutate(self, info, name, last_name): user = UserModel(name=name, last_name=last_name) user.save() NewUsersSubscription.broadcast( # Subscription group to notify clients in. group='group42', # Dict delivered to the `publish` method. # Can not pass objects, So pass id And resolve it on Subscription payload=user.id) return CreateUserMutation(user=user)
def register(request): if request.method == 'POST': form = RegisterForm(request.POST or None) form.need_confirm = False if form.is_valid(): clean_data = form.cleaned_data email = clean_data.get('email', None) password = clean_data.get('password', None) validate_code = clean_data.get('validate_code', None) invite_code = clean_data.get('invite_code', None) user = UserModel.objects.filter(email=email) if user: return Response(status=status.HTTP_409_CONFLICT) else: user = UserModel() user.email = email encode_password = make_password(password) user.password = encode_password records = MailCodeModel.objects.filter(code=validate_code) if records: user.active = True invitation = InvitationCodeModel.objects.filter( code=invite_code, active=False) if invitation: invitation.active = True user.invite = True invitation.save() user.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request): form = RegisterForm(request.POST) if form.is_valid() is False: return HttpResponse(render(request, template_name='register.html', context={'form': form}), status=400) data = form.cleaned_data print(data) new_model = UserModel(name=data['name'], email=data['email'], password=data['password'], age=data['age'], gender=data['gender']) new_model.save() request.session['logged-in'] = True request.session['logged-in-user'] = new_model.name return HttpResponseRedirect('/')
def api_auth_setup( model: Setup, db: Session = Depends(get_db) ): if model.user_id == "": raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Blanks are not allowed in id" ) # ユーザがいる場合はセットアップ済みなのでイジェクト if not db.query(UserModel).all() == []: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Already initialized" ) # ユーザ追加 user_model = UserModel( id=model.user_id, hashed_password=pwd_context.hash(model.password) ) db.add(user_model) db.commit() db.add(UserScope(user_id=user_model.id,name="admin")) db.add(UserScope(user_id=user_model.id,name="user")) db.commit() return model
def check_user_name(self, request, *args, **kwargs): u_name = request.data.get("u_name") #获取u_name if UserModel.check_username(u_name): #如果存在u_name存在就抛异常 raise ValidationError(detail="用户名已存在") data = {"status": HTTP_200_OK, "msg": "用户名可用"} return Response(data) #如果不存在,表示用户名可用
def validate(self, attrs): user = self.instance if user is None: user = UserModel(**attrs) if 'password' in attrs: try: validate_password(attrs.get('password'), user=user) attrs['password'] = make_password(attrs['password']) except ValidationError as error: raise serializers.ValidationError( {'password': list(error.messages)}) return super(User, self).validate(attrs)
def register(request): """ 注册 """ if request.method == 'GET': return render(request, 'user/user_register.html') if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') icon = request.FILES.get('icon') # 加密 password = make_password(password) # 加密 if not all([username, password, icon]): msg = '不能为空' return render(request, 'user/user_register.html', {'msg': msg}) #创建用户 user = UserModel(username=username, email=email, password=password, icon=icon) if user: user.save() return HttpResponseRedirect(reverse('axf:mine'))
def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get( Q(email__iexact=username) | Q(username__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate( user): return user return super().authenticate(request, username, password, **kwargs)
def get(self, request, *args, **kwargs): #激活接口 action = request.query_params.get("action") if action == "activate": try: token = request.query_params.get("token") #获取token u_name = cache.get(token) #获取u_name if u_name: #判断u_name是否有数据 cache.delete(token) #有就删除 user = UserModel.get_user(u_name) user.is_active = True user.save() except Exception as e: print(e) # return redirect("/index/") return render(request, "index.html")
def register(request): """注册接口""" if request.method == 'POST': # 忽略参数为空 username = request.POST.get('username', '') if not username: return JsonResponse({'error': '请输入用户名'}) password = request.POST.get('password', '') phone = request.POST.get('phone', '') address = request.POST.get('address', '') email = request.POST.get('email', '') # 新建用户 user = UserModel() user.username = username # 密码加密后存储 user.password = make_password(password) user.phone = phone user.address = address user.email = email user.save() return HttpResponseRedirect('/account/login') return render(request, 'user/register.html')
def do_login(self, request, *args, **kwargs): u_user = request.data.get("u_user") u_password = request.data.get("u_password") user = UserModel.get_user(u_user) if not user.check_password(u_password): raise AuthenticationFailed(detail="密码错误") if not user.is_active: raise PermissionDenied(detail="用户未激活") token = generate_token() cache.set(token, user, timeout=USER_TOKEN_TIMEOUT) data = {"msg": "登录成功", "status": HTTP_200_OK, "data": {"token": token}} return Response(data)
def do_login(self, request, *args, **kwargs): #登录-->就是验证用户名 密码邮箱等是否存在,并验证输入的是否正确, 验证账户的激活状态激活后才能登录 u_user = request.data.get("u_user") #用户名标示 u_password = request.data.get("u_password") user = UserModel.get_user(u_user) if not user.check_password(u_password): raise AuthenticationFailed( detail="密码错误") #AuthenticationFailed 认证失败 if not user.is_active: #判断用户是否 激活 raise PermissionDenied(detail="用户未激活") #权限拒绝 token = generate_token() cache.set(token, user, timeout=USER_TOKEN_TIMEOUT) #用户过期时间 data = {"msg": "登录成功", "status": HTTP_200_OK, "data": {"token": token}} return Response(data)
def mutate(self, info, users, stageIds=[]): code,error,user,timezone = current_user() if not user.role in (ADMIN,SUPER_ADMIN) : raise Exception("Permission denied!") ids = [] with ScopedSession() as local_db_session: duplicated = [] for i in range(len(users) - 1): for j in range(i + 1, len(users)): if users[i].username == users[j].username: duplicated.append(users[i].username) if duplicated: raise Exception('Duplicated username: '******', '.join(duplicated)) existed = [user.username for user in DBSession.query(UserModel).filter(UserModel.username.in_([x.username for x in users])).all()] if existed: raise Exception('Username already existed: ' + ', '.join(existed)) for item in users: user = UserModel( username=item.username, active=True, role=GUEST ) # Add validation for non-empty passwords, etc. user.password = encrypt(item.password) local_db_session.add(user) local_db_session.flush() ids.append(user.id) # Now assigns users into stages stages = DBSession.query(StageModel).filter(StageModel.id.in_(stageIds)).all() for stage in stages: player_access = stage.attributes.filter(StageAttributeModel.name == 'playerAccess').first() if player_access: accesses = json.loads(player_access.description) for user_id in ids: if user_id not in accesses[0]: accesses[0].append(user_id) # append user id to player ids player_access.description = json.dumps(accesses) local_db_session.flush() local_db_session.commit() users = DBSession.query(UserModel).filter(UserModel.id.in_(ids)).all() return BatchUserCreation(users=users)
def get(self, request, *args, **kwargs): action = request.query_params.get("action") if action == "activate": try: token = request.query_params.get("token") u_name = cache.get(token) if u_name: cache.delete(token) user = UserModel.get_user(u_name) user.is_active = True user.save() # request.session["info"] = "激活成功" messages.warning(request._request, "激活成功") except Exception as e: print(e) # request.session["info"] = "激活失败" messages.warning(request._request, "激活失败") return redirect("/index/")
def register(request): if request.method == "POST": user = UserRegisterForm(request.POST) if not user.is_valid(): return JsonResponse(user.errors.get_json_data(), safe=False) username = request.POST.get('username') password = request.POST.get('password') phone = request.POST.get('phone', '') address = request.POST.get('address', '') email = request.POST.get("email", '') user = UserModel() user.username = username user.password = make_password(password) user.phone = phone user.address = address user.email = email user.save() return redirect('/account/login/') return render(request, 'user/register.html')
def mutate(self, info, inbound): data = graphql_utils.input_to_dictionary(inbound) if not data['email'] and data['role'] != GUEST: raise Exception("Email is required!") user = UserModel(**data) user_id = None # Add validation for non-empty passwords, etc. user.password = encrypt(user.password) if not user.role: user.role = PLAYER with ScopedSession() as local_db_session: local_db_session.add(user) local_db_session.flush() user_id = user.id user = DBSession.query(UserModel).filter(UserModel.id==user_id).first() send(user.email, f"Welcome to UpStage!", user_registration(user)) admin_emails = [admin.email for admin in DBSession.query(UserModel).filter(UserModel.role.in_([SUPER_ADMIN,ADMIN])).all()] approval_url = f"{request.url_root}backstage/admin/player-management" send(','.join(admin_emails), f"Approval required for {user.username}'s registration", admin_registration_notification(user, approval_url)) return CreateUser(user=user)
def sign_up(request): form = RegisterForm(request.POST or None) if request.method == 'POST' and form.is_valid(): clean_data = form.cleaned_data email = clean_data.get('email', None) password = clean_data.get('password', None) validate_code = clean_data.get('validate_code', None) invite_code = clean_data.get('invite_code', None) user = UserModel.objects.filter(email=email) if user: form.add_error(None, '邮箱已注册') else: user = UserModel() user.email = email encode_password = make_password( password ) user.password = encode_password records = MailCodeModel.objects.filter(code=validate_code) if records: user.active = True invitation = InvitationCodeModel.objects.filter(code=invite_code, active=False) if invitation: invitation.active = True user.invite = True invitation.save() user.save() if request.session.test_cookie_worked(): request.session.delete_test_cookie() request.session['user_id'] = user.id return HttpResponseRedirect(reverse('image_browser:home')) return render(request, 'register.html', {'form': form})
def post(self, request): username = request.data["nickName"] userrole = request.data["role"] userlevel = request.data["level"] print(username) print(userrole) print(request.data) try: find1 = UserModel.objects.filter(U_name=username).first() except: find1 = None if (find1): find2 = UserModel.objects.filter(U_name=username, U_role=userrole).first() # find2 = find1.objects.filter(U_role=userrole).first() if find2: if int(userlevel) > int(find2.U_level): find2.U_level = userlevel find2.save() else: user = UserModel() user.U_name = username user.U_level = userlevel user.U_role = userrole user.save() return HttpResponse(status=200) else: user = UserModel() user.U_name= username user.U_level = userlevel user.U_role = userrole # print(user.role) user.save() return HttpResponse(status=200) return HttpResponse(status=200)
def register(request): """ 用户注册 :param request:POST :return: 注册成功返回登陆页面 注册失败返回提示信息 """ if request.method == 'POST': register_form = forms.RegisterForm(request.POST) register_error = "请检查填写的内容!" if register_form.is_valid(): nick_name = register_form.cleaned_data['nick_name'] password = register_form.cleaned_data['password'] tel = register_form.cleaned_data['tel'] email = register_form.cleaned_data['email'] username = register_form.cleaned_data['username'] std_num = register_form.cleaned_data['std_num'] std_class = register_form.cleaned_data['std_class'] same_tel = UserModel.objects.filter(tel=tel) nick_name_only = UserModel.objects.filter(nick_name=nick_name) if same_tel: register_error = '该手机号已被注册,请使用别的手机号码!' return render(request, 'login/register.html', locals()) if nick_name_only: register_error = '此昵称已存在!' return render(request, 'login/register.html', locals()) new_user = UserModel() new_user.nick_name = nick_name new_user.username = username new_user.password = hash_code(password) new_user.tel = hash_code(tel) new_user.email = email new_user.std_num = std_num new_user.std_class = std_class new_user.save() avatar = UserAvatar(user=new_user) avatar.save() return redirect("userApp:login") else: return render(request, 'login/register.html', locals()) register_form = forms.RegisterForm() return render(request, 'login/register.html', locals())