Esempio n. 1
0
def delete_user(
    username: EmailStr,
    db: Session = Depends(dependancies.get_db),
    user: user_schema.User = Depends(dependancies.get_current_user)
):
    """Deletes a user. Only accessible to Admin

    - **HEADERS**:
        ```
        {
            "Authorization": "Bearer <sample token>"
        }
        ```
    - **REQUEST**:
        ```
        {}
        ```
    - **RESPONSE**:
        ```
        {
            "detail": "Resource deleted"
        }
        ```
    """ 
    if not user.is_admin:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=constants.OPERATION_NOT_PERMITTED)
    UserHandler.delete_user(db, username=username)
    return {constants.DETAIL: constants.RESOURCE_DELETED}
Esempio n. 2
0
 def create_user():
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     return user
Esempio n. 3
0
 def test_user_change_info(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     u = UserHandler.update_user_info(user.uid, 'new name', 'new last name')
     self.assertEqual('new name', u.first_name)
     self.assertEqual('new last name', u.last_name)
Esempio n. 4
0
    def test_log_in_by_email(self):
        pss = 'Pa$$w0rd'
        user = User(password=pss,
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region check failed scenario
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email(user.email, user.password)
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email(user.email, 'wrong password')
        self.assertEqual('Entered password is wrong!', str(_ex.exception))
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email('*****@*****.**', pss)
        self.assertEqual('Wrong Email Address!', str(_ex.exception))
        # endregion

        # region check succeed scenario
        u = UserHandler.log_in_by_email(user.email, pss)
        # assert user properties with origin properties
        self.assertEqual(user.first_name, u.first_name)
        self.assertEqual(user.last_name, u.last_name)
        self.assertEqual(user.phone, u.phone)
        self.assertEqual(user.email, u.email)
        # check if password is null
        self.assertIsNone(u.password)
Esempio n. 5
0
 def test_generate_user_and_verify_its_email_by_url_token(self):
     # 2. (Email) generate a user -> get token -> send token for verification -> check if verified
     user_id = self.create_user().uid
     session = DBInitializer.get_session()
     email_token = session.query(Token).filter_by(
         exchange_method=ExchangeMethods.EMAIL.value).one()
     UserHandler.verify_user_exchange_method_by_url_token(
         email_token.url_token)
     user = UserHandler.get_user_by_id(user_id)
     self.assertEqual(user.is_email_verified, True)
     self.assertEqual(UserState.OBSCURE.value, user.state)
Esempio n. 6
0
    def test_generate_user_and_verify_its_phone_by_url_token(self):
        # 1. (Phone) generate a user -> get token -> send token for verification -> check if verified

        user_id = self.create_user().uid
        session = DBInitializer.get_session()
        phone_token = session.query(Token).filter_by(
            exchange_method=ExchangeMethods.PHONE.value).one()
        UserHandler.verify_user_exchange_method_by_url_token(
            phone_token.url_token)
        user = UserHandler.get_user_by_id(user_id)
        self.assertEqual(user.is_phone_verified, True)
        self.assertEqual(UserState.PARTIALLY.value, user.state)
Esempio n. 7
0
    def patch(self):
        """Logout user.
        """
        identity = get_jwt_identity()
        user_handler = UserHandler()
        user = user_handler.user_table.find_one({"id": identity["id"]})
        if not user:
            response = {"error": "User not found. Couldn't logout."}
            return make_response(jsonify(response), 404)

        jwt_token = request.environ.get("HTTP_AUTHORIZATION").split(" ")[-1]
        user_handler.blacklist_token({"id": identity["id"]}, jwt_token)
        response = {"message": "Logged out successfully."}
        return make_response(jsonify(response), 200)
Esempio n. 8
0
 def test_generate_user_and_verify_its_email_and_phone(self):
     user_id = self.create_user().uid
     session = DBInitializer.get_session()
     phone_token = session.query(Token).filter_by(
         exchange_method=ExchangeMethods.PHONE.value).one()
     email_token = session.query(Token).filter_by(
         exchange_method=ExchangeMethods.EMAIL.value).one()
     UserHandler.verify_user_phone_by_hex_token(user_id,
                                                phone_token.hex_token)
     UserHandler.verify_user_exchange_method_by_url_token(
         email_token.url_token)
     user = UserHandler.get_user_by_id(user_id)
     self.assertEqual(user.is_email_verified, True)
     self.assertEqual(user.is_phone_verified, True)
     self.assertEqual(UserState.ACTIVE.value, user.state)
Esempio n. 9
0
 def test_create_user_and_get_by_email(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     u = UserHandler.get_user_by_email('*****@*****.**')
     # assert user properties with origin properties
     self.assertEqual(user.first_name, u.first_name)
     self.assertEqual(user.last_name, u.last_name)
     self.assertEqual(user.phone, u.phone)
     self.assertEqual(user.email, u.email)
     # check if password is null
     self.assertIsNone(u.password)
Esempio n. 10
0
    def test_add_address_to_user_addresses(self):
        user = User(password='******',
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region Succeed Scenario
        address = Address(province='tehran',
                          city='tehran',
                          zip_code='1' * 10,
                          postal_address='somewhere in tehran')
        result = AddressHandler.add_address(user.uid, address)
        self.assertTrue(result)
        add = AddressHandler.get_address_by_id(address.uid)
        self.assertEqual(address.province, add.province)
        self.assertEqual(address.city, add.city)
        self.assertEqual(address.zip_code, add.zip_code)
        self.assertEqual(address.postal_address, add.postal_address)
        # endregion

        # region Failed Scenario
        new_address = Address(city='tehran',
                              zip_code='1' * 10,
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              zip_code='1' * 10,
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              city='tehran',
                              zip_code='0123456789')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              city='tehran',
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException) as _ex:
            AddressHandler.add_address(12345, new_address)
        self.assertEqual("there is no user with this id: 12345",
                         str(_ex.exception))
Esempio n. 11
0
 def test_db_check_if_different_session_affect_entities(self):
     session = DBInitializer.get_session()
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**',
                 birth=datetime(1988, 1, 1).date())
     uid = UserHandler.create_user(user)
     u = UserHandler.get_user_by_id(uid)
     u.first_name = 'New_Name'
     session.commit()
     n_u = UserHandler.get_user_by_id(uid)
     self.assertNotEqual(n_u.first_name, 'New_Name')
     uu = session.query(User).get(u.uid)
     self.assertIsNotNone(uu.password)
Esempio n. 12
0
def read_user(
    username: EmailStr, 
    db: Session = Depends(dependancies.get_db),
    user: user_schema.User = Depends(dependancies.get_current_user)
):
    """Get user. Only accessible to Admin

    - **HEADERS**:
        ```
        {
            "Authorization": "Bearer <sample token>"
        }
        ```
    - **REQUEST**:
        ```
        {}
        ```
    - **RESPONSE**:
        ```
        {
            "username": "******",
            "is_admin": false
        }
        ```
    """  
    if not user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail=constants.OPERATION_NOT_PERMITTED
        )
    db_user = UserHandler.get_user(db, username)
    if db_user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=constants.RESOURCE_NOT_FOUND)
    return db_user
