ACL on certain records instead of API URLs

74 views Asked by At

I'm stuck with a scenario where a logged in user can create blog posts in a CMS like system. So he creates these posts in a backend system.

When that user is on the Blog page in the admin panel in then an API request like this is sent:

/api/blogs?filter={'userid': '100'}

This gets all the Blog posts made by this user. This user is only allowed to view and edit his own Blog posts.

But if he alters the URL to something like this:

/api/blogs?filter={'userid': '1'}

Then he can get the Blog posts of another users and I want to disallow that.

I know Loopback has ACL. But as far a I know that can only put a restriction on the entire GET, POST etc. requests. So with other words, a user can either call /api/blogs or he can't.

In this case I want the user to be able to call the API url. But I want to disallow certain records from being viewed.

How should I handle such a scenario in a dynamic way in Loopback?

1

There are 1 answers

0
blackkara On BEST ANSWER

If i understand you exactly, your issue could be resolved with 'remote methods' and 'remote hooks'.

module.exports = function (Blog){

    Blog.getBlogs = function(userid, cb){
        // Db operation.
        // Fetch blogs by userid.
        cb(null, blogs);
    };

    Blog.remoteMethod('getBlogs', {
        accepts: {arg: 'userid', type: 'number'},
        returns: {arg: 'blogs', type: 'object'}
    });

    Blog.beforeRemote('getBlogs', function(ctx, unused, next) {
        if(ctx.req.accessToken) {
            // Fetch user id by accesToken
            // Compare user id's
            next();
        } else {
            next(new Error('You are not allowed to get these messages'))
        }
    });
}

Since you defined remote hook, so its possible to check somethings before executing. You can get the user id related to the access token. And then compare fetched user id and incoming user id from parameter.

You can get more detail from loopback documentations

  1. Remote methods
  2. Remote hooks