Remove all data in a collection relating to user - meteor

I'm trying to remove data in a collection, however, I'm getting remove failed: Access denied. I'm not sure what I'm doing wrong.
DB - Files.find
"_id": "",
"url": "",
"userId": "",
"added": ""
Path: file.js
Template.file.events = {
"click .delete-photo" : function () {
Files.remove(this._id);
}
};

If you are uninstall autopublish package use method as above answer:
Meteor.methods({
removePhoto: function (photoId) {
check(photoId, Meteor.Collection.ObjectID);
Files.remove(photoId);
});
And on your client:
Meteor.call("removePhoto", this._id, function(error, affectedDocs) {
if (error) {
console.log(error.message);
} else {
// Do whatever
console.log("success");
}
});
and if you uninstall insecure package please publishand subscribe the collection.
Meteor.publish('collectionname',function(){
return collectionname.find();
}
and subscribe:
Meteor.subscribe('collectionname);

You should consider making this into a Meteor method.
Server side code:
Meteor.methods({
removePhoto: function (photoId) {
check(photoId, Meteor.Collection.ObjectID);
Files.remove(photoId);
});
You should consider to remove the insecure and autopublish packages by typing these commands in your console:
meteor remove autopublish
meteor remove insecure
Below there is an example of how to publish the Files collection (here you also could add security features, such as only find and publish files belonging to user with correct id):
Meteor.publish('files',function(){
return Files.find();
}
And on your client:
Meteor.call("removePhoto", this._id, function(error, affectedDocs) {
if (error) {
console.log(error.message);
} else {
// Do whatever
console.log("success");
}
});
Here is the code for subscribing to the Files collection:
Meteor.subscribe('collectionname');
Read about methods, publish and subscribe over at Meteor docs. Links: http://guide.meteor.com/methods.html, https://www.meteor.com/tutorials/blaze/security-with-methods, https://www.meteor.com/tutorials/blaze/publish-and-subscribe

Related

Meteor "update failed: Access denied" when user attempts to update their own profile?

Im adding a field to a user's account on creation. This is working fine:
Accounts.onCreateUser((options, user) => {
user.groups = [2];
return user;
});
I need to make a function that allows the user to change this. When I run this from the front-end I get an error "update failed: Access denied"
Meteor.users.update(
{ _id: Meteor.userId() },
{
$set: { groups: [4, 5] },
},
);
In server/main.js I have:
Meteor.publish('currentUser', function() {
return Meteor.users.find({ _id: this.userId }, { fields: { groups: 1 } });
});
Do not make db updates from the client directly. No client can ever be trusted.
Having said that, there are two ways to deal with this:
ONE
As per the documentation :
By default, the current user’s username, emails and profile are
published to the client. You can publish additional fields for the
current user with:
// Server
Meteor.publish('userData', function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId }, {
fields: { groups: 1 }
});
} else {
this.ready();
}
});
Meteor.users.allow({
update: function(userId, user) {
return true;
/**
* Don't use `return true` in production!
* You probably need something like this:
* return Meteor.users.findOne(userId).profile.isAdmin;
*/
}
});
// Client
Meteor.subscribe('userData');
Meteor allow rules
TWO
Define a meteor method in the server and have the server update the relevant data for you AFTER it does some validations. Server code is always trusted.
server.js
Meteor.method({
updateGroups: function(data){
// make changes to the user record
});

How to populate client-side Meteor.user.services after OAuth with built-in accounts-ui package in Meteor v1.4+?

I'm using accounts-ui and accounts-google in Meteor v1.4.1. I can't get the user.services object to appear scoped in the client code. In particular, I need google's profile picture.
I've configured the server-side code to authenticate with Google like so:
import { Meteor } from 'meteor/meteor';
import { ServiceConfiguration } from 'meteor/service-configuration';
const services = Meteor.settings.private.oauth;
for (let service of Object.keys(services)) {
ServiceConfiguration.configurations.upsert({
service
}, {
$set: {
clientId: services[service].app_id,
secret: services[service].secret,
loginStyle: "popup"
}
});
}
...and the client side code to configure permissions like so:
Accounts.ui.config({
requestPermissions: {
google: ['email', 'profile']
},
forceApprovalPrompt: {
google: true
},
passwordSignupFields: 'EMAIL_ONLY'
});
When users click the 'Sign-In with Google' button, a pop-up appears and they can authenticate. No prompt appears, however, despite forceApprovalPrompt being set to true for google.
The big issue is that when I execute this,
const user = Meteor.user();
console.log(user.services);
anywhere in client code, I do not see the expected user services information. I check my database and it is definitely there for the taking:
$ mongo localhost:27017
> db.users.find({})
> ... "services" : { "google" : { "accessToken" : ... } } ...
I'm curious what I'm missing? Should I explicitly define a publish function in order for user services data to exist in the client?
The services property is intentionally hidden on the client side for security reasons. There are a couple of approaches here :
Suggestions
My preferred one would be to expose a meteor method to bring you the
public keys and avatars you might need in the few places you'd need
them.
On a successful login, you could record the data you need somewhere in the user object, but outside of the services property.
As you said, you could make a new publication which explicitly specifies which fields to retrieve and which ones to hide. You have to be careful what you publish, though.
Code Examples
Meteor methods:
// server
Meteor.methods({
getProfilePicture() {
const services = Meteor.user().services;
// replace with actual profile picture property
return services.google && services.google.profilePicture;
}
});
// client
Meteor.call('getProfilePicture', (err, profilePicture) => {
console.log('profile picture url', profilePicture);
});
Update on successful user creation (you might want to have a login hook as well to reflect any avatar/picture changes in google):
// Configure what happens with profile data on user creation
Accounts.onCreateUser((options, user) => {
if (!('profile' in options)) { options.profile = {}; }
if (!('providers' in options.profile)) { options.profile.providers = {}; }
// Define additional specific profile options here
if (user.services.google) {
options.profile.providers.google = {
picture: user.services.google.picture
}
}
user.profile = options.profile;
return user;
});
Publish only select data...
// Server
Meteor.publish('userData', function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId }, {
fields: { other: 1, things: 1 }
});
} else {
this.ready();
}
});
// Client
Meteor.subscribe('userData');