Esempio n. 13
0
def get_users(
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(dependancies.get_db),
    user: user_schema.User = Depends(dependancies.get_current_user)
):
    """List all users. Only accessible to Admin

    - **HEADERS**:
        ```
        {
            "Authorization": "Bearer <sample token>"
        }
        ```
    - **REQUEST**:
        ```
        {}
        ```
    - **RESPONSE**:
        ```
        [
            {
                "username": "******",
                "is_admin": false
            }
        ]
        ```
    """    
    if not user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail=constants.OPERATION_NOT_PERMITTED
        )
    users = UserHandler.get_users(db, skip=skip, limit=limit)
    return users
Esempio n. 14
0
 def test_create_and_get_user(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**',
                 birth=datetime(1988, 1, 1).date())
     uid = UserHandler.create_user(user)
     u = UserHandler.get_user_by_id(uid)
     # assert user properties with origin properties
     self.assertEqual(user.first_name, u.first_name)
     self.assertEqual(user.last_name, u.last_name)
     self.assertEqual(user.phone, u.phone)
     self.assertEqual(user.email, u.email)
     self.assertEqual(user.birth, u.birth)
     # check if password is null
     self.assertIsNone(u.password)
Esempio n. 15
0
 def create_user(just_phone: bool = False):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     if just_phone:
         user.email = None
     user_id = UserHandler.create_user(user)
     return user_id
Esempio n. 16
0
    def post(self):
        """Registers a user.

        Returns:
            Details of user and access token.
        """
        data = json.loads(request.get_data())
        user_handler = UserHandler()
        user_id, additional_id = user_handler.create_user(data)

        identity = {"id": user_id, "additionalId": additional_id}
        response = {
            "data": {
                "token": create_access_token(payload=identity,
                                             expires_delta=False),
                "user_id": user_id,
            }
        }

        return make_response(jsonify(response), 201)
Esempio n. 17
0
 def generate_toke(self, no_exchange=False, user_id=None):
     if user_id is None:
         if no_exchange:
             user_id = UserHandler.create_user(
                 User(password='******',
                      first_name='first name',
                      last_name='last name'))
         else:
             user_id = self.create_user()
     result = TokenHandler.generate_token(user_id, ExchangeMethods.PHONE)
     return user_id, result
Esempio n. 18
0
 def inner(*args, **kwargs):
     identity = get_jwt_identity()
     user_handler = UserHandler()
     user = user_handler.user_table.find_one({"id": identity["id"]},
                                             {"_id": 0})
     if not user:
         response = {
             "error":
             "Authentication token incorrect. Try logging in again."
         }
         return make_response(jsonify(response), 403)
     return func(*args, **kwargs)
