def test_valid_reset_pw_token(self): """Test a valid reset password token""" usr = User(password='******') db.session.add(usr) db.session.commit() token = usr.generate_reset_password_token() self.assertEqual(User.verify_reset_password_token(token), usr)
def test_valid_confirmation_token(self): """Test a valid email confirmation token""" usr = User(password='******') db.session.add(usr) db.session.commit() token = usr.generate_confirmation_token() self.assertTrue(usr.confirm(token))
def my_setup(obj): """Call this function from setUp as: def setUp(self): my_setup(self) """ # This seems a bug in Flask_REST_JSONAPI # # The Flask_REST_JSONAPI does not remove the Blue Blueprint objects # stored internally when the application objects they are applied to # is destroyed. # # I found this same issue is there for Flask Restful extension as # discovered and described in the book Mastering Flask: # https://books.google.com/books?id=NdZOCwAAQBAJ&pg=PA219&lpg=PA219&dq=flask:+how+to+destroy+application+object&source=bl&ots=nx7L_UG3EM&sig=yA-DG-ZYPtM5JxKJsFiXrhSkwzQ&hl=en&sa=X&ved=0ahUKEwies8G-x-7ZAhUh_IMKHdYKDCsQ6AEIdDAG#v=onepage&q=flask%3A%20how%20to%20destroy%20application%20object&f=false # # The result is that during a 2nd test, the view routes are created # twice and this error will be thrown: # builtins.AssertionError: View function mapping is overwriting an # existing endpoint function: api.api.user_list # # Workaround is to reset them manually rest_jsonapi.resources = [] obj.app = create_app(TestConfig) # initialize the test client obj.client = obj.app.test_client obj.app_context = obj.app.app_context() obj.app_context.push() db.create_all() Role.insert_roles() User.insert_default_users() Item.insert_default_items()
def test_invalid_reset_pw_token(self): """Test that a wrongly created reset password token fails""" usr = User(password='******') db.session.add(usr) db.session.commit() token = usr.generate_reset_password_token() self.assertIsNone(User.verify_reset_password_token(token + 'a'))
def test_invalid_invitation_token(self): """Test that a invitation token from another user fails""" user_email1 = '*****@*****.**' user_email2 = '*****@*****.**' token = User.generate_invitation_token(user_email1) self.assertNotEqual(User.email_from_invitation_token(token), user_email2)
def test_expired_confirmation_token(self): """Test that an expired email confirmation token fails""" usr = User(password='******') db.session.add(usr) db.session.commit() token = usr.generate_confirmation_token(1) time.sleep(2) self.assertFalse(usr.confirm(token))
def test_expired_reset_pw_token(self): """Test that an expired reset password token fails""" usr = User(password='******') db.session.add(usr) db.session.commit() token = usr.generate_reset_password_token(1) time.sleep(2) self.assertIsNone(User.verify_reset_password_token(token))
def test_valid_email_change_token(self): """Test a valid email change token""" usr = User(email='*****@*****.**', password='******') db.session.add(usr) db.session.commit() token = usr.generate_email_change_token('*****@*****.**') self.assertTrue(usr.change_email(token)) self.assertTrue(usr.email == '*****@*****.**')
def test_administrator_role(self): """Test CRUD permissions of administrator""" role = Role.query.filter_by(name='Administrator').first() usr = User(email='*****@*****.**', password='******') usr.role = role self.assertTrue(usr.can(Permission.CRUD_OWNED)) self.assertTrue(usr.can(Permission.CRUD_USERS)) self.assertTrue(usr.can(Permission.ADMIN))
def test_wrong_email_change_token(self): """Test that a email change token from another user fails""" usr1 = User(email='*****@*****.**', password='******') usr2 = User(email='*****@*****.**', password='******') db.session.add(usr1) db.session.add(usr2) db.session.commit() token = usr2.generate_email_change_token('*****@*****.**') self.assertFalse(usr2.change_email(token)) self.assertTrue(usr2.email == '*****@*****.**')
def init_user(self): # clean all existing user User.drop_collection() demo = User.create(name=u'demo', email=u'*****@*****.**', password=u'123456') admin = User.create(name=u'admin', email=u'*****@*****.**', password=u'123456') demo.save() admin.save()
def get_all_users(self): query = f'SELECT * FROM {User.table_name};' self._main_cursor.execute(query) return [ User.from_table_values(result) for result in self._main_cursor.fetchall() ]
def users(self): users = [] raw_users = self.db['users'].find() for raw_user in raw_users: user = User(raw_user['_id'], raw_user['role']) users.append(user) return users
def test_0_3_token_auth(self): """Test that a token is only provided after correct authentication""" # add a confirmed role = Role.query.filter_by(name='User').first() self.assertIsNotNone(role) usr = User(email='*****@*****.**', password='******', confirmed=True, role=role) db.session.add(usr) db.session.commit() # issue a request with a bad token url = '/api/v1/users/{}'.format(usr.id) headers = get_api_headers('bad-token', '') response = self.client().get(url, headers=headers) self.is_401_unauthorized(response) # get a token url = '/api/v1/token' headers = get_api_headers('*****@*****.**', 'cat') response = self.client().post(url, headers=headers) self.is_200_ok(response) json_response = json.loads(response.get_data(as_text=True)) self.assertIsNotNone(json_response.get('token')) token = json_response['token'] # issue a request with the token url = '/api/v1/users/{}'.format(usr.id) headers = get_api_headers(token, '') response = self.client().get(url, headers=headers) self.is_200_ok(response)
def login(): if request.method == "POST": email = request.form['email'] password = request.form['password'] # Verify Credentials q = "SELECT * FROM users WHERE email='{0}' AND password='******'".format( email, password) results = database.query(q) if results is not None and len(results) != 0: usr = User(results[0]['id'], results[0]['email'], results[0]['password']) login_user(usr) return redirect(url_for("user_dashboard", user=results[0]['id'])) else: return render_template("login.html", title="Login | GameChain", active="home", loginFailed=True) else: q = "SELECT * FROM users" results = database.query(q) invalidEmails = [] if results is not None: for user_info in results: invalidEmails.append(user_info['email']) return render_template("login.html", title="Login | GameChain", active="home", loginFailed=False, invalidEmails=invalidEmails)
def load_user(userid): q = "SELECT * FROM users WHERE id='{0}'".format(userid) results = database.query(q) if results is not None: return User(userid, results[0]['email'], results[0]['password']) else: return None
def get_user(self, github_id): github_id = int(github_id) if self.user_exists(github_id): raw_user = self.db['users'].find_one({'_id': github_id}) return User(raw_user['_id'], raw_user['role']) else: # TODO: Work out a more sensible return type/functionality. return None
def get_user_by_login(self, search_login): query = f'SELECT * FROM {User.table_name} ' \ f'WHERE "login" = {sql.Literal(search_login).as_string(self._main_cursor)};' self._main_cursor.execute(query) query_result = self._main_cursor.fetchone() if query_result is not None: return User.from_table_values(query_result) else: return None
def process_callback(): # Get information from authorisation request response. authorization_response_url = request.url authorization_response_code = request.args.get('code') # Construct token request. client_secret = os.environ.get('GITHUB_CLIENT_SECRET') token_request_base_url = "https://github.com/login/oauth/access_token" token_request_url, token_request_headers, token_request_body = client.prepare_token_request( token_request_base_url, authorization_response=authorization_response_url, code=authorization_response_code, client_secret=client_secret) # Get an access token. token_request_response = requests.post(token_request_url, headers=token_request_headers, data=token_request_body) client.parse_request_body_response(token_request_response.text) # Get user details. user_request_base_uri = "https://api.github.com/user" user_request_uri, user_request_headers, user_request_body = client.add_token( user_request_base_uri) user_info = requests.get(user_request_uri, headers=user_request_headers, data=user_request_body).json() # Create user object and log user in. user_id = user_info['id'] user = User(user_id, "reader") users = mongo_client.users # Assign the first user to be an admin. if len(users) == 0: user.role = "admin" mongo_client.add_user(user_id, user.role) login_user(user) # Return to the main page. return redirect('/')
def edit_user_role(self, github_id, new_role): github_id = int(github_id) user = User( github_id, new_role) # To check the validity of the role being assigned. if self.user_exists(github_id): self.db['users'].update_one( {'_id': github_id}, {'$set': { '_id': github_id, 'role': new_role }})
def login(): if request.method == 'GET': return render_template('login.html', title = u"Вход") username = request.form['username'] password = request.form['password'] db = get_db() cursor = db.cursor() count = cursor.execute("SELECT username, password FROM user WHERE username = %s AND password = %s", (username, password)) if not count: return registration_failed_redirection() registered_user = cursor.fetchone() login_user(User(registered_user[0], registered_user[1])) flash(u"Вход выполнен, %s"%current_user) return redirect(request.args.get('next') or url_for('index'))
def test_invalid_confirmation_token(self): """Test that a wrongly created email confirmation token fails""" usr1 = User(password='******') usr2 = User(password='******') db.session.add(usr1) db.session.add(usr2) db.session.commit() token = usr1.generate_confirmation_token() self.assertFalse(usr2.confirm(token))
def test_0_2_bad_auth(self): """Test that requests without wrong authentication return code 401""" # add a user role = Role.query.filter_by(name='User').first() self.assertIsNotNone(role) usr = User(email='*****@*****.**', password='******', confirmed=True, role=role) db.session.add(usr) db.session.commit() # authenticate with bad password url = '/api/v1/users/{}'.format(usr.id) headers = get_api_headers('*****@*****.**', 'dog') response = self.client().get(url, headers=headers) self.is_401_unauthorized(response)
def update_user(self, user: User): if user is None: raise ValueError("cannot update None user object") if self._connected_state: if user.id != -1: # object id remains the same self._query_update_one(user, {"id": user.id}) else: # execute insert query and update user id user.id = self._query_insert_one(user) self._main_connection.commit() return user return None
def test_invalid_email_change_token(self): """Test that an email change token for non-existing user fails""" usr1 = User(email='*****@*****.**', password='******') usr2 = User(email='*****@*****.**', password='******') db.session.add(usr1) db.session.add(usr2) db.session.commit() token = usr1.generate_email_change_token('*****@*****.**') self.assertFalse(usr2.change_email(token)) self.assertTrue(usr2.email == '*****@*****.**')
def login(): if current_user.is_authenticated: return redirect("/") if request.method == "GET": return render_template("login.html") else: if not ("username" in request.form) or not ("password" in request.form): return render_template("login.html") userid = request.form["username"] password = request.form["password"] if check_user(userid, password): login_user(User(userid), True) return redirect("/") else: return render_template("login.html")
def test_0_5_unconfirmed_account(self): """Test that a token is only provided for accounts with confirmed email. """ # add an unconfirmed user role = Role.query.filter_by(name='User').first() self.assertIsNotNone(role) usr = User(email='*****@*****.**', password='******', confirmed=False, role=role) db.session.add(usr) db.session.commit() # get user info with the unconfirmed account url = '/api/v1/users/{}'.format(usr.id) headers = get_api_headers('*****@*****.**', 'cat') response = self.client().get(url, headers=headers) self.is_403_forbidden(response) # get a token with the unconfirmed account url = '/api/v1/token' headers = get_api_headers('*****@*****.**', 'cat') response = self.client().post(url, headers=headers) self.is_403_forbidden(response)
def load_user(_id): return User.get(int(_id)) if (_id is not None) else None
def test_password_salts_are_random(self): """Test that password hashes are always different due to salting""" usr = User(password='******') usr2 = User(password='******') self.assertTrue(usr.password_hash != usr2.password_hash)
def test_password_verification(self): """Test verify_password method""" usr = User(password='******') self.assertTrue(usr.verify_password('cat')) self.assertFalse(usr.verify_password('dog'))
def test_no_password_getter(self): """Test that trying to retrieve the password raises error""" usr = User(password='******') with self.assertRaises(AttributeError): usr.password # pylint: disable=W0104