Meteor: callLoginMethod not found error

I'm having difficulty invoking a login method, it follows
$ meteor list
Accounts-base 1.2.14 A user account system
Ecmascript 0.6.1 Compiler plugin that supports ES2015 + in all .js files
Meteor-base 1.0.4 Packages that every Meteor app needs
React 15.0.1 Everything you need to use React with Meteor.
Static-html 1.1.13 Defines static page content in .html files
/server/main.js
import { Accounts } from 'meteor/accounts-base'
Accounts.registerLoginHandler('simples', (ttt) => {
console.log(ttt);
});
/client/main.js
autenticar(){
Accounts.callLoginMethod({
methodName: 'simples',
methodArguments: [{ tipo : 'simples' }],
validateResult: function (result) {
console.log('result', result);
},
userCallback: function(error) {
if (error) {
console.log('error', error);
}
}
})
}
When calling authenticar(), I get this error:
errorClass
  Details: undefined
  Error: 404
  ErrorType: "Meteor.Error"
  Message: "Method 'simples' not found [404]"
  Reason: "Method 'simples' not found"
Where is the error?
I've never used this API personally, but from a quick glance through the Meteor internals, I see a couple issues.
Accounts.registerLoginHandler only adds an additional handler to an array of built-in handlers which are called as part of the default Meteor login process.
If you are trying to plug in an additional handler into the existing process, you should call Accounts.callLoginMethod without the methodName key.
Calling Accounts.callLoginMethod with methodName will bypass the built-in handlers completely and replace them with your custom method, however this method needs to be declared separately by you with Meteor.methods, not registerLoginHandler.
So, that's probably your error -- you need to define your simples method with Meteor.methods. Also, you should check the code for the requirements of this method, see the comments in the code here:
https://github.com/meteor/meteor/blob/devel/packages/accounts-base/accounts_client.js
Only to complement and keep as a referral for someone else to get here. That way it's working
client.js
Accounts.callLoginMethod({
methodArguments: [{tipo: 'simples'}],
validateResult: (result) => {
console.log('success', result);
},
userCallback: function(error) {
if (error) {
console.log('error', error);
}
}
});
server.js
Meteor.startup(function () {
var config = Accounts.loginServiceConfiguration.findOne({
service : 'simples'
});
if (!config) {
Accounts.loginServiceConfiguration.insert({ service: 'simples' });
}
});
Accounts.registerLoginHandler((opts) => {
if(opts.tipo === 'simples'){
return Accounts.updateOrCreateUserFromExternalService ('simples', {
id: 0 // need define something
}, {
options : 'optional'
})
}
});

