def insert_user(self, user: User): """ Insert a User object into the DB if it doesn't exist, skip otherwise :param user: User object to insert :return: True if user was inserted, False otherwise """ logging.info("inserting user: %s", user) id = user.get_property("id") created = user.get_property("created") karma = user.get_property("karma") about = user.get_property("about") about = about.replace("\x00", "") if about is not None else about submitted = user.get_property("submitted") query = """ INSERT INTO {} (id, created, karma, about, submitted) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (id) DO NOTHING; """ query_sql = sql.SQL(query).format(sql.Identifier(self.table_name)) # if not is_value_exists( # self.conn_obj, self.table_name, self.primary_key_name, id # ): self.cursor.execute(query_sql, (id, created, karma, about, submitted))
def registration(username, password, name, surname): hashed_password = hashlib.sha512(password.encode('utf-8')).hexdigest() u = User(username, hashed_password, name, surname) db_session.add(u) db_session.commit() return u
def test_create_user_valid_data(self, mock_user_repo): mock_user_repo.create.return_value = Mock() create_user_uc = CreateUserUseCase(repository=mock_user_repo) create_user_uc.execute(user_name="badra", password="******") encrypted_password = User(user_name="badra", password="******").get_encrypted_password() mock_user_repo.create.assert_called_once_with( user_name="badra", password=encrypted_password )
def login(): posted_user = UserShcema().load(request.get_json()) current_user = User.find_by_username(posted_user.data['username']) if not current_user: return jsonify({'message': 'User {} doesn\'t exist'.format(posted_user.data['username'])}), 400 if current_user.check_password(posted_user.data['password']): access_token = create_access_token(identity=posted_user.data['username']) refresh_token = create_refresh_token(identity=posted_user.data['username']) user = UserShcema(only=('username', 'password')).dump(current_user) return jsonify(user=user.data, access_token=access_token, refresh_token=refresh_token), 200 else: return jsonify({'message': 'Wrong credentials'}), 401
def test_login_user_with_invalid_credentials(self, mock_user_repo): mock_user_repo.validate_user.return_value = False login_uc = LoginUserUseCase(repository=mock_user_repo) is_valid_user = login_uc.execute(user_name='badra', password="******") self.assertFalse(is_valid_user) encrypted_password = User( user_name="badra", password="******").get_encrypted_password() mock_user_repo.validate_user.assert_called_once_with( user_name='badra', password=encrypted_password)
def add_user(): posted_user = UserSchema(only=("name", "email", "telegram", "pw")).load(request.get_json()) user = User(**posted_user) session = Session() try: session.add(user) session.commit() except Exception: session.close() return 'User with that name already exists', 500 new_user = UserSchema().dump(user) session.close() return jsonify(new_user), 200
class TestUser(): @classmethod def setup_class(self): self.user = User(name='name', email='*****@*****.**') def test_constructor(self): assert self.user.name == 'name' assert self.user.email == '*****@*****.**' def test_from_dict(self): source = {'name': 'name', 'email': '*****@*****.**'} user = User.from_dict(source) assert user.name == 'name' assert user.email == '*****@*****.**' def test_to_dict(self): dest = self.user.to_dict() expect = {'name': 'name', 'email': '*****@*****.**'} assert dest == expect
def registration(): if not request.get_json(): return jsonify({'message': 'Empty request'}), 400 posted_user = UserShcema().load(request.get_json()) try: user = User(**posted_user.data) db.session.add(user) db.session.commit() new_user = UserShcema().dump(user).data access_token = create_access_token(identity=new_user['username']) refresh_token = create_refresh_token(identity=new_user['username']) return jsonify(new_user, access_token, refresh_token), 201 except IntegrityError: db.session.rollback() return jsonify({'message': 'This member is already exists'}), 422 except TypeError as e: return jsonify({'message': 'Something went wrong: {}'.format(e)}), 400
def get_user(self, user_id: str) -> Optional[User]: """ Get a User object with a given ID from the DB :param user_id: ID of the user to get :return: User object if exists, None otherwise """ logging.info("getting user with id: %s", user_id) if self._is_user_exists(user_id): query = "SELECT * FROM {table} WHERE {column} = %s;" query_sql = sql.SQL(query).format( table=sql.Identifier(self.table_name), column=sql.Identifier(self.col_name_id), ) self.cursor.execute(query_sql, user_id) user = User().from_db_call(self.cursor.fetchall()) return user logging.info("user with id: %s does not exist", user_id) return None
def get_user(self, user_id: str) -> Optional[User]: """ Get a user with a given ID :param user_id: ID of the user to get :return: an object of class User (or None if an item does not exist) """ url = self.create_url(user_id=user_id) logging.info("making GET request: %s", url) res = get(url=url) if res.status_code != 200: logging.warning( "GET request failed: %s, user_id: %s", res.status_code, user_id ) # raise Exception( # "API response: {}. User id: {}".format(res.status_code, user) # ) return None logging.info("GET request succeeded for user_id: %s", user_id) user = User().from_api_call(res.json()) return user
def test_validate_user_name_with_invalid_data(self): user = User(user_name="testuser###", password="******") self.assertRaises(ValueError, user.validate_user_name)
def get_user(user_name: str) -> Optional[User]: # TODO: load user from database return User("dummy", "dummy", "dummy")
def setup_class(self): self.user = User(name='name', email='*****@*****.**')
def test_from_dict(self): source = {'name': 'name', 'email': '*****@*****.**'} user = User.from_dict(source) assert user.name == 'name' assert user.email == '*****@*****.**'
def test_validate_password_policy_with_valid_password(self): user = User(user_name="badra123", password="******") self.assertTrue(user.validate_password_policy())
def test_validate_user_name_with_valid_data(self): user = User(user_name="testuser", password="******") self.assertTrue(user.validate_user_name())
def test_validate_password_policy_with_invalid_password(self): user = User(user_name="badra123", password="******") self.assertFalse(user.validate_password_policy())
from src.repositories.entity import Session from src.entities.user import User from src.entities.role import Role from src.repositories.role_repository import fetch_role from datetime import datetime from src.repositories.entity import init_db init_db() session = Session() try: role = session.query(Role).filter(Role.name == 'Admin').first() if not role: role = Role('Admin', 'This is the admin role') session.add(role) session.commit() user = session.query(User).filter( User.email == '*****@*****.**').first() if not user: role = fetch_role(session, 'Admin') cDate = datetime.now() user = User('test', '*****@*****.**', '123456', cDate, role) session.add(user) session.commit() session.close() except Exception as e: print(str(e))
def test_password_encryption(self): user = User(user_name="testuser", password="******") # password is encrypted assert user.get_encrypted_password() != 'Cleanapp@123'