示例#1
0
    def test_user_permission_add_proper(self, full_app, sqla_session):
        with session_context(sqla_session) as session:
            admin, token = create_admin(session)
            user = create_user({
                'user_name': 'aaaa',
                'email': 'foo'
            },
                               sqla_session=session)
            resource = create_entry({
                'resource_name': 'entry-x',
                'note': 'x'
            },
                                    sqla_session=session)

        node_id = resource.resource_id
        url_path = '/api/0.1/resources/{}/user_permissions'.format(node_id)
        headers = {str('x-testscaffold-auth-token'): str(token)}
        perm_name = 'edit'
        perm_dict = {'user_name': user.user_name, 'perm_name': perm_name}
        response = full_app.post_json(url_path,
                                      perm_dict,
                                      status=200,
                                      headers=headers)
        assert response.json['user_id'] == user.id
        assert response.json['perm_name'] == perm_name
        assert response.json['resource_id'] == node_id
        perm_inst = UserResourcePermissionService.get(user.id,
                                                      resource_id=node_id,
                                                      perm_name=perm_name,
                                                      db_session=sqla_session)
        assert isinstance(perm_inst, UserResourcePermission)
示例#2
0
def delete_user_resource_permission_response(user, resource, permission, db_session, similar=True):
    # type: (models.User, ServiceOrResourceType, PermissionSet, Session, bool) -> HTTPException
    """
    Get validated response on deleted user resource permission.

    :param user: user for which to delete the permission.
    :param resource: service or resource for which to delete the permission.
    :param permission: permission with modifiers to be deleted.
    :param db_session: database connection.
    :param similar:
        Allow matching provided permission against any similar database permission. Otherwise, must match exactly.
    :returns: valid HTTP response on successful operations.
    :raises HTTPException: error HTTP response of corresponding situation.
    """
    ru.check_valid_service_or_resource_permission(permission.name, resource, db_session)
    res_id = resource.resource_id
    if similar:
        found_perm = get_similar_user_resource_permission(user, resource, permission, db_session)
    else:
        found_perm = permission
    del_perm = UserResourcePermissionService.get(user.id, res_id, str(found_perm), db_session)
    permission.type = PermissionType.APPLIED
    err_content = {"resource_id": res_id, "user_id": user.id,
                   "permission_name": str(permission), "permission": permission.json()}
    ax.verify_param(del_perm, not_none=True, http_error=HTTPNotFound, content=err_content,
                    msg_on_fail=s.UserResourcePermissionName_DELETE_NotFoundResponseSchema.description)
    ax.evaluate_call(lambda: db_session.delete(del_perm), fallback=lambda: db_session.rollback(),
                     http_error=HTTPNotFound, content=err_content,
                     msg_on_fail=s.UserResourcePermissionName_DELETE_NotFoundResponseSchema.description)
    return ax.valid_http(http_success=HTTPOk, detail=s.UserResourcePermissionName_DELETE_OkResponseSchema.description)
示例#3
0
def user_resource_permission_create(request):
    """
    Set new permissions for user for a resource
    """
    resource = request.context.resource
    user_name = request.unsafe_json_body.get("user_name")
    user = UserService.by_user_name(user_name)
    if not user:
        user = UserService.by_email(user_name)
    if not user:
        return False

    for perm_name in request.unsafe_json_body.get("permissions", []):
        permission = UserResourcePermissionService.by_resource_user_and_perm(
            user.id, perm_name, resource.resource_id
        )
        if not permission:
            permission = UserResourcePermission(perm_name=perm_name, user_id=user.id)
            resource.user_permissions.append(permission)
    DBSession.flush()
    perms = [
        p.perm_name
        for p in ResourceService.perms_for_user(resource, user)
        if p.type == "user"
    ]
    result = {"user_name": user.user_name, "permissions": list(set(perms))}
    return result
示例#4
0
    def test_user_permission_remove_proper(self, full_app, sqla_session):
        perm_name = 'edit'
        with session_context(sqla_session) as session:
            admin, token = create_admin(session)
            user = create_user({
                'user_name': 'aaaa',
                'email': 'foo'
            },
                               sqla_session=session)
            resource = create_entry({
                'resource_name': 'entry-x',
                'note': 'x'
            },
                                    sqla_session=session)
            perm_inst = UserResourcePermission(user_id=user.id,
                                               perm_name=perm_name)
            resource.user_permissions.append(perm_inst)

        node_id = resource.resource_id
        qs = parse.urlencode({
            'user_name': user.user_name,
            'perm_name': perm_name
        })
        url_path = '/api/0.1/resources/{}/user_permissions?{}'.format(
            node_id, qs)
        headers = {str('x-testscaffold-auth-token'): str(token)}
        response = full_app.delete(url_path, status=200, headers=headers)
        perm_inst = UserResourcePermissionService.get(user.id,
                                                      resource_id=node_id,
                                                      perm_name=perm_name,
                                                      db_session=sqla_session)
        assert not isinstance(perm_inst, UserResourcePermission)
示例#5
0
 def user_permission_get(self, resource_id, user_id, perm_name):
     perm_inst = UserResourcePermissionService.get(
         resource_id=resource_id,
         user_id=user_id,
         perm_name=perm_name,
         db_session=self.request.dbsession)
     if not perm_inst:
         raise pyramid.httpexceptions.HTTPNotFound()
     return perm_inst
