Izack
Izack

Reputation: 843

Iron Route - Server Side, access this.params from onBeforeAction()

I need to serve some REST API Endpoints from my meteor application.
Endpoints must be accessible on the server side, so I'm using Iron router for server side routing.
All works great, but now I need access to the this.params for permission checking.

My current route:

Router.route('myServerRoute', {
    where: "server",
    path: '/api/v1/doit/:partner',
    onBeforeAction: function(req, res, next) {
        API.beforeAction(req, res, next, ['admin','API']);
    }
})

The API.beforeAction is a function I'm using to validate the user token (This token is in one of the headers)
This function check if the token is valid and if that user have one of the roles from the 4th parameter.

The :partner is the name of the partner that use the API.

Let say that :partner is 'store1' (/api/v1/doit/store1)
I want to verify that only users that have the store1 role will be able to access the /api/v1/doit/store1 URL
So I want to pass the value of the :partner parameter to the API.beforeAction function

On the onBeforeAction function, I don't have access to the this.params (it is empty)
Some suggested to access the params using Router.current()
But this is a client call, and it is not available server side.

I can use req.url, parse it and get the partner name. but I don't like to do the parsing myself when I know that Iron Route already parsed this URL

Any suggestions how to get the URL parameters inside the onBeforeAction?

Upvotes: 0

Views: 217

Answers (1)

fnkrm
fnkrm

Reputation: 498

You don't need to do permission checking in your onBeforeAction. I implemented my API with Iron Router. In the example bellow I handle a get request with an API key and return informations or error code.

Router.route('/api/thing/:apikey', { where: 'server' })
.get(function getThing () {
    if (typeof this.params.apikey === 'undefined' || this.params.apikey.length != 16 || !Userprofile.findOne({ apiKey: this.params.apikey })) {
        this.response.statusCode = 403;
        return this.response.end('Not authorized');
    }
    const things = Thing.find({ owner: Userprofile.findOne({ apiKey: this.params.apikey }).owner }).fetch();
    if (things.length > 0) {
        this.response.statusCode = 200;
        return this.response.end(JSON.stringify(things));
    } else {
        this.response.statusCode = 200;
        return this.response.end('No things found');
    }
});

Upvotes: 1

Related Questions