Beispiel #1
0
 def __init__(self, request):
     BaseController.__init__(self, request)
     self.role_repo = RoleRepo()
     self.user_role_repo = UserRoleRepo()
     self.user_repo = UserRepo()
     self.permission_repo = PermissionRepo()
     self.redis_set = RedisSet()
Beispiel #2
0
            def decorated(*args, **kwargs):

                user_role_repo = UserRoleRepo()
                permission_repo = PermissionRepo()

                user_id = Auth.user('sub')
                user_role = user_role_repo.find_first(**{'user_id': user_id})

                if not user_id:
                    return make_response(jsonify({'msg': 'Missing user ID in token'})), 400

                if not user_role:
                    return make_response(jsonify({'msg': 'Access Error - No Role Granted'})), 400

                user_perms = permission_repo.get_unpaginated(**{'role_id': user_role.role_id})

                perms = [perm.name for perm in user_perms]

                if len(perms) == 0:
                    return make_response(jsonify({'msg': 'Access Error - No Permission Granted'})), 400

                if permission not in perms:
                    return make_response(jsonify({'msg': 'Access Error - Permission Denied'})), 400

                return f(*args, **kwargs)
Beispiel #3
0
class TestUserRoleRepo(BaseTestCase):
    def setUp(self):
        self.BaseSetUp()
        self.repo = UserRoleRepo()

    def test_new_user_role_method_returns_new_user_role_object(self):
        user_role = UserRoleFactory.build()

        new_user_role = self.repo.new_user_role(user_role.role_id.id,
                                                user_role.user_id,
                                                user_role.location_id,
                                                user_role.email)

        self.assertIsInstance(new_user_role, UserRole)
        self.assertEqual(str(new_user_role.user_id), str(user_role.user_id))
        self.assertEqual(new_user_role.location_id, user_role.location_id)

    def test_exclude_works_user_role_instance(self):
        user_role = UserRoleFactory.build()

        new_user_role = self.repo.new_user_role(user_role.role_id.id,
                                                user_role.user_id,
                                                user_role.location_id,
                                                user_role.email)

        excluded_response = new_user_role.to_dict(exclude=["user_id"])

        self.assertFalse(excluded_response.get("user_id", False))
Beispiel #4
0
            def decorated(*args, **kwargs):

                user_role_repo = UserRoleRepo()

                role_repo = RoleRepo()

                user_id = Auth.user('id')
                user_role = user_role_repo.find_first(**{'user_id': user_id})

                if not user_id:
                    return make_response(
                        jsonify({'msg': 'Missing User ID in token'})), 401

                if not user_role:
                    return make_response(
                        jsonify({'msg':
                                 'Access Error - No Role Granted'})), 401

                if role_repo.get(user_role.role_id).name != role:
                    return make_response(
                        jsonify({
                            'msg':
                            'Access Error - This role does not have the access rights'
                        })), 401

                return f(*args, **kwargs)
Beispiel #5
0
class TestUserRoleRepo(BaseTestCase):
    def setUp(self):
        self.BaseSetUp()
        self.repo = UserRoleRepo()
        self.redis_set = RedisSet()

    def tearDown(self):
        self.BaseTearDown()

    def test_new_user_role_method_returns_new_user_role_object(self):
        role = RoleFactory.create()
        location = LocationFactory.create()
        user_role = UserRoleFactory.build(role_id=role.id, location=location)

        new_user_role = self.repo.new_user_role(user_role.role_id,
                                                user_role.user_id,
                                                user_role.location_id,
                                                user_role.email)

        self.assertIsInstance(new_user_role, UserRole)
        self.assertEqual(str(new_user_role.user_id), str(user_role.user_id))
        self.assertEqual(new_user_role.location.id, user_role.location.id)

    def test_exclude_works_user_role_instance(self):
        role = RoleFactory.create()
        location = LocationFactory.create()
        user_role = UserRoleFactory.build(role_id=role.id,
                                          location_id=location.id)

        new_user_role = self.repo.new_user_role(user_role.role_id,
                                                user_role.user_id,
                                                user_role.location_id,
                                                user_role.email)

        excluded_response = new_user_role.to_dict(exclude=["user_id"])

        self.assertFalse(excluded_response.get("user_id", False))

    def test_new_user_role_updates_cache(self):
        role = RoleFactory.create()
        location = LocationFactory.create()
        user_role = UserRoleFactory.build(role_id=role.id, location=location)

        self.repo.new_user_role(user_role.role_id, user_role.user_id,
                                user_role.location_id, user_role.email)

        results = self.redis_set.get(user_role.email[0:1])
        self.assertTrue(user_role.email in results)

        results = self.redis_set.get(user_role.email[0:3])
        self.assertTrue(user_role.email in results)

        results = self.redis_set.get(user_role.email[0:5])
        self.assertTrue(user_role.email in results)

        results = self.redis_set.get(user_role.email[0:len(user_role.email) -
                                                     1])
        self.assertTrue(user_role.email in results)
