1

I'm new in backend development with Sails, I'd like to know how I can prevent users to list ressources they do not own, here are my models :

models/User.js :

var bcrypt = require('bcryptjs')

module.exports = {
  attributes: {
    //  ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦  ╦╔═╗╔═╗
    //  ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
    //  ╩  ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
    password: {type: 'string', required: true},
    email: {type: 'string', required: true, unique: true},
    firstName: {type: 'string', allowNull: true},
    lastName: {type: 'string', allowNull: true},
    phoneNumber: {type: 'string', allowNull: true},

    //  ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
    //  ║╣ ║║║╠╩╗║╣  ║║╚═╗
    //  ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝

    //  ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
    //  ╠═╣╚═╗╚═╗║ ║║  ║╠═╣ ║ ║║ ║║║║╚═╗
    //  ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
    bankAccounts: {collection: 'bankAccount', via: 'user'},
  },

  customToJSON: function() {
    return _.omit(this, ['password', 'updatedAt'])
  },
  beforeCreate: function(values, cb) {
    bcrypt.hash(values.password, 10, (err, hash) => {
      if (err) return cb(err)
      values.password = hash
      cb()
    })
  },
}

models/BankAccount.js :

module.exports = {
  attributes: {
    //  ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦  ╦╔═╗╔═╗
    //  ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
    //  ╩  ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
    user: {model: 'user'},
    name: {type: 'string', required: true},
    iban: {type: 'string', required: true, unique: true, maxLength: 34},
    bic: {type: 'string', required: true, maxLength: 11},
    //  ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
    //  ║╣ ║║║╠╩╗║╣  ║║╚═╗
    //  ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝

    //  ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
    //  ╠═╣╚═╗╚═╗║ ║║  ║╠═╣ ║ ║║ ║║║║╚═╗
    //  ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
  },
}

What I would like is to prevent a user from seeing all the accounts when he does a GET /user/ and prevent him to list other bank accounts than his when he does a GET /bank_account/ or to access GET /bank_account/:id if the id is not one of his accounts.

To resume, it can be viewed as an isOwner policy, but couldn't find one !

Hope you can help me and I'm clear enough for you to understand, do not hesitate to tell me if I can give more details or explain more my problem.

a-coruble
  • 411
  • 4
  • 15
  • Good question, I generally create an action for these scenarios on index response, so something like `GET /bank_account/`has some logic that gets the user ID from the session and only returns a subset of "bank accounts". Be interested to see if there is another solution but I don't think so. – Glen May 05 '19 at 20:02
  • 1
    @Glen Does it mean you override the default blueprint actions ? – a-coruble May 06 '19 at 01:03
  • 1
    Yep, just create a custom route, have a look here https://sailsjs.com/documentation/concepts/routes/custom-routes – Glen May 08 '19 at 17:56

0 Answers0