示例#6
0
def upgrade():
    context = get_context()
    session = Session(bind=op.get_bind())
    if not isinstance(context.connection.engine.dialect, PGDialect):
        return

    grp_res_perms = GroupResourcePermissionService.base_query(
        db_session=session)
    usr_res_perms = UserResourcePermissionService.base_query(
        db_session=session)

    for perm_list in [grp_res_perms, usr_res_perms]:
        perm_map = [(perm, PermissionSet(perm.perm_name))
                    for perm in perm_list]
        perm_rm = set()
        perm_keep = set()
        # find any user/group-resource that has both recursive and match permissions simultaneously
        # this is not allowed anymore, so remove the match access that is redundant anyway
        for perm_db, perm_set in perm_map:
            perm_dup = False
            for other_db, other_set in perm_map:
                if perm_set is other_set:
                    continue
                if perm_db.resource_id == other_db.resource_id and perm_set.like(
                        other_set):
                    if perm_set.scope == Scope.RECURSIVE:
                        perm_keep.add(perm_db)
                        perm_rm.add(other_db)
                    else:
                        perm_keep.add(other_db)
                        perm_rm.add(perm_db)
                    perm_dup = True
                    break
            if not perm_dup:
                perm_keep.add(perm_db)

        # apply changes
        for perm in perm_keep:
            perm_name_raw = perm.perm_name
            perm_scope = Scope.RECURSIVE
            if perm_name_raw.endswith("-" + Scope.MATCH.value):
                perm_name_raw = perm_name_raw.rsplit("-", 1)[0]
                perm_scope = Scope.MATCH
            perm.perm_name = str(PermissionSet(perm_name_raw,
                                               scope=perm_scope))
        for perm in perm_rm:
            session.delete(perm)

    session.commit()
示例#7
0
 def test_get_resource_permission(self, db_session):
     created_user = add_user(db_session)
     resource = add_resource(db_session, 1, 'test_resource')
     permission = UserResourcePermission(perm_name='test_perm',
                                         user_id=created_user.id,
                                         resource_id=resource.resource_id)
     resource.user_permissions.append(permission)
     db_session.flush()
     perm = UserResourcePermissionService.get(
         user_id=created_user.id,
         resource_id=resource.resource_id,
         perm_name='test_perm',
         db_session=db_session)
     assert perm.perm_name == 'test_perm'
     assert perm.resource_id == resource.resource_id
     assert perm.user_id == created_user.id
    def by_resource_user_and_perm(cls, user_id, perm_name, resource_id,
                                  db_session=None):
        """

        .. deprecated:: 0.8

        :param user_id:
        :param perm_name:
        :param resource_id:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        return UserResourcePermissionService.by_resource_user_and_perm(
            user_id=user_id, perm_name=perm_name, resource_id=resource_id,
            db_session=db_session)
 def test_get_resource_permission(self, db_session):
     created_user = add_user(db_session)
     resource = add_resource(db_session, 1, 'test_resource')
     permission = UserResourcePermission(
         perm_name='test_perm', user_id=created_user.id,
         resource_id=resource.resource_id)
     resource.user_permissions.append(permission)
     db_session.flush()
     perm = UserResourcePermissionService.get(
         user_id=created_user.id,
         resource_id=resource.resource_id,
         perm_name='test_perm',
         db_session=db_session
     )
     assert perm.perm_name == 'test_perm'
     assert perm.resource_id == resource.resource_id
     assert perm.user_id == created_user.id
def downgrade():
    """
    Any existing 'BROWSE' permission must be dropped.
    """
    context = get_context()
    session = Session(bind=op.get_bind())
    if not isinstance(context.connection.engine.dialect, PGDialect):
        return

    # two following lines avoids double "DELETE" erroneous call (ignore duplicate)
    # https://stackoverflow.com/questions/28824401
    context.connection.engine.dialect.supports_sane_rowcount = False
    context.connection.engine.dialect.supports_sane_multi_rowcount = False

    grp_perms = GroupResourcePermissionService.base_query(db_session=session)
    usr_perms = UserResourcePermissionService.base_query(db_session=session)
    for perm in grp_perms:
        if perm.perm_name == "browse":
            session.delete(perm)
    for perm in usr_perms:
        if perm.perm_name == "browse":
            session.delete(perm)
    session.commit()
示例#11
0
def user_resource_permission_delete(request):
    """
    Removes user permission from specific resource
    """
    resource = request.context.resource

    user = UserService.by_user_name(request.GET.get("user_name"))
    if not user:
        return False

    for perm_name in request.GET.getall("permissions"):
        permission = UserResourcePermissionService.by_resource_user_and_perm(
            user.id, perm_name, resource.resource_id
        )
        resource.user_permissions.remove(permission)
    DBSession.flush()
    perms = [
        p.perm_name
        for p in ResourceService.perms_for_user(resource, user)
        if p.type == "user"
    ]
    result = {"user_name": user.user_name, "permissions": list(set(perms))}
    return result
示例#12
0
def downgrade():
    context = get_context()
    session = Session(bind=op.get_bind())
    if not isinstance(context.connection.engine.dialect, PGDialect):
        return

    # two following lines avoids double "DELETE" erroneous call (ignore duplicate)
    # https://stackoverflow.com/questions/28824401
    context.connection.engine.dialect.supports_sane_rowcount = False
    context.connection.engine.dialect.supports_sane_multi_rowcount = False

    grp_res_perms = GroupResourcePermissionService.base_query(
        db_session=session)
    usr_res_perms = UserResourcePermissionService.base_query(
        db_session=session)

    for perm_list in [grp_res_perms, usr_res_perms]:
        for perm in perm_list:
            perm_set = PermissionSet(perm.perm_name)
            if perm_set.implicit_permission is None:
                session.delete(perm)
            else:
                perm.perm_name = perm_set.implicit_permission
    session.commit()