Beispiel #6
0
    def test_run_5_minute_method(self):
        role = RoleFactory.create()
        location = LocationFactory.create()
        user_role = UserRoleFactory.build(role_id=role.id, location=location)

        UserRoleRepo().new_user_role(user_role.role_id, user_role.user_id,
                                     user_role.location_id, user_role.email)

        Cron(self.app).run_5_minute()

        results = self.redis_set.get(user_role.email[0])
        self.assertEqual(user_role.email, results[0])

        results = self.redis_set.get(user_role.email[0:1])
        self.assertEqual(user_role.email, results[0])

        results = self.redis_set.get(user_role.email[0:2])
        self.assertEqual(user_role.email, results[0])
Beispiel #7
0
class TestUserRoleRepo(BaseTestCase):
    def setUp(self):
        self.BaseSetUp()
        self.repo = UserRoleRepo()
        self.redis_set = RedisSet()

    def tearDown(self):
        self.BaseTearDown()

    # def test_new_user_role_method_returns_new_user_role_object(self):
    #     role = RoleFactory.create()
    #     user = UserFactory.create()
    #     # user_role = UserRoleFactoryFake.build(user_id=user.id, role_id=role.id,)
    #     user_role = UserRoleFactory.build(role_id=role.id, user_id=user.id, )
    #
    #     # new_user_role = self.repo.new_user_role(
    #     #     user_id=user.id, role_id=user_role.role_id,
    #     # )
    #     new_user_role = self.repo.new_user_role(
    #         user_id=user_role.user_id, role_id=user_role.role_id,
    #     )
    #     print(new_user_role.__dict__)
    #     self.assertIsInstance(new_user_role, UserRole)
    #     self.assertEqual(str(new_user_role.user_id), str(user.id))

    def test_exclude_works_user_role_instance(self):
        role = RoleFactory.create()
        user = UserFactory.create()

        user_role = UserRoleFactory.build(
            role_id=role.id,
            user_id=user.id,
        )

        new_user_role = self.repo.new_user_role(
            user_id=user_role.user_id,
            role_id=user_role.role_id,
        )

        excluded_response = new_user_role.to_dict(exclude=["user_id"])

        self.assertFalse(excluded_response.get("user_id", False))
