def add_role_to_user(self, user, role): if not self.user_exists(user) or not self.role_exists(role): raise StorageException('User or role does not exist') roles = [role.name for role in self.get_user(user).roles] if role in roles: raise StorageException('User already has role') roles.append(role) self._user.update_one({'name': user}, {'$set': {'roles': roles}})
def remove_role_from_user(self, user, role): if not self.user_exists(user) or not self.role_exists(role): raise StorageException('User or role does not exist') roles = [role.name for role in self.get_user(user).roles] if role not in roles: raise StorageException('User doesn\'t have role') roles.remove(role) self._user.update_one({'name': user}, {'$set': {'roles': roles}})
def change_password(self, user_name, password): if not self.user_exists(user_name): raise StorageException('User does not exist') if not password_is_legal(password): raise StorageException( 'Illegal password. Ask admin for password rules.') self._user.update_one({'name': user_name}, {'$set': { 'password': hash_password(password) }})
def create_role(self, name, **kwargs): if kwargs: raise NotImplementedError( 'Other parameters than name, including {} not supported'. format(kwargs)) if self.role_exists(name): raise StorageException('Role already exists') self._role.insert_one({'name': name})
def create_user(self, name: str, password: str, roles: List[str] = None, is_hashed: bool = False): if self.user_exists(name): raise StorageException('User already exists') if not is_hashed and not password_is_legal(password): raise StorageException( 'Illegal password. Ask admin for password rules.') if roles and not all(self.role_exists(role) for role in roles): raise StorageException('Not all roles in {} exist'.format(roles)) self._user.insert_one({ 'name': name, 'password': password if is_hashed else hash_password(password), 'roles': roles if roles else [] })
def get_user(self, identifier: str, throw: bool = False) -> Union[SecurityUser, None]: if not self.user_exists(identifier): if throw: raise StorageException('User does not exist') else: return None user = self._user.find_one({'name': identifier}) return SecurityUser(name=user['name'], password=user['password'], roles=user['roles'])
def delete_user(self, user: str): if not self.user_exists(user): raise StorageException('User does not exist') self._user.delete_one({'name': user})