Reputation: 103
I have a user model and a widget model. I have a relationship setup between user and widgets. I also have a policy defined for authentication, if the user is authenticated then I'm saving the user ID in the req.session.
The user is required on the widget:
attributes: {
user: {model: 'user', required: true}
}
is there some way to tell the WidgetController to use the user from the auth policy and still use all the default actions provided by blueprint?
Upvotes: 2
Views: 1378
Reputation: 24948
As @MrVinz writes in his answer, policies are a great way to accomplish this. However, altering req.body
or req.query
isn't recommended, because you might want access to their original values. Instead, you can use req.options.values
to provide defaults for blueprint values. For example, to default the name
value to a logged-in user's name, you could create a policy similar to:
module.exports = function defaultNamePolicy (req, res, next) {
// Make sure req.options.values is an object, and don't overwrite
// values from prior policies
req.options.values = req.options.values || {};
// If there's a logged in user, default to using their name.
// Otherwise this will be undefined and will have no effect
req.options.values.name = req.session.user && req.session.user.name
return next();
}
The values in req.options.values
are used as defaults for the request, so if req.param('name')
exists, it will be used instead of req.options.values.name
.
Upvotes: 3
Reputation: 874
Yes there is :) You can use a policy to achieve this :)
module.exports = function(req, res, next) {
if(req.session.user){
//then it depends on your implementation but
req.params["widget"].user=req.session.user
//cab be req.query["widget"] or req.body["widget"]
/*
if(req.params["widget"]){
req.params["widget"].user=req.session.user
}
if(req.query["widget"]){
req.query ["widget].user=req.session.user
}
if(req.body["widget"]){
req.body ["widget].user=req.session.user
}
*/
}
//other stuff
next();
}
you can also make this more generic by doing something like this
var model = req.options.model || req.options.controller;
if(model && sails.models[model].attributes['user']){
//do the same trick
}
if you store a "user" full object in your session
adapt the code and use a req.session.user.id
EDIT
My apologies i use custom blueprints and queries as i'am using sails ember blueprints :) however it makes things even easier you just have to check req.params["user"]
or req.query["user"]
if my memory is correct :)
Upvotes: 1