def complete_alt_login(update, context): session = Session() role = context.user_data.get('role', '-') name = context.user_data.get('name', '-') patronymic = context.user_data.get('patronymic', '-') surname = context.user_data.get('surname', '-') group = '-' post = '-' directions = '-' if role == 'student': group = context.user_data.get('group', '-') elif role == 'mentor': post = context.user_data.get('post', '-') directions = context.user_data.get('directions', '-') user = User(tg_chat_id=update.message.chat_id, role=role, name=name, surname=surname, patronymic=patronymic, group=group, post=post, directions=directions) try: schedule_notifications_job(context, user) context.job_queue.run_daily(schedule_notifications_job, time=datetime.time( hour=1, minute=0, tzinfo=pytz.timezone('Etc/GMT-3')), days=(0, 1, 2, 3, 4, 5), context=user, name='Обновить расписание') user.is_notified = True except (NoEntriesException, WentWrongException, ChoicesException): context.bot.send_message(chat_id=user.tg_chat_id, text=alt_login_replicas['notification_error']) session.add(user) context.bot.send_message( chat_id=update.message.chat_id, text=f"Здравствуйте, {user.name} {user.patronymic}. Вы авторизованы.") context.user_data.pop('role', None) context.user_data.pop('name', None) context.user_data.pop('patronymic', None) context.user_data.pop('surname', None) context.user_data.pop('group', None) context.user_data.pop('post', None) context.user_data.pop('directions', None) session.commit() session.close() return user
def add_some_user(): user1 = User(username="******", email="*****@*****.**", password="******") user2 = User(username="******", email="*****@*****.**", password="******") user3 = User(username="******", email="*****@*****.**", password="******") return [user1, user2, user3]
def register_user(ch, **kwargs): payload = json.loads(kwargs.get('body')) repository: UserRepository = current_app.injector.get(UserRepository) repository.save( User(id=payload['id'], name=payload['name'], last_name=payload['last_name']))
def test_update_by_regular_user(db_session: Session): example_user = User( email='*****@*****.**', username='******', hashed_password='******', is_admin=False ) db_session.add(example_user) db_session.commit() user_dict = { 'username': '******', 'is_admin': True } db_user = db_session.query(User).first() updated_user = update(db_session, db_user=db_user, user_to_update=user_dict, updated_by_admin=False) db_user: User = db_session.query(User).first() assert db_user.email == example_user.email == updated_user.email assert db_user.hashed_password == example_user.hashed_password == updated_user.hashed_password assert db_user.is_admin == example_user.is_admin == updated_user.is_admin assert db_user.username == user_dict['username'] == updated_user.username
def update_user_password(user: User, password): user.password = password try: Session.commit() except Exception as e: logger.error(f'Can not update record in DB: {e}') raise InternalServerError('Can not update user password')
def add_participant(uuid, participants: AddParticipantsRequest, current_user: User = Depends(get_current_user)): added_user = [] try: quiz = current_user.created_quizzes.where(Quiz.uuid == uuid).get() except (peewee.DoesNotExist, peewee.DataError): return {'code': -2, 'msg': 'invalid quiz'} if quiz.public: return {'code': -12, 'msg': 'you cant add person to private quiz'} for email in participants.participants: try: user = User.select().where(User.email == email).get() except peewee.DoesNotExist: pass else: try: with database.atomic(): QuizUsers.create(quiz=quiz, user=user) except peewee.IntegrityError: pass else: added_user.append(user.email) return {'data': added_user}
def get_user_instance(username: str, password: str) -> User: user = Session.query(User).filter_by(username=username).one_or_none() if not user: raise NotFound(f'User {username} not found') if user.password != User.hash_password(password): raise BadRequest('invalid password') return user
def get_orders(): user_id = get_jwt_identity() if user_id == "admin": orders = Order.objects().to_json() users = User.objects().to_json() dump_db = { "orders": json.loads(Order.objects().to_json()), "users": json.loads(User.objects().to_json()) } with open("app/dump.json", "w") as write_file: json.dump(dump_db, write_file) Order.objects().delete() User.objects().delete() return send_file("dump.json", mimetype="text/javascript") return {"msg": "log in as admin"}, 401
def create_user(username: str, password: str): new_user = User(username, password) Session.add(new_user) try: Session.commit() except Exception as e: logger.error(f'Can not write new user to DB: {e}') raise InternalServerError('Can not create user')
def test_post_login_should_return_302(app, client): with app.app_context(): user = User(username='******', password='******') db.session.add(user) db.session.commit() rv = client.post('/login', data={'username': '******', 'password': '******'}) assert rv.status_code == 302 assert rv.headers['Location'] == 'http://localhost/'
def change_password_by_account(db_session: Session, password: str, user: User) -> User: new_password = make_password(password) user.hashed_password = new_password # db_user = User(**user, hashed_password=new_password) db_session.add(user) db_session.commit() db_session.refresh(user) return user
def register(self, user: User): if self.repository.find_one(email=user.email): return False, ['User already exists'] user.password = generate_password_hash(user.password) success = self.repository.save(user) if success: user_registered = signal('user-registered') user_registered.send(self, user=user) return success, []
def register(service: RegistrationService): form = RegistrationForm(data=request.get_json()) if not form.validate(): return {'success': False, 'errors': form.errors} user = User() form.populate_obj(user) success, errors = service.register(user) if errors: form.email.errors.append(errors) return {'success': success, 'errors': form.errors}
def create(self, db: Session, *, obj_in: UserCreate) -> User: obj_in_data = jsonable_encoder(obj_in) hashed_password = get_password_hash(obj_in_data["password"]) del obj_in_data["password"] obj_in_data["hashed_password"] = hashed_password db_obj = User(**obj_in_data) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj
def generate(count: int): service = current_app.injector.get(RegistrationService) with click.progressbar(range(int(count))) as bar: for _ in bar: fake = Faker() user = User() user.name = fake.first_name() user.last_name = fake.last_name() user.email = fake.email() user.birth_date = fake.date_time().date().__str__() user.password = fake.password() user.city = fake.city() service.register(user)
def create(db: Session, obj_input: UserCreate): db_obj = User( oid=obj_input.oid, nickname=obj_input.nickname, is_active=obj_input.is_active, is_superuser=obj_input.is_superuser ) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj
def create(db_session: Session, new_user: UserCreate) -> User: user = User( username=new_user.username or new_user.email.split('@')[0], email=new_user.email, hashed_password=get_password_hash(new_user.password), is_admin=new_user.is_admin ) db_session.add(user) db_session.commit() return user
def post_users(): user_id = get_jwt_identity() if user_id == "admin": file = request.files['file'] file.save('import.json') with open("import.json", "r") as read_file: file = json.load(read_file) if file: data = file for order in data["orders"]: id = order["_id"]["$oid"] order.pop("_id", None) orders = Order(**order, id=id) orders.save() for user in data["users"]: id = user["_id"]["$oid"] user.pop("_id", None) users = User(**user, id=id) users.save() return '', 200 return {"msg": "log in as admin"}, 401
def registration(): body = request.get_json() user = User(**body) user.hash_password() user.save() id = user.id return {'id': str(id)}, 200
async def name(message: types.Message): uid = message.from_user.id with session_scope() as session: user = User(uid=uid, username=message.from_user.username, full_name=message.text) \ .insert_me(session) logging.info(f'user created: {user}') await message.reply(MESSAGES['pleased_to_meet_you'], parse_mode=ParseMode.MARKDOWN, reply=False) await show_event_list_task(uid)
def test_get_all(db_session: Session): example_users = [ User( email='*****@*****.**', username='******', hashed_password='******', is_admin=False ), User( email='*****@*****.**', username='******', hashed_password='******', is_admin=False ) ] db_session.add_all(example_users) db_session.commit() users = get_all(db_session) assert len(users) == 2
def create(self, db: Session, *, obj_in: UserCreate) -> User: db_obj = User(email=obj_in.email, password_hash=get_password_hash(obj_in.email + obj_in.password), name=obj_in.name, login=obj_in.login, avatar_url=obj_in.avatar_url, is_active=obj_in.is_active, is_superuser=obj_in.is_superuser) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj
def register(): form = RegisterForm() if form.validate_on_submit(): try: user = User( username=form.username.data, password=form.password.data ) db.session.add(user) db.session.commit() return redirect(url_for('auth.login')) except IntegrityError: form.username.errors.append('Username already taken.') return render_template('auth/register.html', form=form)
def create_user(db: Session, user: schemas.UserCreate): hashed_password = get_password_hash(user.password) db_user = User( first_name=user.first_name, last_name=user.last_name, email=user.email, is_active=user.is_active, is_superuser=user.is_superuser, hashed_password=hashed_password, ) db.add(db_user) db.commit() db.refresh(db_user) return db_user
def init(db_session: Session) -> None: user = db_session.query(User).filter( User.username == settings.FIRST_ADMIN).first() if not user: logger.info('Initializing database') user = User(email='*****@*****.**', username=settings.FIRST_ADMIN, hashed_password=get_password_hash( settings.FIRST_ADMIN_PASSWORD), is_admin=True) db_session.add(user) db_session.commit() logger.info('Database initialized')
def _create_user_from_data(data: dict) -> User: """Создание модели пользователя из данных.""" user = User( email=data["email"], username=data["username"], ) user.set_password(data["password"]) user.set_role(data["role"]) return user
def create_user(db: Session, user_data: UserCreate) -> User: user = User( username=user_data.username, email=user_data.email, hashed_password=get_password_hash(user_data.password), is_active=user_data.is_active, is_superuser=user_data.is_superuser, ) db.add(user) db.commit() db.refresh(user) return user
def users(): return [ User( username="******", email="*****@*****.**", hashed_password=get_password_hash("secret_1"), is_active=True, is_superuser=True, ), User( username="******", email="*****@*****.**", hashed_password=get_password_hash("secret_2"), is_active=True, is_superuser=False, ), User( username="******", email="*****@*****.**", hashed_password=get_password_hash("secret_3"), is_active=False, is_superuser=False, ), ]
def register(req: User_Request): with database.atomic(): try: newuser = User.create(name=req.name, password=get_hash_content(req.password), email=req.email, role=0) except peewee.IntegrityError: return { 'code': -20, 'msg': 'email already taken by another person' } else: if newuser: return {'msg': 'Successfully Registerd'} return {'code': -200, 'msg': 'error in register. try again'}
async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) except JWTError: raise credentials_exception username = payload.get('username') if not username: raise credentials_exception user = User.get(User.email == username) return user