Esempio n. 19
0
    def get(self):
        """Fetch details of logged in user.

        Returns:
            A user object.
        """
        identity = get_jwt_identity()
        user_handler = UserHandler()
        user = user_handler.user_table.find_one({"id": identity["id"]},
                                                {"_id": 0})
        print(user)
        if not user:
            response = {
                "error":
                "User not found or authentication token has expired. Try login again."
            }
            return make_response(jsonify(response), 404)
        return make_response(jsonify({"data": user}), 200)
Esempio n. 20
0
def create_user(
    new_user: user_schema.UserCreate, 
    db: Session = Depends(dependancies.get_db),
    user: user_schema.User = Depends(dependancies.get_current_user)
):
    """Creates new user. Only accessible to Admin

    - **HEADERS**:
        ```
        {
            "Authorization": "Bearer <sample token>"
        }
        ```
    - **REQUEST**:
        ```
        {
            "username": "******",
            "password": "******",
            "is_admin": false
        }
        ```
    - **RESPONSE**:
        ```
        {
            "username": "******",
            "is_admin": false
        }
        ```
    """
    if not user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail=constants.OPERATION_NOT_PERMITTED
        )
    # new_user.password = auth_service.get_password_hash(new_user.password)
    user_in_db = user_schema.UserInDb(
        **new_user.dict(), 
        hashed_password=auth_service.get_password_hash(new_user.password)
    )
    return UserHandler.create_user(db, user=user_in_db)
Esempio n. 21
0
def get_current_user(db: Session = Depends(get_db),
                     token: str = Depends(oauth2_scheme)):
    """Extracts current user for token.
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail=constants.CREDENTIALS_NOT_VALID,
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt_service.decode_token(token)
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = token_schema.TokenData(username=username)
    except JWTError:
        raise credentials_exception
    user = UserHandler.get_user(db, username=token_data.username)
    if user is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail=constants.INCORRECT_CREDENTIALS)
    return user
Esempio n. 22
0
    def test_change_password(self):
        pss = 'Pa$$w0rd'
        user = User(password=pss,
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region check failed scenario
        with self.assertRaises(SecurityException) as _ex:
            UserHandler.change_password(0, pss, 'Pa$$w)rd1')
            self.assertEqual("user doesn't exist!", str(_ex.exception))
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.change_password(user.uid, 'another Pa$$w0rd',
                                        'Pa$$w)rd1')
        self.assertEqual('Entered password is wrong!', str(_ex.exception))
        with self.assertRaises(ValueException) as _ex:
            UserHandler.change_password(user.uid, pss, 'pass')
        self.assertEqual('Entered password is not valid!', str(_ex.exception))
        # endregion

        # region check succeed scenario
        new_pss = 'NEW pa$$w0rd'
        UserHandler.change_password(user.uid, pss, new_pss)
        u = UserHandler.log_in_by_email(user.email, new_pss)
        self.assertEqual(user.uid, u.uid)
Esempio n. 23
0
import falcon

from handlers import UserHandler, FindNeighborsHandler
from middlewares import MiddlewareSessionManager
from errors import ApplicationError, exception_handler
from utils.db import SessionManager
from utils.config import get_config

# middleware
api = falcon.API(middleware=[
    MiddlewareSessionManager(session_manager=SessionManager(
        config=get_config()['db']))
])

api.add_error_handler(ApplicationError, exception_handler)

# routes
api.add_route('/user', UserHandler())
api.add_route('/neighbors/{coords}', FindNeighborsHandler())
def get_user_builder(user_id):
    from handlers import UserHandler
    return UserHandler.get_user_by_id(user_id)
Esempio n. 25
0
    def test_retrieve_password_by_email_and_phone(self):
        user = User(password='******',
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)
        # ask for retrieve and
        # save retrieve auth code to db

        # get tokens from db
        session = DBInitializer.get_session()
        token = session.query(Token).filter_by(
            exchange_method=ExchangeMethods.PHONE.value).one()
        session.close()
        # fail scenario: if user does not exist
        with self.assertRaises(SecurityException) as ex:
            UserHandler.change_password_by_hex_token(0, token.hex_token,
                                                     "New Pa$$w0rd1")
        #       if url token is wrong
        with self.assertRaises(AuthenticationException) as ex:
            UserHandler.change_password_by_url_token("wrong url token",
                                                     "New Pa$$w0rd1")
        # change password
        new_password = "******"
        result = UserHandler.change_password_by_hex_token(
            user.uid, token.hex_token, new_password)
        self.assertTrue(result)
        # check if password is really change
        UserHandler.log_in_by_email(user.email, new_password)

        # change password through url token
        result = UserHandler.change_password_by_url_token(
            token.url_token, "New Pa$$w0rd1")
        self.assertTrue(result)
        # check if password is really change
        UserHandler.log_in_by_email(user.email, "New Pa$$w0rd1")