class TestUserModel(unittest.TestCase): def setUp(self): self.class_under_test = UserModel() @patch('core.models.user.User') def test_should_get_all(self, mock_user_get_all): user = UserModel() user.username = "******" user.id = 12 mock_user_get_all.query.all.return_value = [user] users = self.class_under_test.get_all() self.assertEqual(1, len(users)) user = users[0] self.assertEqual(12, user.id) self.assertEqual('Foo', user.username) def test_should_verify_password(self): password = '******'; self.class_under_test.hash_password(password) self.assertTrue(self.class_under_test.verify_password(password)) @patch('core.db.session.commit', return_value=None) @patch('core.db.session.add', return_value=None) def test_save(self, mock_add, mock_commit): user = UserModel() user.username = "******" user.id = 12 user.save()
def login(): try: data = {} if request.form["password"] != request.form["password2"]: raise Exception("Паролі не співпадають") if request.form["name"] == "": raise Exception("Ім'я не може бути пустим") if len(request.form["password"]) > 0 and len( request.form["password"]) < 6: raise Exception("Пароль не може менше 6ти знаків") if request.form["password"]: data["pass"] = request.form["password"] u = User() data["name"] = request.form["name"] data["access_id"] = request.form["access_id"] user = u.update(request.args.get("id"), data) return make_response(redirect("/admin/users.html")) except Exception as e: print(e) return make_response( render_template("admin/user.html", error=str(e), params=request.args.to_dict(), user=g.user))
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### user_table = op.create_table( 'user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=32), nullable=False), sa.Column('password_hash', sa.String(length=128), nullable=False), sa.Column('created', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False), sa.Column('updated', sa.TIMESTAMP(), server_default=sa.text( 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')), sa.PrimaryKeyConstraint('id')) op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True) # ### end Alembic commands ### # insert users user = UserModel() username = app.config['AUTH_USERNAME'] password = app.config['AUTH_PASSWORD'] user.hash_password(password) hash_password = user.password_hash op.bulk_insert(user_table, [{ 'username': username, 'password_hash': hash_password }])
def main(): userLoc = User() users = userLoc.list() logging.info('HomeHandler:: users ??? ') logging.info('HomeHandler:: users '+ json.dumps(users)) article = Article() articles = article.list() logging.info('HomeHandler:: articles ??? ') logging.info('HomeHandler:: articles '+ json.dumps(articles))
def enumerate(): user = User() if not request.args.get('search') is None: search = json.loads(request.args.get('search')) else: search = None start = request.args.get('start') limit = request.args.get('limit') data = user.enumerate(search=search, start=start, limit=limit) return jsonify(data)
def test_should_get_all(self, mock_user_get_all): user = UserModel() user.username = "******" user.id = 12 mock_user_get_all.query.all.return_value = [user] users = self.class_under_test.get_all() self.assertEqual(1, len(users)) user = users[0] self.assertEqual(12, user.id) self.assertEqual('Foo', user.username)
def collect_members(self, members_url): members = [] if self.args.verbose: Helpers.print_success("Collecting members") last_page = Helpers.get_last_page(members_url) last_page = last_page + 1 if last_page == 0 else last_page for i in range(1, (last_page + 1)): result = Helpers.request("{}?page={}".format(members_url, i)) if result: if self.args.include_users: members.append( list( filter( bool, [ self.collect_user(mem["login"], with_repositories=False) for mem in result ], ))) else: members.append([ User(mem["login"], None, None, None, None) for mem in result ]) return Helpers.flatten(members)
def setUp(self): self.user_manager = UserManager() self.user = User(id=123456789, first_name='chris', last_name='imberti', email='*****@*****.**', username='******', password='******', about='this is me', location='San Francisco, CA', website='https://stoksinterest.io/chris', image_url='http://chris', gender='male')
class UserManagerTestCase(unittest.TestCase): def setUp(self): self.user_manager = UserManager() self.user = User(id=123456789, first_name='chris', last_name='imberti', email='*****@*****.**', username='******', password='******', about='this is me', location='San Francisco, CA', website='https://stoksinterest.io/chris', image_url='http://chris', gender='male') def test_add_user(self): ret = self.user_manager.add_one(self.user) self.assertEquals(ret, 1) self.user['email'] = '*****@*****.**' ret = self.user_manager.update_one(self.user) self.assertEquals(ret, 1) self.user = self.user_manager.get_one(username='******') self.assertEquals(self.user.get('email'), '*****@*****.**') def test_delete_user(self): ret = self.user_manager.delete_one(self.user) self.assertEquals(ret, 1) def tearDown(self): pass
def post(self): data = parser.parse_args() current_user = User.query.filter_by(username=data['username']).first() if not current_user: return { 'message': 'User {} doesn\'t exist.'.format(data['username']) }, 400 error_message = {'message': 'Wrong credentials.'}, 400 try: if User.verify_hash(data['password'], current_user.password): access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return { 'message': 'Logged in as {}.'.format(current_user.username), 'access_token': access_token, 'refresh_token': refresh_token } return error_message except ValueError: return error_message
def user_edit(): """ 用户编辑 :return: 响应结果 """ form = ModifyUserForm() # Flask 校验参数 if form.validate_on_submit(): user = User(id=form.id.data, sex=form.sex.data, email=form.email.data, qq=form.qq.data, icon=form.icon.data) rs = security_user_handler.user_edit(user) success_value = ResponseEnum.SUCCESS.value return jsonify( ResponseDTO(code=success_value["code"], msg=success_value["msg"], data=rs.nickname).__dict__) validate_error = ResponseEnum.PARAM_VALIDATE_ERROR.value return jsonify( ResponseDTO(code=validate_error["code"], msg=validate_error["msg"], data=form.errors).__dict__)
def collect_user(self, username): Helpers().print_success("Collecting information of {} in Bitbucket".format(username)) url = "{}/users/{}".format(self.base_url, username) result = Helpers().request(url) if result: repos = self.collect_repositories("{}/repositories/{}".format(self.base_url, username)) return User(result["username"], result["display_name"], None, result["website"], repos) return False
def run(self): role1 = Role.query.filter_by(name="admin").first() admin_user = User(first_name="Patrick",\ last_name = "Adonteng", email = "*****@*****.**", password="******", confirmed=True, bday=date(1988,10,30), role= role1) self.db.session.add(admin_user) self.db.session.commit()
def login_user(self, user): if user is not None and len(user) > 0: data = User(user[3], f'{user[1]} {user[2]}', user[-1]) auth_interface_imp = AuthInterfaceConcrete(data) self.app.get('managers', 'AuthManager').login(auth_interface_imp) self.app.log('Successful login') else: self.app.log('Wrong credentials')
def main(message_data): user = User(message_data['user_id']) message = Message(message_data['messages'], user.id) therapy_session = TherapySession(user.id) bot = BotFactory.create(user, message, therapy_session) bot.reply() message.mark_done()
def signup(): if request.method == 'POST': username = request.form.get('username').encode('utf-8') first_name = request.form.get('firstname').encode('utf-8') last_name = request.form.get('lastname').encode('utf-8') email = request.form.get('email').encode('utf-8') password = request.form.get('password').encode('utf-8') user = User(username=username, first_name=first_name, last_name=last_name, email=email, password=password) user = base.managers.user_manager.add_one(user) # TODO: do this in a better way if user: login_handler.login_user(user.get('id'), user.get('username')) return render_template('profile.html') flash('Invalid login.', 'danger') return render_template('signup.html')
def load_user(): user_data = {} if "sess_id" in request.cookies: sess = Session() s = sess.read(request.cookies["sess_id"]) if not s is None and "user_id" in s: user = User() user_data = user.read(s["user_id"]) pass g.user = user_data
def login(): try: email=request.form["email"] password=request.form["password"] u=User() user=u.login(email,password) if user is None: return make_response(render_template("/login.html")) print(user) sess=Session() s=sess.create({"user_id":user["id"]}) if request.args.get("u"): url=request.args.get("u") else: url="/index.html" resp=make_response(redirect(url)) resp.set_cookie('sess_id', str(s["id"])) return resp except e: print(" [x] Error: " + str(e))
def collect_user(self, username): userid = self.get_userid(username) Helpers().print_success( "Collecting information of {} in Gitlab".format(username)) url = "{}/users/{}".format(self.base_url, userid) result = Helpers().request(url) if result: repos = self.collect_repositories("{}/users/{}/projects".format( self.base_url, userid)) return User(result["username"], result["name"], None, result["bio"], repos) return False
def post(username, password): if username is None or password is None: abort( 400, message="Missing arguments." ) has_user = UserModel \ .query \ .filter(UserModel.username == username) \ .first() if has_user is not None: abort( 400, message="User with username: "******" already exist." ) user = UserModel(username=username) user.hash_password(password) user.save() return ({'id': user.id, 'username': user.username}, 201)
def collect_user(self, username, with_repositories=True): Helpers().print_success( "Collecting information of {} in Github".format(username)) url = "{}/users/{}".format(self.base_url, username) result = Helpers().request(url) if result: repos = None if with_repositories: repos = self.collect_repositories("{}/repos".format(url)) return User(result["login"], result["name"], result["email"], result["bio"], repos) return False
def test_creation(self): user = User("Igor", 25, "*****@*****.**", "igornsa", "password") self.assertEqual(user.name, 'Igor') self.assertEqual(user.age, 25) self.assertEqual(user.email, '*****@*****.**') self.assertEqual(user.username, "igornsa") self.assertEqual(user.password, "password") self.assertNotEqual(user.name, "Olar") self.assertNotEqual(user.age, -1) self.assertNotEqual(user.email, "*****@*****.**") self.assertNotEqual(user.username, "rogihc") self.assertNotEqual(user.password, "!senha!")
def main(message_data): """ This func is called by worker. :param message_data: :return: """ user = User(message_data['user_id']) message = Message(message_data['messages'], user.id) therapy_session = TherapySession(user.id) bot = BotFactory.create(user, message, therapy_session) bot.reply() message.mark_done()
def post(self): data = parser.parse_args() if User.query.filter_by(username=data['username']).scalar(): response = jsonify({ 'message': 'The user {} already exists.'.format(data['username']) }) response.status_code = 409 return response new_user = User(username=data['username'], password=User.generate_hash(data['password'])) new_user.save() access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return { 'message': 'User {} was created.'.format(data['username']), 'access_token': access_token, 'refresh_token': refresh_token }
def __send_remind(cls, remind_users): for user_id in remind_users: user = User(user_id) MyDB.send_responses(StringConstant.remind_text.value, None, user.sender_id, user_id, ['REMIND']) send_quick_replies(user.sender_id, StringConstant.remind_quick_replies_title.value, StringConstant.remind_quick_replies.value, "REMIND_ASK_MOOD") latest_session_id = models.Session.find_latest_id_by_user_id( user_id) models.Session.update_status(latest_session_id, SessionStatus.ended.value) models.Remind.register_remind(user_id)
def userauthentication(): import getpass cursor = get_Cursor() """ Gets account no., password and check in db returns user object """ flag = False cursor.execute("select * from users") # cursor = get_Cursor() data = cursor.fetchall() while flag == False: # user authentication acc = int(input("Enter your account no.:")) if acc == 0: break passwd = getpass.getpass("Enter your password:"******"Account no. or the password is wrong. Try again.") print("Press 0 to skip signin") # returns true if user verified else false if flag == True: # get firstname, lastname, datecreated, and balance cursor.execute("select firstname from users where accno = %s", (acc, )) firstname = cursor.fetchone() cursor.execute("select lastname from users where accno = %s", (acc, )) lastname = cursor.fetchone() cursor.execute("select date_created from users where accno = %s", (acc, )) datecreated = cursor.fetchone() cursor.execute("select balance from users where accno = %s", (acc, )) balance = cursor.fetchone() # return User object print("You are signed in.") return User(acc, firstname, lastname, datecreated, balance) if flag == False: return None
def get_user_by_id(self, user_id: int) -> User: """ Gets user by id from db or creates user in db :param user_id: user id in Telegram :return: User object """ session = self.session user = session.query(User).filter(User.id == user_id).one_or_none() if user: session.close() return user new_user = User(id=user_id) session.add(new_user) session.commit() session.refresh(new_user) return new_user
def process_users_dict(self, users_dict: Dict) -> Dict[str, User]: users = {} for user_name, user_properties in users_dict.items(): user_task_names = user_properties.get("tasks") user_tasks = [] for task_name in user_task_names: current_task = self.get_task(task_name) if current_task is None: raise BaseConfigParserException( "Task %s does not exist for user %s" % (task_name, user_name)) else: user_tasks.append(current_task) user_rate = user_properties.get("rate", 1) current_user = User( name=user_name, task_list=user_tasks, rate=user_rate, ) users[user_name] = current_user return users
def post(self): user_schema = UserSchema(unknown=EXCLUDE) json_data = request.form['data'] if not json_data: return {"error": "No input data provided."}, 400 try: new_user = user_schema.load(json_data) except ValidationError as err: raise SchemaValidationError try: db_user = User(**new_user) db.session.add(db_user) db.session.commit() except IntegrityError: db.session.rollback() raise EmailAlreadyExistsError result = user_schema.dump(User.query.get(db_user.id)) return {"message": "Account created successfully", "data": result}, 201
def get_unsent_responses(): try: unsent_messages = models.Response.find_unsent_message_data() # e.g. unsent_messages = [(response_id, user_id, response_text),...] if len(unsent_messages) == 0: return [] models.Response.update_response_sent_flag(unsent_messages) unsent_messages = [list(i) for i in unsent_messages] for idx, user_id in enumerate([i[1] for i in unsent_messages]): user = User(user_id) unsent_messages[idx].append(user.sender_id) res_list = [[i[1], i[2], i[3]] for i in unsent_messages] return res_list except: logging.exception('') return []
def test_staticmethod_verify_hash(init_db, new_user): user_hash = User.generate_hash(new_user.password) assert User.verify_hash(new_user.password, user_hash)
def new_user(): return User(username='******', password='******')
def setUp(self): self.user = User("Igor", 25, "*****@*****.**", "igornsa", "password")
class TestUser(TestBase): def setUp(self): self.user = User("Igor", 25, "*****@*****.**", "igornsa", "password") def test_creation(self): user = User("Igor", 25, "*****@*****.**", "igornsa", "password") self.assertEqual(user.name, 'Igor') self.assertEqual(user.age, 25) self.assertEqual(user.email, '*****@*****.**') self.assertEqual(user.username, "igornsa") self.assertEqual(user.password, "password") self.assertNotEqual(user.name, "Olar") self.assertNotEqual(user.age, -1) self.assertNotEqual(user.email, "*****@*****.**") self.assertNotEqual(user.username, "rogihc") self.assertNotEqual(user.password, "!senha!") def test_setters(self): self.user.set_age(13) self.assertEqual(self.user.age, 13) self.assertNotEqual(self.user.age, 25) self.user.set_name("Ursula") self.assertNotEqual(self.user.name, 'Igor') self.assertEqual(self.user.name, 'Ursula') self.user.set_email("*****@*****.**") self.assertNotEqual(self.user.email, "*****@*****.**") self.assertEqual(self.user.email, "*****@*****.**") self.user.set_password("******") self.assertNotEqual(self.user.password, "password") self.assertEqual(self.user.password, "******") def test_report(self): self.user.report_lost("Achei uma bolsa", "Lorem Ipsum", "Estojo", "LCC1", "14/02/2017", "1", None, "3331-2163") self.assertEqual(len(self.user.reports), 1) self.user.report_found("Achei uma bolsa", "Lorem Ipsum", "Estojo", "LCC1", "14/02/2017", "1", None, "3331-2163") self.assertEqual(len(self.user.reports), 2)