Beispiel #8
0
class RoleController(BaseController):
    def __init__(self, request):
        BaseController.__init__(self, request)
        self.role_repo = RoleRepo()
        self.user_role_repo = UserRoleRepo()
        self.user_repo = UserRepo()
        self.permission_repo = PermissionRepo()
        self.redis_set = RedisSet()

    """ ROLES """

    def list_roles(self):
        roles = self.role_repo.filter_by(is_deleted=False)

        role_list = [role.serialize() for role in roles.items]
        return self.handle_response("OK",
                                    payload={
                                        "roles": role_list,
                                        "meta": self.pagination_meta(roles)
                                    })

    def get_role(self, role_id):
        role = self.role_repo.get(role_id)
        if role:
            return self.handle_response("OK",
                                        payload={"role": role.serialize()})
        return self.handle_response("Invalid or Missing role_id",
                                    status_code=400)

    def create_role(self):
        name, help_ = self.request_params("name", "help")
        role1 = self.role_repo.find_first(name=name)

        if not role1:
            try:
                role = self.role_repo.new_role(name=name, help_=help_)
                return self.handle_response("OK",
                                            payload={"role": role.serialize()},
                                            status_code=201)
            except Exception as e:
                return self.handle_response("Error processing: " + str(e),
                                            status_code=400)

        return self.handle_response("Role with this name already exists",
                                    status_code=400)

    def update_role(self, role_id):
        name, help_ = self.request_params("name", "help")
        role = self.role_repo.get(role_id)
        if role:
            updates = {}
            if name:
                role1 = self.role_repo.find_first(name=name)
                if role1:
                    return self.handle_response(
                        "Role with this name already exists", status_code=400)
                updates["name"] = name
            if help_:
                updates["help"] = help_

            role = self.role_repo.update(role, **updates)
            return self.handle_response("OK",
                                        payload={"role": role.serialize()})
        return self.handle_response("Invalid or incorrect role_id provided",
                                    status_code=400)

    def delete_role(self, role_id):
        role = self.role_repo.get(role_id)
        if role:
            updates = {}
            updates["is_deleted"] = True
            self.role_repo.update(role, **updates)
            return self.handle_response("role deleted",
                                        payload={"status": "success"})
        return self.handle_response("Invalid or incorrect role_id provided",
                                    status_code=404)

    """ USER ROLES """

    def get_user_roles(self, user_id):
        user_roles = self.user_role_repo.get_unpaginated(user_id=user_id)
        if user_roles:
            role_list = [role.serialize() for role in user_roles]
            return self.handle_response("OK", payload={"user_role": role_list})
        return self.handle_response("There are no roles for this user",
                                    status_code=404)

    def create_user_role(self):
        try:
            role_id, user_id = self.request_params("role_id", "user_id")
            user = self.user_repo.find_first(id=user_id)
            if user is None:
                return self.handle_response("This user record does not exist",
                                            status_code=400)
            user_id = user.id
            user_role = self.user_role_repo.get_unpaginated(role_id=role_id,
                                                            user_id=user_id,
                                                            is_deleted=False)
            if not user_role:
                role = self.role_repo.get(role_id)
                if role:
                    user_role = self.user_role_repo.new_user_role(
                        role_id=role_id,
                        user_id=user_id,
                    )
                    user_role_data = user_role.serialize()
                    user_role_data.update(
                        {"name": f"{user.first_name} {user.last_name}"})
                    return self.handle_response(
                        "OK",
                        payload={"user_role": user_role_data},
                        status_code=201)
                return self.handle_response("This role does not exist",
                                            status_code=400)
            return self.handle_response("This User has this Role already",
                                        status_code=400)
        except Exception as e:
            return self.handle_response("Error Occurred: " + str(e),
                                        status_code=400)

    def delete_user_role(self, user_role_id):
        user_role = self.user_role_repo.get(user_role_id)
        if user_role:
            updates = {}
            updates["is_deleted"] = True
            self.user_role_repo.update(user_role, **updates)
            return self.handle_response("user_role deleted for user",
                                        payload={"status": "success"})
        return self.handle_response(
            "Invalid or incorrect user_role_id provided", status_code=404)

    def disable_user_role(self):
        user_id, role_id = self.request_params("userId", "roleId")
        user_role = self.user_role_repo.get_unpaginated(user_id=user_id,
                                                        role_id=role_id)[0]
        if user_role:
            updates = {}
            updates["is_active"] = False
            self.user_role_repo.update(user_role, **updates)
            return self.handle_response("user_role disabled for user",
                                        payload={"status": "success"})
        return self.handle_response(
            "Invalid or incorrect user_role_id provided", status_code=404)

    """ PERMISSIONS """

    def get_role_permissions(self, role_id):
        permissions = self.permission_repo.get_unpaginated(
            **{"role_id": role_id})
        perm_list = [permission.serialize() for permission in permissions]
        return self.handle_response("OK",
                                    payload={
                                        "role_id": role_id,
                                        "role_permissions": perm_list
                                    })

    def get_single_permission(self, role_id, permission_id):
        permission = self.permission_repo.filter_by(role_id=role_id,
                                                    id=permission_id)
        permissions = [
            permission.serialize() for permission in permission.items
        ]
        return self.handle_response("OK", payload={"permission": permissions})

    def get_all_permissions(self):
        permissions = self.permission_repo.get_unpaginated()
        perm_list = [permission.serialize() for permission in permissions]
        return self.handle_response("OK", payload={"permissions": perm_list})

    def create_role_permission(self):
        role_id, name, keyword = self.request_params("role_id", "name",
                                                     "keyword")
        permission = self.permission_repo.get_unpaginated(name=name,
                                                          is_deleted=False,
                                                          role_id=role_id)
        if not permission:
            role = self.role_repo.get(role_id)
            if role:
                permission = self.permission_repo.new_permission(
                    role_id=role_id, name=name, keyword=keyword)
                return self.handle_response(
                    "OK",
                    payload={"permission": permission.serialize()},
                    status_code=201,
                )
            return self.handle_response("This role does not exist",
                                        status_code=400)
        return self.handle_response("This permission already exists",
                                    status_code=400)

    def update_permission(self, permission_id):
        role_id, name, keyword = self.request_params("role_id", "name",
                                                     "keyword")
        permission = self.permission_repo.get(permission_id)
        if permission:
            updates = {}
            if name:
                permission1 = self.permission_repo.find_first(name=name)
                if permission1:
                    return self.handle_response(
                        "Permission with this name already exists",
                        status_code=400)
                updates["name"] = name
            if role_id:
                updates["role_id"] = role_id
            if keyword:
                updates["keyword"] = keyword

            self.role_repo.update(permission, **updates)
            return self.handle_response(
                "OK", payload={"permission": permission.serialize()})
        return self.handle_response(
            "Invalid or incorrect permission id provided", status_code=400)

    def delete_role_permission(self, permission_id):
        permission = self.permission_repo.get(permission_id)
        if permission:
            updates = {}
            updates["is_deleted"] = True
            self.role_repo.update(permission, **updates)
            return self.handle_response("permission deleted",
                                        payload={"status": "success"})
        return self.handle_response(
            "Invalid or incorrect permission id provided", status_code=404)

    def autocomplete(self):
        params = self.get_params("q")
        rows = []
        if params:
            for value in self.redis_set.get(params[0]):
                if value:
                    rows.append(value)
        return self.handle_response(rows, status_code=200)
