def test_user_login_failure(self): with self.assertRaises(BadRequest) as context: # wrong email User().login("*****@*****.**", "loanjamestest") self.assertEquals(context.exception.message, "User '*****@*****.**' login failed") with self.assertRaises(BadRequest) as context: # wrong email User().login("*****@*****.**", "123456") self.assertEquals(context.exception.message, "User '*****@*****.**' login failed")
def test_user_authenticate_invalid_token_failure(self): with self.assertRaises(BadRequest) as context: # Authenticate User().authenticate( "thisisatesttokennotarealtokenbutitlookslikeitright") self.assertEquals(context.exception.message, "Token is invalid")
def admin_admin_add(): form = AddAdminForm() profile = Profile.query.filter_by(user_id=current_user.id).all() if form.validate_on_submit(): new_user = User(username=form.username.data, email=form.email.data, password=user_manager.hash_password( form.password.data)) db.session.add(new_user) db.session.commit() db_manager.add_user_role(new_user, 'Admin') db_manager.commit() new_profile = Profile(firstname=form.firstname.data, middlename=form.middlename.data, lastname=form.lastname.data, gender=form.gender.data, nationality=form.nationality.data, user_id=new_user.id) db.session.add(new_profile) db.session.commit() flash('New admin added', 'success') return redirect(url_for('admin_admins')) return render_template('admin_admin_add.html', form=form, profile=profile[0])
def test_user_authenticate_corrupted_token_failure(self): payload = { 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS) } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) with self.assertRaises(BadRequest) as context: # Authenticate User().authenticate(jwt_token) self.assertEquals(context.exception.message, "Token is corrupted")
def test_user_authenticate_unauthorized_failure(self): payload = { 'user_id': "this-is-a-test-user-id", 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS) } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) with self.assertRaises(Unauthorized) as context: # Authenticate User().authenticate(jwt_token) self.assertEquals(context.exception.message, "User is not authorized")
def test_user_login_success(self): # Login + JWT jwt_token = User().login("*****@*****.**", "loanjamestest") # Decode JWT payload = jwt.decode(jwt_token, JWT_SECRET, algorithms=[JWT_ALGORITHM]) # Fetch user user = User.query.get(payload['user_id']) # Asserts self.assertIsNotNone(user) self.assertEqual(user.email, "*****@*****.**")
def test_user_00_add_success(self): # Add user User(email=test_user['email']).add(test_user['password']) # Fetch user user = db.session.query(User).filter( User.email == test_user['email']).one() # Has password password h_password = bcrypt.hashpw(test_user['password'].encode('utf-8'), user.salt.encode('utf-8')).decode() self.assertEquals(h_password, user.h_password)
def login(): """Endpoint to login to the application. :return: a JSON object containing the JWT to be used for further actions. """ # Parse payload payload = request.get_json(force=True, silent=True) if ('email' not in payload or 'password' not in payload): raise BadRequest("e-mail address and password required") # Create JWT token jwt_token = User().login(payload['email'], payload['password']) return jsonify({"jwt_token": jwt_token}), 200
def initdb_command(): """Initializes the database.""" is_database_up = False for _ in range(3): # Three attempts before giving up try: # Initialize database db.create_all() is_database_up = True break except Exception: time.sleep(5) if not is_database_up: raise AssertionError("Database is not up") app.logger.info('Database successfully initialized') for row in csv.DictReader(open("/usr/local/share/users.csv", 'r')): User(email=row['email']).add(row['password'])
def test_user_authenticate_success(self): # Login + JWT jwt_token = User().login("*****@*****.**", "loanjamestest") # Authenticate User().authenticate(jwt_token)
def sendUserData(token, product, user: User): logging.info('user is %s', user.to_dire().__str__()) params = {'token': token, 'data': {}} userData = { 'name': user.nick, 'phone': user.mobile, 'media': product.pushName, 'loan_limit': user.amount, 'repay_term': 12, 'credit': user.overdue, 'house': 0, 'car': 0, 'is_work': 0, 'is_fund': 0, 'is_insurance': 0, 'id_card': user.idCard, 'city_id': user.city, 'profession': user.profession, 'gender': 0, 'salary_bank_private': user.salaryPayment, 'salary': 0 } if not userData['media']: userData['media'] = product.name pass if user.estate == 3: userData['house'] = 0 pass else: userData['house'] = 1 pass if user.car == 3: userData['car'] = 0 pass else: userData['car'] = 1 pass if user.profession == 5: userData['is_work'] = 0 pass else: userData['is_work'] = 1 pass if user.provident == 3: userData['is_fund'] = 0 pass else: userData['is_fund'] = 1 pass if user.lifeInsurance == 2: userData['is_insurance'] = 0 pass else: userData['is_insurance'] = 1 pass if user.sex == 1: userData['gender'] = 1 pass else: userData['gender'] = 0 pass if user.income == 1: userData['salary'] = 4000 pass elif user.income == 2: userData['salary'] = 6000 pass elif user.income == 3: userData['salary'] = 10000 pass params['data'] = userData logging.info("params is %s", json.dumps(params)) return requests.post(constant.zdAPI, data=json.dumps(params))
def decorated_function(*args, **kwargs): jwt_token = request.headers.get('authorization', None) User().authenticate(jwt_token) return f(*args, **kwargs)
from loan.randomforest import RandomForestAlgorithm from loan.functions import modify_home_ownership, modify_purpose, modify_term, modify_time_of_employment user_manager = UserManager(app, db, User) db_manager = DBManager(app, db, User, UserEmailClass=None, UserInvitationClass=None, RoleClass=Role) db.create_all() if len(User.query.all()) < 1: user = User(username='******', email='*****@*****.**', password=user_manager.hash_password('asdfghjkl'), active=True) user.roles.append(Role(name='Admin')) db.session.add(user) db.session.commit() profile = Profile(firstname='Peter', middlename='Mike', lastname='Ahueze', gender='male', nationality='Nigerian', user_id=user.id) db.session.add(profile)