Sails: How to handle a route with a dot in route param

Created on 25 Feb 2020  路  10Comments  路  Source: balderdashy/sails

Node version: 10.19.0
Sails version _(sails)_: 1.2.3


Hi,

I have a controller which serves an image. I am trying to get this route to work

/content/26/image.png

It responses 404 but work with

/content/26/image.png/

I got it to work with a custom inline route ( fn: async function (req, res)) but I want access control for this route.

Many thanks in advance and kindest regards

does this answer your question? help wanted

Most helpful comment

Thanks for the detailed explanation @georgeben!

All 10 comments

@dailez Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. _(Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)_
  • tell us why this issue is important to you and your team. What are you trying to accomplish? _(Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)_
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. _(Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)_
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. _(Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)_
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. _(Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)_

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

Hey @dailez , You could put the image in the assets folder. Sails automatically generates an asset route for the image. Read more about it here

Thanks for your message but I need to add a parameter to the route. I can't use the route as it is.

Please can you share a screenshot of your route address inconfig/route.js

@dailez You probably want to use the skipAssets options in your routes file (I think set to false)..

Please find below an extract of the route.js:

'GET /temp-files/:fileName': {
    skipAssets: false,
    fn: async function (req, res) {
      console.log(req.user); // undefined
      //...
    }
  },

I'm currently implementing the functionality inline. The problem is that req.user is undefined but I need this information because the route is not /temp-files/:fileName but /temp-files/userId/:fileName. I can not add the userId to the route, I want to use it from the logged-in user. I tried to do it with a dedicated file (also actions2) but it always fails with not authorized.

As I said above, not inline gives an error:

'GET /temp-files/:fileName': {action: 'download-temp-file', skipAssets: false},

http://localhost:1337/temp-files/image.jpg response with 401 (Unauthorized)

Okay, from what I understand, GET /temp-files/:fileName can only be accessed by an authorized user right?

  • You can set up your route like this:
    GET /api/v1/temp-files/:filename': { action: 'download-temp-file', skipAssets: false }
  • Create the download-temp-file action by running sails generate action download-temp-file on your terminal
  • To get the filename passed in the request url, your action can look like this:
friendlyName: 'Download temp file',


  description: '',


  inputs: {
    filename: {
      required: true,
      type: 'string'
    }
  },


  exits: {

  },


  fn: async function (inputs) {
    // You can access the filename in your action with inputs.filename
    // All done.
    return {
    }

  }
  • To prevent unauthorized users from accessing GET /api/v1/temp-files/:filename, you need to create a policy
    Here is a snippet of a policy that checks for an authorization token in the request header to determine if the user making the request is authorized: It is located in api/policies/isLoggedIn.js
module.exports = async function (req, res, proceed) {
  const authorizationHeader = req.headers.authorization;
  if (!authorizationHeader) {
    return res.unauthorized();
  }
  try {
    const requestToken = authorizationHeader.split('Bearer').pop().trim();
    const payload = await sails.helpers.decodeAuthToken(requestToken); //Extracting the data from the token
     // Get the user
    const user = await Users.findOne({
      id: payload.id,
      deactivated: false,
    });
    if (!user) {
      return res.unauthorized();
    }
    // Add the user to the request object/dictionary
    req.user = user;
    return proceed();
  } catch (error) {
    sails.log.error(error);
    switch (error.name) {
      case 'JsonWebTokenError':
        return res.unauthorized();
      case 'TokenExpiredError':
        return res.unauthorized();
      default:
        return res.serverError();
    }
  }
};

Then you need to modify your config/policies.js file to add the isLoggedIn policy to the download-temp-file action.
You can do it like so:

module.exports.policies = {
    'download-temp-file': 'isLoggedIn'
}
  • Now you can access the user information in your download-temp-file action using this.req.user

Hope this helps.

Thanks a lot

Thanks for the detailed explanation @georgeben!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

victory-deployment picture victory-deployment  路  4Comments

danil-z picture danil-z  路  3Comments

pawankorotane picture pawankorotane  路  3Comments

thomasfr picture thomasfr  路  3Comments

3imed-jaberi picture 3imed-jaberi  路  3Comments