async def create_user(cls: Any, db: Any, user: User) -> Optional[str]: """Create user function. Args: db (Any): the db user (User): a user instanse to be created Returns: Optional[str]: The id of the created user. None otherwise. Raises: IllegalValueException: input object has illegal values """ # Validation: if user.id: raise IllegalValueException( "Cannot create user with input id-") from None if user.username == "admin": raise IllegalValueException( 'Cannot create user with username "admin".') from None # create id id = create_id() user.id = id # insert new user new_user = user.to_dict() result = await UsersAdapter.create_user(db, new_user) logging.debug(f"inserted user with id: {id}") if result: return id return None
def test_delete_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() response = self.client.delete('/api/users/' + str(user.id)) self.assertStatus(response, 204)
def test_delete_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() response = self.client.delete('/api/users/'+str(user.id)) self.assertStatus(response, 204)
def create_users_and_roles(): role_customer = Role(name="CUSTOMER").save() role_admin = Role(name="ADMIN").save() user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() user.roles.append(role_customer) user.save() admin = User(first_name='User', last_name='Theuser', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() admin.roles.append(role_admin) admin.save() second_user = User(first_name='My User', last_name='Van Gogh', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() second_user.roles.append(role_customer)
def test_get_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() response = self.client.get('/api/users/' + str(user.id)) self.assertStatus(response, 200) self.assertEqual(response.json['first_name'], 'First')
def test_get_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() response = self.client.get('/api/users/'+str(user.id)) self.assertStatus(response, 200) self.assertEqual(response.json['first_name'], 'First')
def test_put_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user.first_name = 'UpdateFirstName' response = self.client.put('/api/users/'+str(user.id), data=json.dumps(user.to_dict()), content_type='application/json') self.assertStatus(response, 200) self.assertEqual(response.json['first_name'], 'UpdateFirstName')
def init_database(): """setup and teardown db for testing""" DB.create_all() user1 = User('Bob Readerson', '*****@*****.**') user2 = User('Billy Bookhound', '*****@*****.**') DB.session.add(user1) DB.session.add(user2) DB.session.commit() yield DB DB.drop_all()
async def post(self) -> Response: """Post route function.""" db = self.request.app["db"] # Authenticate and authorize: token = await extract_token_from_request(self.request) await AuthorizationService.authorize(db, token, [Role.ADMIN, Role.USER_ADMIN]) # Process request: body = await self.request.json() logging.debug(f"Got create request for user {body} of type {type(body)}") try: user = User.from_dict(body) except KeyError as e: raise HTTPUnprocessableEntity( reason=f"Mandatory property {e.args[0]} is missing." ) from e try: id = await UsersService.create_user(db, user) except IllegalValueException as e: raise HTTPUnprocessableEntity() from e if id: logging.debug(f"inserted document with id {id}") headers = MultiDict([(hdrs.LOCATION, f"{BASE_URL}/users/{id}")]) return Response(status=201, headers=headers) raise HTTPBadRequest() from None
async def put(self) -> Response: """Put route function.""" db = self.request.app["db"] # Authenticate and authorize: token = await extract_token_from_request(self.request) await AuthorizationService.authorize(db, token, [Role.ADMIN, Role.USER_ADMIN]) # Process request: body = await self.request.json() try: user = User.from_dict(body) except KeyError as e: raise HTTPUnprocessableEntity( reason=f"Mandatory property {e.args[0]} is missing." ) from e id = self.request.match_info["id"] logging.debug(f"Got request-body {body} for {id} of type {type(body)}") try: await UsersService.update_user(db, id, user) except IllegalValueException as e: raise HTTPUnprocessableEntity() from e except UserNotFoundException as e: raise HTTPNotFound() from e return Response(status=204)
def user_registration(): """Handle the user registration.""" required_fields = ['username', 'email', 'password'] response = {} # Initialize a response dictionary user_data = request.get_json() if not check_required_fields(required_fields, user_data.keys()): response['message'] = "Required fields are missing" return jsonify(response), 400 # Create a user object username = user_data['username'] password = generate_password_hash(user_data['password']) email = user_data['email'] user = User(username=username, password=password, email=email) db.session.add(user) try: db.session.commit() except Exception: response['message'] = 'Unable to register the user' return jsonify(response), 400 response['message'] = "User registration successful" return jsonify(response), 200
async def get_user_by_id(cls: Any, db: Any, id: str) -> User: """Get user function.""" user = await UsersAdapter.get_user_by_id(db, id) # return the document if found: if user: return User.from_dict(user) raise UserNotFoundException(f"User with id {id} not found") from None
async def test_create_access_token() -> None: """Should return a token.""" user = User(username="******", role="test_role") token = await create_access_token(user) assert token assert len(token) > 0 secret = os.getenv("JWT_SECRET") jwt.decode(token, secret, algorithms="HS256") # type: ignore
async def get_all_users(cls: Any, db: Any) -> List[User]: """Get all users function.""" users: List[User] = [] _users = await UsersAdapter.get_all_users(db) for _user in _users: user = User.from_dict(_user) users.append(user) return users
def test_post_user_integrity_check(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user_ = {'first_name': 'First', 'last_name': 'Last', 'birth_date': datetime.date.today().isoformat(), 'email': '*****@*****.**', 'password': '******', 'phone': '4988888'} json_user = json.dumps(user_) response = self.client.post('/api/users', data=json_user, content_type='application/json') self.assert400(response)
def test_login_logout_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user_ = {'email': '*****@*****.**', 'password': '******'} json_user = json.dumps(user_) response = self.client.post('/api/users/login', data=json_user, content_type='application/json') self.assertStatus(response, 200) self.assertEqual(1, response.json['login_count']) response = self.client.post('/api/users/logout', data=json.dumps({'user_id': response.json['id']}), content_type='application/json') self.assertStatus(response, 200) self.assertEqual('OK', response.json['status'])
def create_users_and_roles(): role_customer = Role(name="CUSTOMER").save() role_admin = Role(name="ADMIN").save() user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() user.roles.append(role_customer); user.save() admin = User(first_name='User', last_name='Theuser', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() admin.roles.append(role_admin) admin.save() second_user = User(first_name='My User', last_name='Van Gogh', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888').save() second_user.roles.append(role_customer)
def test_post_user_integrity_check(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user_ = { 'first_name': 'First', 'last_name': 'Last', 'birth_date': datetime.date.today().isoformat(), 'email': '*****@*****.**', 'password': '******', 'phone': '4988888' } json_user = json.dumps(user_) response = self.client.post('/api/users', data=json_user, content_type='application/json') self.assert400(response)
async def authorize(cls: Any, db: Any, token: Optional[str], target_roles: List[str]) -> None: """Check token and check role against role in token. Args: db (Any): the db token (str): the jwt to be checked target_roles (List[str]): the roles to be checked against Raises: UserNotAuthorizedException: user's role does not match target role IncompleteTokenException: token lacks mandatory attributes InconsistentTokenException: role in token is different from users role InvalidInputException: required input parameter is missing """ # Validate input: if not token: raise InvalidInputException("Token is required input.") from None if not target_roles: raise InvalidInputException("Roles is required input.") from None # Decode token: decoded_token = await decode_token(token) try: username = decoded_token["username"] token_role = decoded_token["role"] except KeyError as e: raise IncompleteTokenException( f"Mandatory property in token {e.args[0]} is missing.") from e # Check username: # admin user is good if username == "admin": pass else: # Check if user given by username exists in our records: logging.debug(f"Trying to verify user with username: {username}") _user = await UsersAdapter.get_user_by_username(db, username) user = User.from_dict(_user) # Verify that user has role given in token: if user.role != token_role: raise InconsistentTokenException( f"Inconsistent roles: user.role is {user.role} vs token_role {token_role}" ) from None # We authorize if username is "admin" or if the user has sufficient role: if token_role in target_roles: pass else: raise UserNotAuthorizedException( f"User {username} does not have sufficient role.") from None
def test_login_logout_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user_ = {'email': '*****@*****.**', 'password': '******'} json_user = json.dumps(user_) response = self.client.post('/api/users/login', data=json_user, content_type='application/json') self.assertStatus(response, 200) self.assertEqual(1, response.json['login_count']) response = self.client.post('/api/users/logout', data=json.dumps( {'user_id': response.json['id']}), content_type='application/json') self.assertStatus(response, 200) self.assertEqual('OK', response.json['status'])
async def login(cls: Any, db: Any, username: str, password: str) -> str: """Check username and passord. Args: db (Any): the db username (str): the username of the user trying to log in password (str): the users password Returns: str: A jwt token. Raises: UnknownUserException: If the user is unknown to us WrongPasswordException: If the password does not match our records """ # First we see if it is the admin trying to log in. # Then we need to check if we have the user in our db, user = None if username == ADMIN_USERNAME and password == ADMIN_PASSWORD: user = User(username=ADMIN_USERNAME, password=ADMIN_PASSWORD, role=Role.ADMIN) else: _user = await UsersAdapter.get_user_by_username(db, username) if _user: user = User.from_dict(_user) # Evaluate what we have in the user-object: if not user: raise UnknownUserException( f"Username {username} not found.") from None if password != user.password: raise WrongPasswordException( f"Password for {username} did not match.") from None jwt_token = await create_access_token(user) return jwt_token
async def update_user(cls: Any, db: Any, id: str, user: User) -> Optional[str]: """Get user function.""" # Validation: if user.username == "admin": raise IllegalValueException( 'Cannot change username to "admin".') from None # get old document old_user = await UsersAdapter.get_user_by_id(db, id) # update the user if found: if old_user: if user.id != old_user["id"]: raise IllegalValueException( "Cannot change id for user.") from None new_user = user.to_dict() result = await UsersAdapter.update_user(db, id, new_user) return result raise UserNotFoundException(f"User with id {id} not found.") from None
def test_put_user(self): user = User(first_name='First', last_name='Last', birth_date=datetime.date.today(), email='*****@*****.**', password='******', phone='4988888') user.save() user.first_name = 'UpdateFirstName' response = self.client.put('/api/users/' + str(user.id), data=json.dumps(user.to_dict()), content_type='application/json') self.assertStatus(response, 200) self.assertEqual(response.json['first_name'], 'UpdateFirstName')
async def mock_test_user(db: Any, username: str) -> User: """Create a mock user object.""" return User( # noqa: S106 id=ID, username="******", password="******", role="user-admin" )
def new_user(): """fixture to test user class""" user = User('Ralph Realname', '*****@*****.**') return user