def test_get_by_id(self) -> None: """Get user by ID.""" user = User("*****@*****.**") user.save() retrieved = User.get_by_id(user.id) assert retrieved == user
def test_get_by_id(self): """Get user by ID.""" user = User('foo', '*****@*****.**') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user
def create_user(name, email, phone, about, birth, study, nationality, pic, department): try: if (User.objects.filter(email=email).exists() is False) and \ (User.objects.filter(phone=phone).exists() is False): created_user = User(name=name.lower(), email=email.lower(), phone=phone, birth=birth, pic=pic, about=about, study=study, nationality=nationality) created_user.save() group = None if department is not None: group = GroupReader.GroupReadService.read_group_by_name( name=department) if group is not None: GroupManagement.add_member(created_user.id, group_id=group[0].id) return status.HTTP_201_CREATED else: return status.HTTP_201_CREATED else: return status.HTTP_417_EXPECTATION_FAILED except exceptions.FieldError: return status.HTTP_500_INTERNAL_SERVER_ERROR except exceptions.PermissionDenied: return status.HTTP_500_INTERNAL_SERVER_ERROR
def register_user(phonenumber, email, password, fname, lname, sex, age, address, melli_code, role='USER'): # TODO generate random pass and mail to user password = password password_hash = generate_password_hash(password) registration_time = datetime.utcnow() user = User(phonenumber=phonenumber, password=password_hash, email=email, fname=fname, lname=lname, sex=sex, age=age, address=address, melli_code=melli_code, role=role, datetime=registration_time) return user.save()
def mutate(self, info: ResolveInfo, email: str, password: str, **kwargs) -> "CreateUser": """ Creates a user in the database using the data sent by the user. :param info :type ResolveInfo :param email :type str: user's email :param password :type str: user's unhashed password :return :type CreateUser """ user = User(email=email, password=password, **kwargs) user.save() return CreateUser(id=user.id, email=user.email)
def test_check_password(self): """Check password.""" user = User.create(username='******', email='*****@*****.**', password='******') assert user.check_password('foobarbaz123') assert not user.check_password('barfoobaz')
def create_user(save=True): password = factory.password(10) user = User( login=factory.user_name(), email=factory.email(), password=User.hash_password(password), firstname=factory.first_name(), middlename=factory.name(), lastname=factory.last_name(), is_aproved=True, ) if save: user.save() return user, password
def post(self): self.context['form'] = form = self.form(request.form) # noqa: WPS204 if not form.validate(): return render_template(self.template, **self.context) # noqa: WPS204 login = request.form.get('login') email = request.form.get('email') password = request.form.get('password') firstname = request.form.get('firstname') middlename = request.form.get('middlename') lastname = request.form.get('lastname') image = request.form.get('email') pass_hash = User.hash_password(password) user = User( login=login, email=email, password=pass_hash.decode(), firstname=firstname, middlename=middlename, lastname=lastname, image=image, gravatar='gravatar', ) if User.query.filter_by(login=login).first(): flash('Логин уже занят.', 'error') return render_template( self.template, **self.context, ) if User.query.filter_by(email=email).first(): flash('Такой e-mail уже привязан к другому аккаунту.', 'error') return render_template( self.template, **self.context, ) User.save(user) if send_mail_for_aprove(user): flash( 'Вам на почту отправлена ссылка для подтверждения регистрации', 'info') else: flash('Сбой отправки письма', 'error') return redirect(url_for('auth.login'))
def post(self): form = self.form(request.form) if not form.validate(): return render_template(self.template, **{'form': form}) login = request.form.get('login') email = request.form.get('email') password = request.form.get('password') firstname = request.form.get('firstname') middlename = request.form.get('middlename') lastname = request.form.get('lastname') image = request.form.get('email') pass_hash = User.hash_password(password) user = User( login=login, email=email, password=pass_hash.decode(), firstname=firstname, middlename=middlename, lastname=lastname, image=image, ) if User.query.filter_by(login=login).first(): return render_template( self.template, **{ 'form': form, 'info': 'Логин уже занят' }, ) if User.query.filter_by(email=email).first(): return render_template( self.template, **{ 'form': form, 'info': 'Email уже занят' }, ) User.save(user) if send_mail_for_aprove(user): flash( 'Вам на почту отправлена ссылка для подтверждения регистрации') else: flash('Сбой отправки письма') return redirect(url_for('auth.login'))
def setUp(self): super().setUp() fixture: dict = load_yaml_fixture('auth_test_existed_github_user.yaml') self.user: User = User( email=fixture['email'], login=fixture['login'], github_id=fixture['github_id'], ) self.user.id = fixture['id'] self.user.save()
def create(self, db_session: Session, *, obj_in: UserCreate) -> User: db_obj = User( email=obj_in.email, hashed_password=get_password_hash(obj_in.password), full_name=obj_in.full_name, is_superuser=obj_in.is_superuser, ) db_session.add(db_obj) db_session.commit() db_session.refresh(db_obj) return db_obj
def post(cls): data = request.get_json() user = User.find_by_username(data.get('username')) if user and user.check_password(data.get('password'), user._password): access_token = create_access_token(identity=str(user.id), fresh=True), refresh_token = create_refresh_token(identity=str(user.id)) return { "access_token": access_token, "refresh_token": refresh_token }, 200 return {"message": "Invalid credentials"}, 401
def get_or_create_user_through_github(github_profile: dict) -> User: user: User or None = User.query.filter_by( email=github_profile['email']).first() if user is not None: return user return User( email=github_profile['email'], login=github_profile['login'], is_oauth=True, ).save()
def post(self): form = self.form(request.form) if not form.validate(): return render_template(self.template_name, **self.context) login = request.form.get('login') email = request.form.get('email') firstname = request.form.get('firstname') middlename = request.form.get('middlename') lastname = request.form.get('lastname') user_data = { 'login': login, 'email': email, 'firstname': firstname, 'middlename': middlename, 'lastname': lastname, 'image': email, 'is_oauth': True, } # отдельно смотрим пароль: # если стоит флаг, то меняем # если пароль пустой, то сбрасываем if request.form.get('change_password'): password = request.form.get('password') if request.form.get( 'password') else False pass_hash = User.hash_password( password).decode() if password else '' user_data['password'] = pass_hash if login != self.user.login: if User.query.filter_by(login=login).first(): flash('Логин уже занят.', 'error') return render_template( self.template_name, **{'form': form}, ) if email != self.user.email: if User.query.filter_by(email=email).first(): flash('Такой e-mail уже привязан к другому аккаунту.', 'error') return render_template( self.template_name, **{'form': form}, ) User.query.filter_by(github_id=self.user.github_id).update(user_data) return redirect(url_for('auth.profile_oauth'))
def get_or_create_user_through_github(github_profile: dict) -> User: user: User or None = User.query.filter_by(github_id=str( github_profile['id']), ).first() if user is not None: return user return User( login=github_profile['login'], email=github_profile['email'], firstname=github_profile['name'], github_id=github_profile['id'], image=github_profile['email'], is_oauth=False, is_aproved=True, ).save()
def post(self): form = self.form(request.form) if not form.validate(): return render_template(self.template, **{'form': form}) login = request.form['login'] password = request.form['password'] user = User.query.filter_by(login=login, ).first() if user and User.check_password(user, password): if not user.is_aproved: flash( 'Завершите регистрацию, пройдя по ссылке, отправленной на почту' ) return redirect(url_for('auth.login')) session['auth'] = SessionAuth(True, user) return redirect('/')
def get_or_create_user_through_oauth(service: str, profile: dict) -> User: # ищем участника в базе по id привязке к сервису oauth user: User or None = User.query.filter_by( **{ f'{service}_id': str(profile['id']) }, ).first() # возвращаем, если находим if user is not None: return user # если не находим и в профиле нет email, # то ни создать, ни автоматически привязать не получится, возвращаем пустоту if not profile['email']: return False # если находим, то пытаемся привязать к существующему аккаунту user: User or None = User.query.filter_by(email=profile['email'], ).first() # сессия, чтобы в первый раз отправить на страницу профиля session['oauth_new'] = True if user is not None: return link_user_with_oauth(user, service, profile) # если не находим, то создаём нового пользователя flash(f'Ваш аккаунт был автоматически создан и привязан к {service}.', 'info') return User( **{ 'login': profile['login'], 'email': profile['email'], 'firstname': profile['firstname'], f'{service}_id': profile['id'], 'image': profile['email'], 'is_oauth': True, 'is_aproved': True, }).save()
def post(self): self.context['form'] = form = self.form(request.form) if not form.validate(): return render_template(self.template, **self.context) login = request.form['login'] password = request.form['password'] user = User.query.filter_by(login=login, ).first() if user and User.check_password(user, password): if not user.is_aproved: flash( 'Завершите регистрацию, пройдя по ссылке, отправленной на почту', 'error') return redirect(url_for('auth.login')) session['auth'] = SessionAuth(True, user) if request.referrer and 'answer' in request.referrer: return redirect(request.referrer) return redirect(url_for('index.home')) flash('Неверный логин или пароль!', 'error') return render_template(self.template, **self.context)
def get(self, token): user = User.verify_token_for_mail_aproved(token) if not user: return redirect(url_for('index.index')) return redirect(url_for('auth.login'))
def _foo_user(self) -> User: """Creates and saves foo@bar user.""" user = User(email="*****@*****.**") user.save() return user
def test_password_is_nullable(self): """Test null password.""" user = User(username='******', email='*****@*****.**') user.save() assert user.password is None
def test_created_at_defaults_to_datetime(self): """Test creation date.""" user = User(username='******', email='*****@*****.**') user.save() assert bool(user.created_at) assert isinstance(user.created_at, dt.datetime)
def test(self): # noqa: WPS210 factory: Generator = Faker() chapter_name: str = factory.paragraph() chapter_order_number: int = 1 chapter = Chapter( name=chapter_name, order_number=chapter_order_number, ) Chapter.save(chapter) chapter = Chapter.query.get(1) question_text: str = factory.paragraph() question_order_number: int = 1 question_user_id: int = 1 question = Question( order_number=question_order_number, user=question_user_id, chapter_id=chapter.id, text=question_text, ) Question.save(question) question = Question.query.get(1) user_username: str = factory.md5()[:8] user_password: str = factory.password(8) user_email: str = factory.email() user_firstname: str = factory.first_name() user = User( login=user_username, email=user_email, password=user_password, firstname=user_firstname, is_aproved=True, ) User.save(user) answer_text: str = factory.paragraph() answer_is_approve: bool = True answer_question_id: int = 1 answer_owner_id: int = 1 answer = Answer( text=answer_text, is_approve=answer_is_approve, question_id=answer_question_id, owner_id=answer_owner_id, ) Answer.save(answer) answer = Answer.query.get(1) self.assertEqual(answer.text, answer_text) self.assertEqual(answer.is_approve, answer_is_approve) self.assertEqual(answer.question_id, answer_question_id) response = self.client.get( url_for('answers.answer', question_id=question.id), ) self.assert_200( response, url_for('answers.answer', question_id=question.id), )
def jwt_identity(payload): return User.get_by_id(payload)
def post(self): data = request.get_json() if User.find_by_username(data['username']): return {"message": "A user with this username already exists"}, 400 if not User.query.all(): user = User(**data) user.is_admin = True user.save() return {"message": "Admin successfully created"}, 201 else: user = User(**data) user.is_admin = False user.save() return {"message": "User successfully created"}, 201
def get(self): user = User.find_by_id(get_jwt_identity()) if not user: return {"message": "User not found"}, 404 return user.json()