def test_create_user(_not_logged_in_client): payload = {"confirmation_url": "http://phenopolis.org/confirm/"} response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing user name" payload["user"] = "******" response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing password" payload["argon_password"] = "******" response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing email" user_name = "test_register1" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" _assert_create_user(db_session, _not_logged_in_client, user) finally: # cleans the database _clean_test_users(db_session, user_name)
def post_signup(): """ Post sign up page """ form = SignupForm() uf = UserFactory() params = { 'title': 'Sign up', } # validate form if form.validate_on_submit(): user = uf.get_by_email(form.email.data) # if user is already exists if user: params['error'] = 'User is already registered' return render_template('login.html', **params) instance = User(name=form.name.data, email=form.email.data, created_at=datetime.now()) instance.set_password(form.password.data) uf.save(instance) return render_template('thanks.html') if len(form.errors) > 0: params['errors'] = [x[0] for x in form.errors.values()] return render_template('login.html', **params)
def test_create_and_confirm_user(_not_logged_in_client): user_name = "test_register2" email = "*****@*****.**" with session_scope() as db_session: try: # creates a user user = User() user.user = user_name user.argon_password = "******" user.email = email _assert_create_user(db_session, _not_logged_in_client, user) # confirms the user confirmation_token = generate_confirmation_token(user.email) response = _not_logged_in_client.get( f"/user/confirm/{confirmation_token}") assert response.status_code == 200 observed_user = db_session.query(User).filter( User.user == user.user).first() assert observed_user.user == user.user assert observed_user.enabled, "Enabled field is not true" assert observed_user.confirmed, "Confirmed field is not true" assert observed_user.confirmed_on is not None finally: # cleans the database _clean_test_users(db_session, user_name)
def test_delete_user_itself(_not_logged_in_client): user_name = "temp_user" with session_scope() as db_session: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" _assert_create_user(db_session, _not_logged_in_client, user) confirmation_token = generate_confirmation_token(user.email) response = _not_logged_in_client.get( f"/user/confirm/{confirmation_token}") assert response.status_code == 200 # login with new user resp = _not_logged_in_client.post("/login", json={ "user": f"{user.user}", "password": f"{user.argon_password}" }) assert resp.status_code == 200 assert resp.json == { "success": "Authenticated", "username": f"{user.user}" } # # try to delete another user response = _not_logged_in_client.delete( "/user/demo", content_type="application/json") assert response.status_code == 403 # user deletes itself response = _not_logged_in_client.delete( f"/user/{user_name}", content_type="application/json") assert response.status_code == 200
async def _get(self): id = self.get_argument("id", None) username = self.get_argument("username", None) password = self.get_argument("password", None) page = int(self.get_argument("page", "1")) size = int(self.get_argument("size", "10")) card = User(id=id, username=username, password=password) cards, count = card.query(page=page, size=size) return self.send_json({'cards': cards, 'count': count})
def change_user_ignore(update): with db_session: user_id = update.message.from_user.id user = User.get(tg_user_id=user_id) if not user: insert_user_by_update(update) user = User.get(tg_user_id=user_id) user.tg_user_ignore = 1 ^ user.tg_user_ignore commit() return user.tg_user_ignore
def add_user(email, password): """ 添加用户 """ user = User() user.email = email user.salt = random_str(6) user.password = password_encrypt(password, user.salt) db_session.add(user) db_session.commit() return user
def insert_user_by_update(update): with db_session: user_id = update.message.from_user.id query = User.select(lambda p: p.tg_user_id == user_id) if not list(query): User(tg_user_id=update.message.from_user.id, tg_user_username=update.message.from_user.username, tg_user_nickname="{} {}".format( update.message.from_user.first_name, "" if not update.message.from_user.last_name else update.message.from_user.last_name), tg_user_ignore=0) commit()
def test_create_user_without_email(_not_logged_in_client): user_name = "test_register4" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" response = _not_logged_in_client.post( "/user", json=user.as_dict(), content_type="application/json") assert response.status_code == 400 finally: # cleans the database _clean_test_users(db_session, user_name)
def handle_add_user(json): print('add user using: ' + repr(json)) user = User(**json['data']) SS.add(user) SS.flush() print('user added') emit('user_added', { 'message': 'user {0} has been added, id: {1}'.format(user.emailAddress, user.userId), 'user': User.dump(user), }, broadcast=True)
def get_or_create_anon_user(context: PeeweeContext): name = "unregistered_user" with context.db.atomic(): try: user = User.get(User.user_name == name) return user except DoesNotExist: user = User.create(user_name=name, role=UserRoles.ANON, salt="", password="", coupons=4) user.save() return user
def test_get_coupon_state(testing_db): def get_admin_and_user_data() -> Tuple[Dict, Dict]: response = hug.test.cli('get_coupon_state', module='main', collect_output=True) out = parse_csv(response) a: Dict = next(a for a in out if a['name'] == ADMIN) u: Dict = next(a for a in out if a['name'] == USER) assert len(out) == 2 return a, u admin_1, user_1 = get_admin_and_user_data() assert int(admin_1['num_bookings']) == 0 assert int(user_1['num_bookings']) == 0 assert int(admin_1['coupons']) == 10 assert int(user_1['coupons']) == 10 User.update({ User.coupons: User.coupons + 11 }).where(User.user_name == USER).execute() admin_2, user_2 = get_admin_and_user_data() assert int(admin_2['num_bookings']) == 0 assert int(user_2['num_bookings']) == 0 assert int(admin_2['coupons']) == 10 assert int(user_2['coupons']) == 21 Booking.create( surname="Mustermann", first_name="Marianne", phone="0123456789", office="MusterOffice", secret="SECRET", booked_by=USER, booked_at=datetime.now(), appointment=(Appointment.create(booked=True, time_slot=(TimeSlot.create( start_date_time=datetime.now(), length_min=15)))), ) User.update({ User.coupons: User.coupons - 1 }).where(User.user_name == USER).execute() admin_3, user_3 = get_admin_and_user_data() assert int(admin_3['num_bookings']) == 0 assert int(user_3['num_bookings']) == 1 assert int(admin_3['coupons']) == 10 assert int(user_3['coupons']) == 20
async def _signup(self): data = tornado.escape.json_decode(self.request.body) user = User(username=data['username']) _, c = user.explict_query() assert c == 0, "用户已存在" user = User(**data) user.add() return self.send_json(user.model2dict(user))
def test_accept_accepted_user(self, api_client, db_session, tst_username, tst_email, tst_password): """Testing: accepting user that already is accepted Steps: - add user with <username> to DB - accept user with <username> - send GET http://<APP_HOST>:<APP_PORT>/api/accept_user/<username> request - check that user with <username> is still accepted - delete test data from DB Expected result: - Resp code 304 - 'access' filed for <username> is 1 """ try: db_session.add( User(username=tst_username, password=tst_password, email=tst_email, access=1)) db_session.commit() except IntegrityError: raise UnexpectedDBData() test_user = db_session.query(User).filter_by(username=tst_username).first() db_session.commit() if test_user is None: raise DBDataNotFound() accepting = api_client.accept_user(tst_username) # delete test data from DB db_session.query(User).filter_by(username=tst_username).delete() db_session.commit() assert test_user.access == 1 and accepting.status == 304
def test_block_user(self, api_client, db_session, tst_username, tst_email, tst_password): """Testing: that user is blocked after request Steps: - add user with <username> to DB - check that user with <username> is not blocked - send GET http://<APP_HOST>:<APP_PORT>/api/block_user/<username> request - check that user with <username> is blocked - delete test data from DB Expected result: - Resp code 200 - 'access' filed for <username> is 0 """ try: db_session.add( User(username=tst_username, password=tst_password, email=tst_email, access=1)) db_session.commit() except IntegrityError: raise UnexpectedDBData() test_user = db_session.query(User).filter_by(username=tst_username).first() db_session.commit() if test_user is None: raise DBDataNotFound() blocking = api_client.block_user(tst_username) # delete test data from DB db_session.query(User).filter_by(username=tst_username).delete() db_session.commit() assert test_user.access == 0 and blocking.status == 200
def register(): print(request.remote_addr) # get 方法访问,说明是主页连接过来,返回login页面 if request.method == 'GET': return render_template('register.html') # 如果是POST方法访问过来,说明是当前页面提交的登录请求 if request.method == 'POST': print(request) print(request.form) name = request.form.get('username') phone = request.form.get('user-phone') email = request.form.get('user-email') password = request.form.get('user-pwd') new_user = User(name=name, pwd=password, email=email, phone=phone) new_user.add() return render_template('login.html')
def get_or_create_auto_user(db: PeeweeSession, role: str, name: str): coupons = 4 if ( role == UserRoles.ANON ) else config.Ldap.user_coupon_number if role == UserRoles.USER else 1 with db.atomic(): try: user = User.get(User.user_name == name) return user except DoesNotExist: user = User.create(user_name=name, role=role, salt="", password="", coupons=coupons) user.save() return user
def test_del_user(self, api_client, db_session, tst_username, tst_email, tst_password): """Testing: that user is deleted after request Steps: - add user with <username> to DB - send GET http://<APP_HOST>:<APP_PORT>/api/del_user/<username> request - check that user with <username> is removed from DB - delete test data from DB Expected result: - Resp code 204 - No user in DB with <username> """ try: db_session.add( User(username=tst_username, password=tst_password, email=tst_email)) db_session.commit() except IntegrityError: raise UnexpectedDBData() test_user = db_session.query(User).filter_by(username=tst_username).first() db_session.commit() if test_user is None: raise DBDataNotFound() deleting = api_client.del_user(tst_username) test_user = db_session.query(User).filter_by(username=tst_username).first() # delete test data from DB if it is still there if test_user is not None: db_session.query(User).filter_by(username=tst_username).delete() db_session.commit() assert test_user is None and deleting.status == 204
def test_main_without_vk_id(self, login_page, db_session, tst_username, tst_email, tst_password): """Testing: that main page displays "LOGGED as: <username>" and no vk_id because it's unavailable Steps: - get logged main page Expected result: - main page displays "LOGGED as: <username>" and no vk_id """ try: db_session.add( User(username=tst_username, password=tst_password, email=tst_email, access=1, active=0)) db_session.commit() except IntegrityError: raise UnexpectedDBData() self.page = login_page self.page.login(tst_username, tst_password) test_user = db_session.query(User).filter_by( username=tst_username).first() db_session.commit() # delete test data from DB db_session.query(User).filter_by(username=tst_username).delete() db_session.commit() assert self.driver.current_url == URL_MAIN and self.page.find( MainLocators.TEXT_VKID)
def test_motivation(self, db_session, login_page, tst_username, tst_email, tst_password): """Testing: that main page motivation message id displayed Steps: - get logged main page Expected result: - main page footer motivation message id displayed """ try: db_session.add( User(username=tst_username, password=tst_password, email=tst_email, access=1, active=0)) db_session.commit() except IntegrityError: raise UnexpectedDBData() self.page = login_page self.page.login(tst_username, tst_password) motivation = self.page.find(MainLocators.TEXT_MOTIVATION) # delete test data from DB db_session.query(User).filter_by(username=tst_username).delete() db_session.commit() assert motivation is not None
def note_index_post_page(): """ 添加用户笔记 """ editor = g.curr_user data = {} form = NoteForm() data['is_error'] = False uid = form.uid.data user = None if uid: user = User.get(uid) if not user: user = editor if form.validate(): note = add_note(form.title.data, form.content.data, user, editor, x=form.x.data, y=form.y.data, z=form.z.data) to_redirect = redirect(url_for('note_page.note_index_page', uid=uid)) return to_redirect else: data['is_error'] = True data['form'] = form notes, pages = get_user_recent_notes(user, limit=60) data['notes'] = notes data['pages'] = pages return render('/note/index.html', **data)
def add_users(session): session.add( User( appen_id=keys.test_user_appen_id, email_address="*****@*****.**", given_name="Test", family_name="User", ))
def set_coupon_count(db: directives.PeeweeSession, user_name: hug.types.text, value: hug.types.number): """ [--user_name] <string> [--value] <number>; set the user coupon_count to <value> """ with db.atomic(): user = User.get(User.user_name == user_name) user.coupons = value user.save()
def inc_coupon_count(db: directives.PeeweeSession, user_name: hug.types.text, increment: hug.types.number): """ [--user_name] <string> [--increment] <number>; increment the user coupon_count, to decrement give a negative number """ with db.atomic(): user = User.get(User.user_name == user_name) user.coupons += increment user.save()
def get_user(user_name: str, context: PeeweeContext): with context.db.atomic(): try: return User.get(User.user_name == user_name) except DoesNotExist: log.warning("user not found: %s", user_name) return False except DatabaseError: log.exception("unknown error logging in: %s", user_name) return False
def check_user_ignore(update): user_id = update.message.from_user.id with db_session: query = User.select(lambda p: p.tg_user_id == user_id) if not list(query): return False user = list(query) if user[0].tg_user_ignore is True: return True return False
def test_get_coupon_state(testing_db): admin_1, user_1 = _get_admin_and_user_data() assert int(admin_1['num_bookings']) == 0 assert int(user_1['num_bookings']) == 0 assert int(admin_1['coupons']) == 10 assert int(user_1['coupons']) == 10 User.update({User.coupons: User.coupons + 11}).where(User.user_name == USER).execute() admin_2, user_2 = _get_admin_and_user_data() assert int(admin_2['num_bookings']) == 0 assert int(user_2['num_bookings']) == 0 assert int(admin_2['coupons']) == 10 assert int(user_2['coupons']) == 21 Booking.create( surname="Mustermann", first_name="Marianne", phone="0123456789", office="MusterOffice", secret="SECRET", booked_by=USER, booked_at=datetime.now(), appointment=( Appointment.create( booked=True, time_slot=( TimeSlot.create( start_date_time=datetime.now(), length_min=15) ) ) ), ) User.update({User.coupons: User.coupons - 1}).where(User.user_name == USER).execute() admin_3, user_3 = _get_admin_and_user_data() assert int(admin_3['num_bookings']) == 0 assert int(user_3['num_bookings']) == 1 assert int(admin_3['coupons']) == 10 assert int(user_3['coupons']) == 20
def get_or_add_user(session, username): if username is None: username = '' user = db.user_repository.get_user(session, username) if user is None: logging.debug(f'Adding user {username}') user = User(username=username) session.add(user) session.flush() return user
def _add_one_user(db: directives.PeeweeSession, username: hug.types.text, password: hug.types.text = None, role: hug.types.one_of(UserRoles.user_roles()) = UserRoles.USER, coupons: hug.types.number = 10): with db.atomic(): name = username.lower() salt = get_random_string(2) secret_password = password or get_random_string(12) hashed_password = hash_pw(name, salt, secret_password) user = User.create(user_name=name, role=role, salt=salt, password=hashed_password, coupons=coupons) user.save() return {"name": user.user_name, "password": secret_password}
def test_delete_user(_admin_client): user_name = "test_register6" with session_scope() as db_session: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" _assert_create_user(db_session, _admin_client, user) # deletes user response = _admin_client.delete(f"/user/{user_name}", content_type="application/json") assert response.status_code == 200 # confirms it does not exist o_user = db_session.query(User).filter(User.user == user_name).first() assert o_user is None, "Deletion was not successful" # try to delete non-existent user response = _admin_client.delete("/user/not_me", content_type="application/json") assert response.status_code == 404
def before_request(): """ Do sth before each request. """ clean_resource() # var init. g.curr_user = None g.req_start_time = time.time() user_id = get_user_id_from_cookie() if user_id > 0: # todo(myth) 根据cookie查询数据,获取用户名 curr_user = User.get(user_id) if curr_user: g.curr_user = curr_user
def note_index_page(): """ 用户的笔记 """ data = {} editor = g.curr_user uid = request.args.get('uid', type=int, default=0) user = None if uid: user = User.get(uid) if not user: user = editor form = NoteForm() form.uid.data = user.id data['form'] = form notes, pages = get_user_recent_notes(user, limit=60) data['notes'] = notes data['pages'] = pages return render('/note/index.html', **data)