コード例 #1
0
ファイル: users_test.py プロジェクト: rolaya/gateway
    def test_terms(self):
        """ Tests acceptance of the terms """
        # adding test user to the DB
        user_to_add = User(username='******',
                           password=UserDTO._hash_password('test'),
                           accepted_terms=False)
        user_to_add.save()

        # setup test credentials
        user_dto = UserDTO(username='******')
        user_dto.set_password('test')

        # check if login is possible
        success, data = self.controller.login(user_dto)
        self.assertFalse(success)
        self.assertEqual(data, 'terms_not_accepted')

        # login with accepted terms fields set
        success, data = self.controller.login(user_dto, accept_terms=True)
        self.assertTrue(success)
        self.assertIsNotNone(data)

        # login again to see if fields has been saved
        success, data = self.controller.login(user_dto)
        self.assertTrue(success)
        self.assertIsNotNone(data)
コード例 #2
0
ファイル: users_test.py プロジェクト: rolaya/gateway
    def test_remove_user(self):
        """ Test removing a user. """
        # check that there is only one user in the system
        users_in_controller = self.controller.load_users()
        self.assertEqual(1, len(users_in_controller))
        self.assertEqual('om', users_in_controller[0].username)
        self.assertEqual(1, self.controller.get_number_of_users())

        # create a new user to test with
        user_to_add = User(username='******',
                           password=UserDTO._hash_password('test'),
                           accepted_terms=True)
        user_to_add.save()

        # creating equal credentials to use
        user_dto = UserDTO(username='******')
        user_dto.set_password('test')

        # verify that the user has been added
        users_in_controller = self.controller.load_users()
        self.assertEqual(2, len(users_in_controller))
        self.assertEqual('om', users_in_controller[0].username)
        self.assertEqual('test', users_in_controller[1].username)
        self.assertEqual(2, self.controller.get_number_of_users())

        # verify that the new user can log in to the system
        success, token = self.controller.login(user_dto, accept_terms=True)
        self.assertTrue(success)
        self.assertTrue(self.controller.check_token(token))

        # remove the newly created user
        self.controller.remove_user(user_dto)

        # Verify that the user is logged out of the system
        self.assertFalse(self.controller.check_token(token))

        # verify that the user is deleted from the system
        users_in_controller = self.controller.load_users()
        self.assertEqual(1, len(users_in_controller))
        self.assertEqual('om', users_in_controller[0].username)
        self.assertEqual(1, self.controller.get_number_of_users())

        # verify that the last user cannot be deleted.
        try:
            last_user_dto = UserDTO(username='******')
            self.controller.remove_user(last_user_dto)
            self.fail('Should have raised exception !')
        except Exception as exception:
            self.assertEqual(UserEnums.DeleteErrors.LAST_ACCOUNT,
                             str(exception))
コード例 #3
0
ファイル: user.py プロジェクト: krzysztofz1/gateway
    def dto_to_orm(user_dto):  # type: (UserDTO) -> User
        # Look if there is a user in the DB to take over the unchanged fields
        user = User.get_or_none(username=user_dto.username)
        # if the user is non existing, create a new user with the mandatory fields that can be further filled with the user_dto fields
        if user is None:
            mandatory_fields = {'username', 'password'}
            if not mandatory_fields.issubset(set(user_dto.loaded_fields)):
                raise ValueError('Cannot create user without mandatory fields `{0}`'.format('`, `'.join(mandatory_fields)))

            user = User(username=user_dto.username.lower(), password=user_dto.hashed_password)
        for field in ['accepted_terms']:
            if field in user_dto.loaded_fields:
                setattr(user, field, getattr(user_dto, field))

        return user