Beispiel #9
0
	def add_user_roles_to_cache(self):
		'''A cron job that periodically updated the redis cache with the user emails for autocomplete '''
		with self.app.app_context():
			for user_role in UserRole.query.all():
				UserRoleRepo().update_cache(user_role)
Beispiel #10
0
 def setUp(self):
     self.BaseSetUp()
     self.repo = UserRoleRepo()
class RoleController(BaseController):
    def __init__(self, request):
        BaseController.__init__(self, request)
        self.role_repo = RoleRepo()
        self.user_role_repo = UserRoleRepo()
        self.permission_repo = PermissionRepo()
        self.andela_service = AndelaService()
        self.redis_set = RedisSet()

    ''' ROLES '''

    def list_roles(self):
        roles = self.role_repo.filter_by(is_deleted=False)
        role_list = [role.serialize() for role in roles.items]
        return self.handle_response('OK',
                                    payload={
                                        'roles': role_list,
                                        'meta': self.pagination_meta(roles)
                                    })

    def get_role(self, role_id):
        role = self.role_repo.get(role_id)
        if role:
            return self.handle_response('OK',
                                        payload={'role': role.serialize()})
        return self.handle_response('Invalid or Missing role_id',
                                    status_code=400)

    def create_role(self):
        name, help_ = self.request_params('name', 'help')
        role1 = self.role_repo.find_first(name=name)
        if not role1:
            role = self.role_repo.new_role(name=name, help_=help_)
            return self.handle_response('OK',
                                        payload={'role': role.serialize()},
                                        status_code=201)
        return self.handle_response('Role with this name already exists',
                                    status_code=400)

    def update_role(self, role_id):
        name, help_ = self.request_params('name', 'help')
        role = self.role_repo.get(role_id)
        if role:
            updates = {}
            if name:
                role1 = self.role_repo.find_first(name=name)
                if role1:
                    return self.handle_response(
                        'Role with this name already exists', status_code=400)
                updates['name'] = name
            if help_:
                updates['help'] = help_

            self.role_repo.update(role, **updates)
            return self.handle_response('OK',
                                        payload={'role': role.serialize()})
        return self.handle_response('Invalid or incorrect role_id provided',
                                    status_code=400)

    def delete_role(self, role_id):
        role = self.role_repo.get(role_id)
        if role:
            updates = {}
            updates['is_deleted'] = True
            self.role_repo.update(role, **updates)
            return self.handle_response('role deleted',
                                        payload={"status": "success"})
        return self.handle_response('Invalid or incorrect role_id provided',
                                    status_code=404)

    ''' USER ROLES '''

    def get_user_roles(self, user_id):
        user_roles = self.user_role_repo.get_unpaginated(user_id=user_id)
        if user_roles:
            role_list = [role.serialize() for role in user_roles]
            return self.handle_response('OK', payload={'user_role': role_list})
        return self.handle_response('There are no roles for this user',
                                    status_code=404)

    def create_user_role(self):
        location = Auth.get_location()
        role_id, email_address = self.request_params('roleId', 'emailAddress')
        user = self.andela_service.get_user_by_email_or_id(email_address)
        if user is None:
            return self.handle_response('This user record does not exist',
                                        status_code=400)
        user_id = user['id']
        user_role = self.user_role_repo.get_unpaginated(role_id=role_id,
                                                        user_id=user_id,
                                                        is_deleted=False)
        if not user_role:
            role = self.role_repo.get(role_id)
            if role:
                user_role = self.user_role_repo.new_user_role(
                    role_id=role_id,
                    user_id=user_id,
                    location_id=location,
                    email=email_address)
                user_role_data = user_role.serialize()
                user_role_data.update({'name': user.get('name')})
                return self.handle_response(
                    'OK',
                    payload={'user_role': user_role_data},
                    status_code=201)
            return self.handle_response('This role does not exist',
                                        status_code=400)
        return self.handle_response('This User has this Role already',
                                    status_code=400)

    def delete_user_role(self, user_role_id):
        user_role = self.user_role_repo.get(user_role_id)
        if user_role:
            updates = {}
            updates['is_deleted'] = True
            self.user_role_repo.update(user_role, **updates)
            return self.handle_response('user_role deleted for user',
                                        payload={"status": "success"})
        return self.handle_response(
            'Invalid or incorrect user_role_id provided', status_code=404)

    def disable_user_role(self):
        user_id, role_id = self.request_params('userId', 'roleId')
        user_role = self.user_role_repo.get_unpaginated(user_id=user_id,
                                                        role_id=role_id)[0]
        if user_role:
            updates = {}
            updates['is_active'] = False
            self.user_role_repo.update(user_role, **updates)
            return self.handle_response('user_role disabled for user',
                                        payload={"status": "success"})
        return self.handle_response(
            'Invalid or incorrect user_role_id provided', status_code=404)

    ''' PERMISSIONS '''

    def get_role_permissions(self, role_id):
        permissions = self.permission_repo.get_unpaginated(
            **{'role_id': role_id})
        perm_list = [permission.serialize() for permission in permissions]
        return self.handle_response('OK',
                                    payload={
                                        'role_id': role_id,
                                        'role_permissions': perm_list
                                    })

    def get_single_permission(self, role_id, permission_id):
        permission = self.permission_repo.filter_by(role_id=role_id,
                                                    id=permission_id)
        permissions = [
            permission.serialize() for permission in permission.items
        ]
        return self.handle_response('OK', payload={'permission': permissions})

    def get_all_permissions(self):
        permissions = self.permission_repo.get_unpaginated()
        perm_list = [permission.serialize() for permission in permissions]
        return self.handle_response('OK', payload={'permissions': perm_list})

    def create_role_permission(self):
        role_id, name, keyword = self.request_params('role_id', 'name',
                                                     'keyword')
        permission = self.permission_repo.get_unpaginated(name=name,
                                                          is_deleted=False,
                                                          role_id=role_id)
        if not permission:
            role = self.role_repo.get(role_id)
            if role:
                permission = self.permission_repo.new_permission(
                    role_id=role_id, name=name, keyword=keyword)
                return self.handle_response(
                    'OK',
                    payload={'permission': permission.serialize()},
                    status_code=201)
            return self.handle_response('This role does not exist',
                                        status_code=400)
        return self.handle_response('This permission already exists',
                                    status_code=400)

    def update_permission(self, permission_id):
        role_id, name, keyword = self.request_params('role_id', 'name',
                                                     'keyword')
        permission = self.permission_repo.get(permission_id)
        if permission:
            updates = {}
            if name:
                permission1 = self.permission_repo.find_first(name=name)
                if permission1:
                    return self.handle_response(
                        'Permission with this name already exists',
                        status_code=400)
                updates['name'] = name
            if role_id:
                updates['role_id'] = role_id
            if keyword:
                updates['keyword'] = keyword

            self.role_repo.update(permission, **updates)
            return self.handle_response(
                'OK', payload={'permission': permission.serialize()})
        return self.handle_response(
            'Invalid or incorrect permission id provided', status_code=400)

    def delete_role_permission(self, permission_id):
        permission = self.permission_repo.get(permission_id)
        if permission:
            updates = {}
            updates['is_deleted'] = True
            self.role_repo.update(permission, **updates)
            return self.handle_response('permission deleted',
                                        payload={"status": "success"})
        return self.handle_response(
            'Invalid or incorrect permission id provided', status_code=404)

    def autocomplete(self):
        params = self.get_params('q')
        rows = []
        if params:
            for value in self.redis_set.get(params[0]):
                if value:
                    rows.append(value)
        return self.handle_response(rows, status_code=200)