Meteor Method w/ Mongo Aggregation returning Undefined on Client but not on Server

So I've just started with Meteor and really JavaScript so forgive the messy coding as I am new to all of this please. I'm using a Mongo Aggregation to do some server side math and the method is returning undefined on the client but the server-side console log is returning the correct information. Here is the server method...
Meteor.methods({
'schoolHealth': function() {
var pipeline = [
{
"$group": {
"_id": null,
"total": { "$avg": "$roomHealth"}
}
}
];
Equipment.aggregate(pipeline, function(err, result) {
if (err) {
throw err;
console.log("Error in finding school health average:" + result);
} else {
console.log(result[0].total)
return result[0].total;
}
});
}
});
And on the client...
Meteor.call('schoolHealth', function(error, result) {
if (error) {
console.log(error);
} else {
console.log(result);
Session.set('health', result);
}
});
I'm calling the Session on a blaze template but the method is failing before that happens. Also, I have tried not using a Session and the result is the same. I have read into Sync vs. Async but I don't know enough about it to know if I am doing something wrong there. Thanks ahead of time for the help.

Meteor accounts verifyEmail

I am trying to make email verification that with the accounts-password package work however I have come across a weird problem.
It seems the # in the email verification URL is causing an issue. The verification email URL usually looks like : http://localhost:3000/#/verify-email/cnaTqQSCgYAksIsFo5FgmV94NHwrfaM2g5GvdZDUMlN
When I click on this, nothing seems to happen; it just re-directs to localhost:3000/#
However when I remove the # (http://localhost:3000/verify-email/cnaTqQSCgYAksIsFo5FgmV94NHwrfaM2g5GvdZDUMlN) this seems to work perfectly.
The URL (http://localhost:3000/#/verify-email/cnaTqQSCgYAksIsFo5FgmV94NHwrfaM2g5GvdZDUMlN) comes from Meteor so it's not something I create.
Here are my routes and controllers (using iron-router)
Router.route('/verify-email/:_token', {
controller : 'AccountController',
action : 'verifyEmail'
});
AccountController = RouteController.extend({
fastRender: true,
data: function () {},
onBeforeAction: function () {
this.render('Loading');
this.next();
},
verifyEmail: function() {
var verificationToken = this.params._token;
console.log(verificationToken);
Accounts.verifyEmail(verificationToken, function(error) {
if (error) {
console.log(error);
} else {
Router.go('/');
}
});
}
});
Any help is appreciated.
The conflict might be connected to the accounts-password package together with iron:router as outlined here:
...add a server file that overrides the urls with # paths that Meteor creates, so that the Iron-Router can work:
(function () {
"use strict";
Accounts.urls.resetPassword = function (token) {
return Meteor.absoluteUrl('reset-password/' + token);
};
Accounts.urls.verifyEmail = function (token) {
return Meteor.absoluteUrl('verify-email/' + token);
};
Accounts.urls.enrollAccount = function (token) {
return Meteor.absoluteUrl('enroll-account/' + token);
};
})();
Hope it will guide you in the right direction.

Resources