コード例 #4
0
ファイル: user_controller.py プロジェクト: rolaya/gateway
    def login(self, user_dto, accept_terms=False, timeout=None):
        # type: (UserDTO, Optional[bool], Optional[float]) -> Tuple[bool, str]
        """  Login a user given a UserDTO """

        if timeout is not None:
            try:
                timeout = int(timeout)
                timeout = min(60 * 60 * 24 * 30, max(60 * 60, timeout))
            except ValueError:
                timeout = None
        if timeout is None:
            timeout = self._token_timeout

        user_orm = User.select().where(
            User.username == user_dto.username.lower(),
            User.password == user_dto.hashed_password).first()

        if user_orm is None:
            return False, UserEnums.AuthenticationErrors.INVALID_CREDENTIALS

        if user_orm.accepted_terms == UserController.TERMS_VERSION:
            return True, self._gen_token(user_orm.username,
                                         time.time() + timeout)
        if accept_terms is True:
            user_orm.accepted_terms = UserController.TERMS_VERSION
            user_orm.save()
            return True, self._gen_token(user_orm.username,
                                         time.time() + timeout)
        return False, UserEnums.AuthenticationErrors.TERMS_NOT_ACCEPTED
コード例 #5
0
ファイル: user_controller.py プロジェクト: rolaya/gateway
    def remove_user(self, user_dto):
        # type: (UserDTO) -> None
        """  Remove a user. """
        # set username to lowercase to compare on username
        username = user_dto.username.lower()

        # check if the removed user is not the last admin user of the system
        if UserController.get_number_of_users() <= 1:
            raise Exception(UserEnums.DeleteErrors.LAST_ACCOUNT)
        User.delete().where(User.username == username).execute()

        to_remove = []
        for token in self._tokens:
            if self._tokens[token][0] == username:
                to_remove.append(token)

        for token in to_remove:
            del self._tokens[token]
コード例 #6
0
ファイル: user_controller.py プロジェクト: rolaya/gateway
 def load_users(self):
     # type: () -> List[UserDTO]
     """  Returns a list of UserDTOs with all the usernames """
     _ = self
     users = []
     for user_orm in User.select():
         user_dto = UserMapper.orm_to_dto(user_orm)
         user_dto.clear_password()
         users.append(user_dto)
     return users
コード例 #7
0
ファイル: users_test.py プロジェクト: rolaya/gateway
    def test_load_users(self):
        """ Test getting all usernames. """
        # get first list of users in the user controller
        users_in_controller = self.controller.load_users()
        self.assertEqual(1, len(users_in_controller))
        self.assertEqual('om', users_in_controller[0].username)

        user_to_add = User(username='******',
                           password=UserDTO._hash_password('test'),
                           accepted_terms=True)
        user_to_add.save()

        # check if the user has been added to the list
        users_in_controller = self.controller.load_users()
        self.assertEqual(2, len(users_in_controller))
        self.assertEqual('om', users_in_controller[0].username)
        self.assertEqual('test', users_in_controller[1].username)

        # check if the number of users is correct
        num_users = self.controller.get_number_of_users()
        self.assertEqual(2, num_users)
コード例 #8
0
ファイル: users.py プロジェクト: rolaya/gateway
 def _migrate(cls):
     # type: () -> None
     old_sqlite_db = constants.get_config_database_file()
     if os.path.exists(old_sqlite_db):
         import sqlite3
         connection = sqlite3.connect(old_sqlite_db,
                                      detect_types=sqlite3.PARSE_DECLTYPES,
                                      check_same_thread=False,
                                      isolation_level=None)
         cursor = connection.cursor()
         for row in cursor.execute(
                 'SELECT id, username, password, accepted_terms FROM users;'
         ):
             username = row[1]
             user = User.get_or_none(username=username)
             if user is None:
                 user = User(username=username,
                             password=row[2],
                             accepted_terms=row[3])
                 user.save()
         cursor.execute('DROP TABLE users;')
コード例 #9
0
 def save(self):
     user = User(
         username= self.validated_data['username'],
         fullname= self.validated_data['fullname'],
         email= self.validated_data['email'],
     )
     password = self.validated_data['password']
     password2 = self.validated_data['password2']
     if password != password2:
         raise serializers.ValidationError({'Password':'******'})
     user.set_password(password)
     user.save()
     return user
コード例 #10
0
ファイル: user_controller.py プロジェクト: rolaya/gateway
 def get_number_of_users():
     # type: () -> int
     """ Return the number of registred users """
     return User.select().count()