def login(): form = LoginForm() regform = RegisterForm() error = None if form.validate_on_submit() or regform.validate_on_submit(): if request.form['btn'] == 'Login': user = User.query.filter_by(username=form.username.data).first() if bcrypt.hashpw( form.password.data.encode('utf8'), user.password.encode('utf8')) == user.password.encode( 'utf8'): #decrypt password session['username'] = form.username.data return redirect(url_for('index')) else: error = "Incorrect username and password" else: # Check if username exists usernames = [u.username for u in User.query.all()] if regform.username.data in usernames: address = (str(regform.house_number) + " " + regform.street + " " + regform.city + ", " + regform.state + " " + str(regform.zip_code)) else: # Add user to DB # 574 22nd Ave San Francisco, CA 94121 address = str( regform.house_number ) + " " + regform.street + " " + regform.city + ", " + regform.state + " " + str( regform.zip_code) print(address) passwordEncrypt = bcrypt.hashpw( regform.password.data.encode('utf8'), bcrypt.gensalt()) #encrypt password regUser = User(regform.fullname.data, regform.email.data, regform.username.data, passwordEncrypt, address) db.session.add(regUser) db.session.commit() #simulate that the record is written # db.session.flush() # error = "Registration failed!" return render_template('user/login.html', form=form, regform=regform, error=error)
def post(self, request): data = json.loads(request.body) try: account = data['account'] if account_validate(account): if account_overlap(account): raise ValidationError('ACCOUNT_OVERLAPED') else: raise ValidationError('INVALID_ACCOUNT_INPUT') email = data.get('email', None) if (email): password = data['password'] name = data['name'] phone_number = data['phone_number'] address = data['address'] email_validate(email) email_overlap(email) password_validate(password) phone_number_validate(phone_number) password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) password = password.decode('utf-8') User( account=account, password=password, name=name, email=email, phone_number=phone_number, address=address, gender=data['gender'], birth=data['birth'], ).save() return JsonResponse({'message': 'SIGNUP_SUCCESS'}, status=200) return JsonResponse({'message': 'ACCOUNT_SUCCESS'}, status=200) except KeyError: return JsonResponse({'message': 'KEY_ERROR'}, status=400) except ValidationError as e: return JsonResponse({'message': e.message}, status=400)
def load_user(id_): """ flask-login的回调函数,从每次请求的session中读取用户id 调用此函数根据id查询数据库返回用户对象,找不到时候要返回None :param id_: :return: """ user = None try: user = mongo.db.user.find_one({"username": id_}) if user is None: raise NoResultFound() user = User(user["username"]) except MultipleResultsFound as e: # TODO: deal with MultipleResultsFound pass finally: return user
def pub(request: HttpRequest): post = Post() content = Content() try: # 1.新增博文 及内容 playload = simplejson.loads(request.body) title = playload['title'] post.title = title post.postdate = datetime.datetime.now( datetime.timezone(datetime.timedelta(hours=8))) post.author = User(id=request.user.id) # 注入id post 表中只要id post.save() contents = playload['content'] content.post = post content.content = contents content.save() return JsonResponse({"post_id": post.id}) except Exception as e: return HttpResponseBadRequest() # 如果出现异常返回实例
def register(request, *args, **kwargs): post_data = json.loads(request.body) email = post_data.get("email") password = post_data.get("password") if (email == None) or (password == None): return JsonResponse({'msg': "Please provide all the fields"}, status=400) password = hashlib.sha256(password.encode()).hexdigest() user = User(email=email, password=password) user.save() verify_token = VerifyToken(user=user) verify_token = verify_token.save() return JsonResponse({ 'msg': "Welcome to Mesh, Please verify your account sent to your Email" })
def pub(request: HttpRequest): post = Post() content = Content() try: payload = simplejson.loads(request.body) post.title = payload['title'] post.author = User(id=request.user.id) post.postdate = datetime.datetime.now( datetime.timezone(datetime.timedelta(hours=8))) post.save() content.content = payload['content'] content.post = post content.save() return JsonResponse({'post_id': post.id}) except Exception as e: print(e) return HttpResponseBadRequest()
def register(request): if request.method == 'POST': mobile = request.POST.get('mobile') password = request.POST.get('password') verify = request.POST.get('verify') user = User() try: mobile_re = '^1[3456789]\d{9}$' if not re.match(mobile_re, mobile): return JsonResponse({'code': -1, 'msg': '请输入正确手机号'}) # if verify != request.session[mobile]: # return JsonResponse({'code': -1, 'msg': '短信验证未通过'}) user.password = make_password(password) uuid_id = str(uuid.uuid4()).replace('-', '')[:11] User.objects.create(mobile=mobile, password=password, uuid=uuid_id) except Exception as e: print(e) return JsonResponse({'code': -1, 'msg': '注册失败'}) return JsonResponse({'code': -1, 'msg': '注册成功'})
def post(self): if not "user_id" in request.json or not "password" in request.json: error = {"code": "MISSING_USER_ID_OR_PASSWORD"} return jsonify({'error': error}), 400 existing_user = User.objects.filter( user_id=request.json.get('user_id')).first() if existing_user: error = {"code": "USER_ID_ALREADY_EXISTS"} return jsonify({'error': error}), 400 else: # create the credentials salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(request.json.get('password'), salt) user = User( user_id=request.json.get('user_id'), password=hashed_password, domain=request.json.get('domain'), ).save() return jsonify({'result': 'ok'})
def setUp(self): currency = Currency.objects.create(name='USD') google = LoginInfo.objects.create(name="Google") facebook = LoginPlatform.objects.create(name='Facebook') profile = UserProfile( profile_header="Hello, I am JunePyo", currency=currency, ) profile.save() user = User(id='12345', username='******', fullname='JunePyo Suh', profile=profile, birthdate=datetime.date(1995, 11, 11)) user.save() LoginInfo.objects.create(platform=google, user=user, email='*****@*****.**')
def post(self, request): data = json.loads(request.body) try: email = data["email"] password = bcrypt.hashpw(data["password"].encode('utf-8'), bcrypt.gensalt()).decode('utf-8') phone_number = data["phone_number"] name = data["name"] if '@' not in email: return JsonResponse({'message': 'INVALID_KEY'}, status=400) if '.' not in email: return JsonResponse({'message': 'INVALID_KEY'}, status=400) if len(password) < 8: return JsonResponse({'message': 'INVALID_KEY'}, status=400) if User.objects.filter(email=email): return JsonResponse({'message': 'INVALID_KEY'}, status=400) if User.objects.filter(phone_number=phone_number): return JsonResponse({'message': 'INVALID_KEY'}, status=400) if User.objects.filter(name=name): return JsonResponse({'message': 'INVALID_KEY'}, status=400) user = User( email = email, password = password, phone_number = phone_number, name = name, ) user.save() return JsonResponse({'message': 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'message': 'INVALID_KEY'}, status=400) except IntegrityError: return JsonResponse(status=400)
def create(self, request): data = UserSerilizer(data=request.data) if not data.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST, data={'message': 'invalid data'}) new_user = User() UserSerilizer(data=request.data) new_user.first_name = data['first_name'].value new_user.last_name = data['last_name'].value new_user.tel = data['tel'].value new_user.user_role = int(data['user_role'].value) new_user.save() return Response(data={ 'data': { 'user': request.data }, 'message': 'valid data' }, status=status.HTTP_201_CREATED)
def post(self, request): try: data = json.loads(request.body) email = data['email'] password = data['password'] date_of_birth = data['date_of_birth'] phone_number = data['phone_number'] user_validation = User.objects.filter( kakao_id__isnull=True).filter(email=email) if user_validation: return JsonResponse({'MESSAGE': 'ACCOUNT_EXISTS_ALREADY'}, status=400) if not re.match(REGEX_EMAIL, email) or not re.match( REGEX_PASSWORD, password): return JsonResponse({'MESSAGE': 'INVALID_EMAIL_OR_PASSWORD'}, status=400) if not re.match(REGEX_DATE_OF_BIRTH, date_of_birth): return JsonResponse({'MESSAGE': 'INVALID_DATE_OF_BIRTH'}, status=400) if not re.match(REGEX_PHONE_NUMBER, phone_number): return JsonResponse({'MESSAGE': 'INVALID_PHONE_NUMBER'}, status=400) hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') User( email=email, password=hashed_password, date_of_birth=date_of_birth, phone_number=phone_number, ).save() return JsonResponse({'MESSAGE': 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'MESSAGE': 'INVALID_KEY'}, status=400) except ValueError: return ValueErrorTypeChecking(data)
def post(self, request): data = { 'name': request.POST.get('name'), 'email': request.POST.get('email'), 'password': make_password(request.POST.get('password')), 'mobile': request.POST.get('mobile'), 'role': 2 } try: userObj = User(**data) userObj.save() messages.success(request, 'User Registered successfully !!') return redirect('faculty-list') except IntegrityError as e: messages.error( request, "This email is already exists Please try with another email") return render(request, 'admin/faculty_create.html', {})
def create_user(user_profile, provider, token): user = User.objects.filter(email=user_profile.get('email')).first() social_account = SocialAccount(provider=provider, token=token, uid=user_profile.get('id'), extra_data=user_profile) if settings.LINK_SOCIAL_ACCOUNT_WITHOUT_LOGIN and user: social_account.user = user elif not user: user = User(email=user_profile.get('email'), first_name=user_profile.get('name')) user.save() social_account.user = user else: return None social_account.save() return social_account
def recipe(): ingredient = Ingredient() ingredient.name = "test_name_ingredient" ingredient.amount = "test_amount_ingredient" ingredient.save() user = User() user.name = 'test_name' user.email = "*****@*****.**" user.password = "******" user.save() recipe = Recipe() recipe.recipe_name = 'test_recipe' recipe.preparation_mode = 'test_preparation_mode' recipe.chef = user recipe.save() recipe.ingredient.add(ingredient) return recipe
def post(self, req_data): user = User() copy_attr(req_data, user) db.session.add(user) try: db.session.commit() except IntegrityError as e: db.session.rollback() if req_data["username"] == None or req_data["email"] == None: abort(422, "Username or email cannot be null") else: abort(422, "Username or email is already taken") except Exception as e: db.session.rollback() abort(422, e.orig.args[0]) json_result = user_serializer.dump(user) return json_result, 200
def add(db_session, data, username): logger.info(LogMsg.START) schema_validate(data, USER_ADD_SCHEMA_PATH) logger.debug(LogMsg.SCHEMA_CHECKED) new_username = data.get('username') # adder = check_user(username,db_session) user = check_by_username(new_username, db_session) if user: logger.error(LogMsg.USER_XISTS, new_username) raise Http_error(409, Message.USERNAME_EXISTS) logger.debug(LogMsg.USR_ADDING) model_instance = User() model_instance.username = new_username model_instance.password = data.get('password') populate_basic_data(model_instance, username, data.get('tags')) logger.debug(LogMsg.POPULATING_BASIC_DATA) person_id = data.get('person_id') if person_id: person_is_valid = validate_person(person_id, db_session) logger.debug(LogMsg.PERSON_EXISTS, {'person_id': person_id}) if person_is_valid: if person_is_valid.is_legal: person_user = get_by_person(person_id, db_session) if person_user is not None: logger.error(LogMsg.LEGAL_PERSON_USER_RESTRICTION) raise Http_error(409, Message.LEGAL_PERSON_USER_RESTRICTION) model_instance.person_id = person_id else: logger.error(LogMsg.INVALID_USER, {'person_id': person_id}) raise Http_error(404, Message.INVALID_USER) db_session.add(model_instance) logger.debug(LogMsg.DB_ADD, model_to_dict(model_instance)) logger.info(LogMsg.END) return model_instance
def signup(): """ Handle signup process """ # instantiate form form = SignupForm() # set up blank error error = None # check form was submitted - checks that form didn't have any errors (from validators) if form.validate_on_submit(): # using werkzeug.security hashed_password = generate_password_hash(form.password.data, method='sha256') # create a user from those form records user = User( # access form data by .data form.fullname.data, form.email.data, form.username.data, hashed_password, str(url_for('static', filename='images/profile_picture.png')), None, str(url_for('static', filename='images/newspaper.jpg')), None, True ) # add to database db.session.add(user) # flush - sqlalchemy simulates that record is written, and provide id etc. However, doesn't hit database yet - can always throw back db.session.flush() # if we have user id - validation if user.id: # actually commit transaction to database db.session.commit() # redirect to user login return redirect(url_for('login')) else: # undo flush by rollback() db.session.rollback() error = "Error creating user" flash(error) # render template and pass in form return render_template('user/signup.html', form=form, error=error)
def register(): if request.method == 'POST': # 先取出所有的参数 如果没有提交就是空格 nickname = request.form.get('nickname', '').strip() password = request.form.get('password', '').strip() gender = request.form.get('gender', '').strip() bio = request.form.get('bio', '').strip() city = request.form.get('city', '').strip() birthday = request.form.get('birthday', '').strip() avatar = request.files.get('avatar') if avatar: avatar_path = '/static/upload/%s' % nickname else: avatar_path = '/static/upload/default' # 创建用户 user = User( nickname=nickname, password=gen_password(password), # 选择性别 gender=gender if gender in ['male', 'female'] else 'male', bio=bio, city=city, birthday=birthday, # 处理头像地址 保存在某一个文件中 出问题再加上 手动写进来 avatar=avatar_path, created=datetime.datetime.now() ) db.session.add(user) # 进行一个异常处理 try: # 会设计事务的提交和回滚的处理 db.session.commit() except IntegrityError: # 数据回滚 db.session.rollback() return render_template('register.html', error='昵称已被占用,请换一个') save_avatar(nickname,avatar) flash('注册成功!') return redirect('/user/login') else: return render_template('register.html')
def post(self, request): form = RegisterForm(request.POST, request.FILES) if form.is_valid(): new_user = User().add_user(form.cleaned_data) if new_user: Mailer().send(new_user.email, 'sign_up', context={"login": new_user.username}) return HttpResponseRedirect('/register/done/') else: message = 'Ошибка при регистрации пользователя: ' + str( form.cleaned_data) else: message = 'Ошибка при регистрации пользователя, проверьте поля ' return render(request, "user/register.html", { "form": form, "message": message, "context": Context.get(request) })
def register(): form = RegisterForm() if form.validate_on_submit(): salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(form.password.data, salt) user = User(form.fullname.data, form.email.data, form.username.data, hashed_password) try: db.session.add(user) db.session.commit() flash('User created successfully!', 'success') flash( 'Please contact the admin to be be approve your account to login!', 'success') flash('Admin info is found in the Contact tab!', 'success') return redirect(url_for('login')) except SQLAlchemyError as e: db.session.rollback() flash('User already exists!', 'error') return render_template('user/register.html', form=form)
def test_post_acl_set_without_login(self): user = User(username='******') user.save() aclobj = ACLBase(name='hoge', created_user=user) params = { 'object_id': str(aclobj.id), 'object_type': str(aclobj.objtype), 'acl': [ { 'member_id': str(user.id), 'member_type': 'user', 'value': str(ACLType.Writable.id)}, ], 'default_permission': str(ACLType.Nothing.id), } resp = self.client.post(reverse('acl:set'), json.dumps(params), 'application/json') self.assertEqual(resp.status_code, 401)
def register(): if request.method == 'POST': nickname = request.form.get('nickname') password = request.form.get('password') birthday = request.form.get('birthday') user = User(nickname=nickname, password=make_password(password), birthday=birthday) try: # 保存到数据库 db.session.add(user) db.session.commit() return redirect('/user/') except IntegrityError: db.session.rollback() return render_template('register.html', err='您的昵称已被占用') else: return render_template('register.html')
def save(self): user = User( email=self.validated_data['email'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], role=self.validated_data['role'], birth_date=self.validated_data['birth_date'], is_active=self.validated_data['is_active'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if self.validated_data['role'] != 1: user.is_staff = True if password != password2: raise serializers.ValidationError( {'password': '******'}) user.set_password(password) user.save() return user
def register(request): if request.method == 'POST': data=json.loads(request.body) email = data['email'] password = data['password'] password2 = data['password2'] try: user = User.objects.get(email=email) except User.DoesNotExist: user = None if user == None and password == password2: #유저를 만든다. username = email.split('@')[0] user = User(email = email, password = password, username = username) user.save() return JsonResponse({'result': True, 'id': username}) else: return JsonResponse({'result': False})
def post(self, *args, **kwargs): face = self.get_argument('face') username = self.get_argument('username') if not (face and username): self.render('register.html', error='注册信息请填写完整') user = session.query(User).filter(User.username == username).first() if user: self.render('register.html', error='该账号已被使用') img = face.split(',')[-1] if not register_face_user(img, username): self.render('register.html', error='注册失败') user = User() user.username = username session.add(user) session.commit() file = base64.b64decode(img) img_dir = os.path.join(IMAGE_DIR, username + '.jpg') with open(img_dir, 'wb') as f: f.write(file) self.write('注册成功')
def register_user(request): data = json.loads(request.body) user_id = data.get('openid') user = User.objects.filter(openid=user_id) if not user: address = data.get('country') + ' ' + data.get( 'province') + ' ' + data.get('city') user = User(openid=user_id, name=data.get('nickName'), avatar=data.get('avatarUrl'), address=address) user.save() for item in all_provinces: province = Province.objects.get(name=item) Gone(user=user, province=province).save() for achievement in achievements: Achievement(name=achievement, user=user).save() return JsonResponse({'status': True}) else: return JsonResponse({'status': True, 'openid': user_id})
def post(self, request): # 接受用户提交的注册信息 data = request.POST form = RegisterModelForm(data) if form.is_valid(): # 数据合法 cleaned_data = form.cleaned_data # 操作数据库, 创建一个用户 user = User() user.user_phone = cleaned_data.get('user_phone') # 将密码进行加密 user.user_password = set_password(cleaned_data.get('password2')) # 然后将用户信息保存到数据库 user.save() # 跳转到登录界面 return redirect(reverse('user:login')) else: # 不合法 return render(request, 'user/reg.html', context={"form": form})
def post(self, request): user_data = json.loads(request.body) try: User( name = user_data['name'], account = user_data['account'], password = bcrypt.hashpw(user_data['password'].encode('utf-8'), bcrypt.gensalt()).decode(), email = user_data['email'], birthday = user_data['birthday'], gender_type = Gender.objects.get(name = user_data['gender_type']), phoneNumber = user_data['phoneNumber'], skinType = SkinType.objects.get(name = user_data['skinType']), skinTrouble = user_data['skinTrouble'], skinSensitivity = user_data['skinSensitivity'] ).save() return JsonResponse({'message':'SIGNUP_SUCCESS'}, status=200) except KeyError: return JsonResponse({'message':'KEYERROR'}, status=400)
def send_otp(request): phone = request.query_params.get('phone', None) if phone is None: return Response({'error': 'Missing phone param.'}, status=status.HTTP_400_BAD_REQUEST) try: user = User.objects.get(phone=phone) except: try: user = User(phone=phone) user.full_clean(exclude=['password']) user.save() except ValidationError as e: return Response({'error': e}, status.HTTP_400_BAD_REQUEST) # Write OTP sending logic here. Using any third party api_view Otp.objects.create(user=user, otp=randint(111111, 999999)) return Response({'message': 'We\'ve sent an OTP to your phone'}, status=status.HTTP_201_CREATED)