With the find and update methods i am able to restrict fetching of data restricted to the logged in user by adding a policy that sets req.options.where.owner = userID, therefore i dont need to create custom controllers or models for these methods.
With update and create i can also set req.options.values.owner = userID so that the user cant create or update an object that will belong to another user.
But the problem is that the blueprint findOne controller does not have any options for this kind of filtering, so any logged in user can request an object created and owned by another user.
Is there anyway i can restrict findOne without writing my own controller and query?
Found a solution to the problem, what you can do is to override the default blueprint action by creating a folder named blueprints in your api folder, there you can create a findone.js (lowercase) file,
copy the original blueprint action from /node_modules/sails/lib/hooks/blueprints/actions/findOne.js to /api/blueprints/findone.js
add .where( actionUtil.parseCriteria(req) ); to the query.
Dont forget to change the path of actionutil from require('../actionUtil'); to require('../../node_modules/sails/lib/hooks/blueprints/actionUtil');
Voila, now the findOne action will respect your req.options.where queries.
You can specify blueprint in your policies like this
module.exports = function (req, res, next) {
var blueprint = req.options.action;
if (blueprint === 'findOne') {
// do restriction here
return next();
}
res.forbidden('not allowed to do something');
};
I'm rather forget, is blueprint name findOne or findone.
Related
Sails enables passing an id property when creating an entity,
i want to ignore the id value the user sent and just set my own with autoincrement
how can i do this?
You can do this per model in sails lifecycle callbacks. For example, if you have a User model, in models/User.js you can add:
module.exports = {
attributes: {
// etc
},
beforeCreate: function(attribs, cb) {
// modify the attributes as needed here
delete attribs.id;
cb();
}
}
There are similar callbacks for beforeUpdate, etc. Unfortunately, this would have to be done in every model you want to affect.
One way to remove ids from every blueprint create request would be to use a policy. Create a policy that strips id from req.body, then apply that policy to the route POST /:model (there's an example of applying policies directly to routes here). If you do this, be careful as this could mask other POST routes you are trying to use.
I'm adding custom data to Meteor user accounts for the first time. I've been able to add custom fields without difficulty and I know they're there because I can see them in Mongol. I am publishing via a global subscription so how do I then go about reading data from individual fields? It seems the syntax is very different from that when using publish/subscribe methods.
So, I have user accounts like this (as seen in Mongol):
"_id": "#################",
"profile": {
"name": "Test User"
},
"customfields": {
"customfield1": [
"A","B","C"
]
}
}
In server/main.js I have the following
Meteor.publish(null, function() {
return Meteor.users.find(this.userId, {fields:{customfields:1}});
});
This seems to be publishing fine. But what code do I use to render the cursor as data? I've been using variations on code like this in client/main.js and having no success:
var stuff = Meteor.users.find(this.userId).fetch();
console.log(stuff.customfield1);
Any help appreciated.
MyCollection.find() returns a cursor whereas MyCollection.findOne() returns an object, i.e. a single mongodb document.
A publication must return a cursor or array of cursors. You publication is fine.
You are basically trying to make the customfields key of the user object visible on the client. (The profile key is automatically published by Meteor).
On the client, where you are doing:
var stuff = Meteor.users.find(this.userId).fetch();
You can simply use:
var stuff = Meteor.user();
or
var stuff = Meteor.users.findOne(Meteor.userId());
Then stuff.customfields will contain what you're looking for.
The second form is way too verbose for me unless you're looking for a different user than the logged in user.
Note: this.userId on the client will not be the userId of the current user, it will be undefined. That only works on the server. That may actually be the root cause of your problem. In addition, your publications must be ready() for the data to be available. This isn't true immediately after login for example.
Since customfield1 is nested in customfields, did you try stuff.customfields.customfield1?
Im working on ember-cli, how do i change rest call on fly in the rest adapter. If i use path params not query params?for example:
export default DS.RESTAdapter.extend({
namespace:'res/v1/users/id',
pathForType: function() {
return Ember.String.underscore("friends");},});
Based on the user selection from dropdown we get the "id", using the id I need to get user friends from the database.
Could you please suggest a better way to do. My aapplication supports pathparams not the query params
To customize the URL, override the buildURL method in your adapter.
The tricky part is to access related records from the adapter. For example, you request friends for a given user. You work in a friend adapter, but you need to know the user's id to include it in the URL.
For that purpose, use the record property on the snapshot argument of the buildURL method.
Alternatively, you might want to override some of buildURL's underlying methods such as urlForFindQuery, depending on how you request your model from the store. With a find.query(), you will retrieve the id of the user from the query.
If this does not help you, please respond with the way you're trying to fetch friends from the store.
I have created a variable in enviroment.js 'userId'. When ever i select a user
i set config.userId in the controller to the corresponding Id.
config.userId=this.get('selectedUser');
In pathforType of adapter I used this varible
pathForType: function() {
return Ember.String.underscore(config.userId+"/friends");
}
you just need to add an import statement
import config from '../config/environment';
Please suggest me if anyone get to know better way. Thanks all for your responses
buildURL() only takes the type imo. so you have to pass some more jazz.
i did something along the lines of the following in the application adapter
$ ember generate adapter application
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
findQuery: function(store, type, query) {
var urlQuery = query.theshityouwant;
var reply = this.ajax(this.buildURL(type.typeKey + '/' + urlQuery), 'GET', { headers: all});
return reply;
},
})
});
I have a few questions that I couldn't find answers anywhere online.
Does sails.js framework support HTTP PATCH method? If not - does anyone know if there is a planned feature in the future?
By default if I create method in a controller it is accessible with GET request is it the routes.js file where I need to specify that method is accessible only via POST or other type of methods?
How would you create a policy that would allow to change protected fields on entity only for specific rights having users. I.e: user that created entity can change "name", "description" fields but would not be able to change "comments" array unless user is ADMIN?
How would you add a custom header to "find" method which specifies how many items there are in database? I.e.: I have /api/posts/ and I do query for finding specific items {skip: 20; limit: 20} I would like to get response with those items and total count of items that would match query without SKIP and LIMIT modifiers. One thing that comes to my mind is that a policy that adds that that custom header would be a good choice but maybe there is a better one.
Is there any way to write a middle-ware that would be executed just before sending response to the client. I.e.: I just want to filter output JSON not to containt some values or add my own without touching the controller method.
Thank you in advance
I can help with 2 and 5. In my own experience, here is what I have done:
2) I usually just check req.method in the controller. If it's not a method I want to support, I respond with a 404 page. For example:
module.exports = {
myAction: function(req, res){
if (req.method != 'POST')
return res.notFound();
// Desired controller action logic here
}
}
5) I create services in api/services when I want to do this. You define functions in a service that accept callbacks as arguments so that you can then send your response from the controller after the service function finishes executing. You can access any service by the name of the file. For example, if I had MyService.js in api/services, and I needed it to work with the request body, I would add a function to it like this:
exports.myServiceFunction = function(requestBody, callback){
// Work with the request body and data access here to create
// data to give back to the controller
callback(data);
};
Then, I can use this service from the controller like so:
module.exports = {
myAction: function(req, res){
MyService.myServiceFunction(req.body, function(data){
res.json(data);
});
}
}
In your case, the data that the service sends back to the controller through the callback would be the filtered JSON.
I'm sorry I can't answer your other questions, but I hope this helps a bit. I'm still new to Sails.js and am constantly learning new things, so others might have better suggestions. Still, I hope I have answered two of your questions.
Is it possible to retrieve specific user data (e.g. profile.name or even something else within profile object) with meteor-presence instead of returning userId? Or should I collect all userIds from Meteor.presences and then query Meteor.users with each userId to get the data I need?
Yes that is the best way to do it. You could use transform in your query too!
Meteor.presences.find({}, {transform:function(doc) {
var user = Meteor.users.findOne({_id:doc.userId});
if(user) doc.profile = user.profile;
return doc;
}
});
You can use this query in your template helper or pretty much anywhere else so that it now has a profile object to match the user. Make sure though all your users in your user collection are published in a safe way.