Beispiel #12
0
 def setUp(self):
     self.BaseSetUp()
     self.repo = UserRoleRepo()
     self.redis_set = RedisSet()
class PermissionController(BaseController):
    def __init__(self, request):
        BaseController.__init__(self, request)
        self.role_repo = RoleRepo()
        self.user_role_repo = UserRoleRepo()
        self.permission_repo = PermissionRepo()

    # Roles
    def list_roles(self):
        roles = self.role_repo.fetch_all()
        role_list = [role.serialize() for role in roles.items]
        return self.handle_response('OK', payload={'roles': role_list, 'meta': self.pagination_meta(roles)})

    def get_role(self, role_id):
        role = self.role_repo.get(role_id)
        if role:
            return self.handle_response('OK', payload={'role': role.serialize()})
        return self.handle_response('Invalid or Missing role_id')

    def create_role(self):
        name, help = self.request_params('name', 'help')
        # return self.handle_response('OK')
        role = self.role_repo.create_role(name=name, help=help)
        if role:
            return self.handle_response('OK', payload={'role': role.serialize()})
        return self.handle_response('Application Error')

    def update_role(self, role_id):
        pass

    def delete_role(self, delete_role):
        pass

    # USER ROLES
    def get_user_role(self, user_id):
        user_role = self.user_role_repo.filter_first(**{'user_id': user_id})
        if user_role:
            return self.handle_response('OK', payload={'user_role': user_role.serialize()})
        return self.handle_response('Invalid or Missing user_id')
        
    def create_user_role(self):
        role_id, user_id = self.request_params('roleId', 'userId')
        user_role = self.user_role_repo.create_user_role(role_id=role_id, user_id=user_id)
        if user_role:
            return self.handle_response('OK', payload={'user_role': user_role.serialize()})
        return self.handle_response('Application Error')

    def delete_user_role(self, user_id):
        pass

    # PERMISSIONS
    def get_role_permissions(self, role_id):
        permissions = self.permission_repo.filter_by(**{'role_id': role_id})
        perm_list = [permission.serialize() for permission in permissions.items]
        return self.handle_response('OK', payload={'role_id': role_id, 'role_permissions': perm_list, 'meta': self.pagination_meta(permissions)})

    def create_role_permission(self):
        role_id, name, keyword = self.request_params('role_id', 'name', 'keyword')
        permission = self.permission_repo.create_permission(role_id=role_id, name=name, keyword=keyword)
        if permission:
            return self.handle_response('OK', payload={'permission': permission.serialize()})
        return self.handle_response('Application Error')

    def delete_role_permission(self, permission_id):
        pass
Beispiel #14
0
 def _create(cls, model_class, *args, **kwargs):
     """Create an instance of the model, and save it to the database."""
     obj = super()._create(model_class, *args, **kwargs)
     UserRoleRepo().update_cache(obj)
     return obj
 def __init__(self, request):
     BaseController.__init__(self, request)
     self.role_repo = RoleRepo()
     self.user_role_repo = UserRoleRepo()
     self.permission_repo = PermissionRepo()
     self.andela_service = AndelaService()