Is it possible to add a role to a user with alanning:roles in meteor from an template event? - mongodb

I am fairly new to Meteor and have been having real trouble with this issue.
I would like to have a select element which updates the users role (once logged in) depending on the option selected. I'm storing the value of the option as a variable when the select is changed and trying to take this value as the name of the role to add to the user.
When I run my app and change the select, the role seems to pop up for a second (viewed in Mongol) before disappearing again. I created a small test to display an alert of the role for the user, which shows up containing the name of the role but once you OK it, the role has disappeared. Am I missing something here?
Here is my template containing the select element...
<template name="select">
<select id="select">
<option value="working">Looking for work</option>
<option value="hiring">Hiring</option>
</select>
</template>
And here is the client side code for the change event
Template.select.events({
'change #select': function (event) {
//remove any current roles added to the user as it will be either
//one or the other
Roles.removeUsersFromRoles( Meteor.userId(), 'working', 'hiring' );
//add a role to the current user with the value from select box
var value = $(event.target).val();
Roles.addUsersToRoles( Meteor.user(), value );
//each of these alerts displays correctly depending on the select
//value
var test = Roles.userIsInRole( Meteor.user(), 'hiring' ); // true
if (test===true){
alert('in hiring role');
}
var test2 = Roles.userIsInRole( Meteor.user(), 'working' ); // true
if (test2===true){
alert('in working role');
}
// either working or hiring
alert(Roles.getRolesForUser(Meteor.userId()));
// alert displays count of 1 when you select 'hiring'
alert(Roles.getUsersInRole('hiring').count());
}
});
Any help would be much appreciated, have been searching through the documentation and online for several days to no avail. Many thanks :)

You try to add roles in your client. However, the client reflects only the data from the server's Roles collection.
You need therefore to change your code to a server side method, that
a) checks wether the current user is permitted to change roles (warning here, potential security threats when not checking permissions)
b) checks, wether the targeted user exists
c) sets the roles for the given userId
There is a good example in the documentation on how to do that. This is a slightly modified version of it:
Meteor.methods({
'updateRoles'({userId, roles, group}) {
check(userId, String);
check(roles, [String]);
check(group, String);
// a) check permission
if (!this.userId || !Meteor.users.findOne(this.userId) || !Roles.userIsInRole(this.userId, 'update-roles', 'lifted-users'))
throw new Meteor.Error('403', 'forbidden', 'you have no permission to change roles');
// b) check target user
if (!Meteor.users.findOne(userId))
throw new Meteor.Error('404', 'user not found');
// c) update user's roles
Roles.setUserRoles(userId, roles, group);
return true;
}
});
This method assumes, that there is a special role/group combination for users, that are allowed to change roles. This should be only a very few people, like admins.
Also note, that this method sets the user roles by using Roles.setUserRoles. If you want to extend the roles you need to use Roles.addUserToRoles.
You can then call this method from your client like every Meteor method:
Template.select.events({
'change #select': function (event) {
// get value from select box
var roles = [$(event.target).val()];
// TODO create a second select for the group
var group = 'defaultUsers'
var userId = Meteor.userId();
Meteor.call('updateRoles', { userId, roles, group }, (err, res) => {
// handle err / res
console.log(Roles.userIsInRole(userId, roles, group)); // should return true
});
}
});
Note, that Roles on the client is a collection which is immediately subscribed to. Changes are reflected reactively. If you do not see the changes immediately

Related

How to stop the user from entering the duplicate record on default save

I have a custom module where there is an email field. Now i want to stop the user if the email is already in the database.
I want to stop the user on save button and show the error. Like when a required field goes empty.
I tried to get some help but was not able to understand it.
Note: I realized after posting this that you are using suitecrm which this answer will not be applicable toward but I will leave it in case anyone using Sugar has this question.
There are a couple of ways to accomplish this so I'll do my best to walk through them in the order I would recommend. This would apply if you are using a version of Sugar post 7.0.0.
1) The first route is to manually create an email address relationship. This approach would use the out of box features which will ensure your system only keeps track of a single email address. If that would work for your needs, you can review this cookbook article and let me know if you have any questions:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_the_Email_Field_to_a_Bean/
2) The second approach, where you are using a custom field, is to use field validation. Documentation on field validation can be found here:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/index.html
The code example I would focus on is:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/#Method_1_Extending_the_RecordView_and_CreateView_Controllers
For your example, I would imagine you would do something like this:
Create a language key for your error message:
./custom/Extension/application/Ext/Language/en_us.error_email_exists_message.php
<?php
$app_strings['ERROR_EMAIL_EXISTS_MESSAGE'] = 'This email already exists.';
Create a custom controller for the record creation (you may also want to do this in your record.js):
./custom/modules//clients/base/views/create/create.js
({
extendsFrom: 'RecordView',
initialize: function (options) {
this._super('initialize', [options]);
//reference your language key here
app.error.errorName2Keys['email_exists'] = 'ERROR_EMAIL_EXISTS_MESSAGE';
//add validation tasks
this.model.addValidationTask('check_email', _.bind(this._doValidateEmail, this));
},
_doValidateEmail: function(fields, errors, callback) {
var emailAddress = this.model.get('your_email_field');
//this may take some time so lets give the user an alert message
app.alert.show('email-check', {
level: 'process',
title: 'Checking for existing email address...'
});
//make an api call to a custom (or stock) endpoint of your choosing to see if the email exists
app.api.call('read', app.api.buildURL("your_custom_endpoint/"+emailAddress), {}, {
success: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//analyze your response here
if (response == '<email exists>') {
errors['your_email_field'] = errors['your_email_field'] || {};
errors['your_email_field'].email_exists = true;
}
callback(null, fields, errors);
}, this),
error: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//throw an error alert
app.alert.show('email-check-error', {
level: 'error',
messages: "There was an error!",
autoClose: false
});
callback(null, fields, errors);
})
});
},
})
Obviously, this isn't a fully working example but it should get you most of the way there. Hope this helps!

How do I remove a user in mongoDB from the terminal by username?

My question is this: How can I remove a user from the users db by username, or at all even?
I have a meteor application with a custom registration, and when an account is created you can login and manage your account and what have you.. My problem is that, on the local host for testing, I created a few extra user accounts that I want to delete individually (not a complete reset). I am on OS X so I went to terminal, typed in 'show dbs' but users came up empty and when I typed 'show users' nothing came up. If I type 'db.users.findOne()' information appears and I can get a username and _id. I know there is users and this command shows that there is at least one but the rest of the commands indicate that I can't manage them.
Below is some code for the registration page, specifically the Accounts.createUser I'm not sure it will mater for the response but I wanted to be thorough.
Template.SignUp.events({
'submit form': function(event, template){
event.preventDefault();
var UsernameVar = template.find('#username').value;
var emailVar = template.find('#Email').value;
var passwordVar = template.find('#password').value;
var ConfirmPasswordVar = template.find('#Cpassword').value;
if(ConfirmPasswordVar == passwordVar)
{
document.getElementById("NotValid").style.display = 'none';
Accounts.createUser({
username: UsernameVar,
email: emailVar,
password: passwordVar
}, function(err, result){
if(err)
{
document.getElementById("Unavailable").style.display = 'block';
}
else{
document.getElementById("Unavailable").style.display = 'none';
}
});
}
else{
document.getElementById("NotValid").style.display = 'block';
}
}
});
I've done a lot of searching on this issue and all I've found is how to grant users the right to remove profiles but I want to do it from terminal, even when the application launches I will be the only one to be using this feature so I don't want to start giving those rights to users.
If there is anything else I should provide please let me know.
meteor mongo
db.users.find({username: "someusername"}) // ensure that your query returns the correct user that you want to remove
db.users.remove({username: "someusername"})

Autopublish removed but why can I still retrieve data from db?

I have a simple Meteor/MongoDB project using the 'roles' package where I optain data from the db to the client. The roles package seems to work fine and the browser shows the right data depending on who is logged in, just like it should do. Then when running 'meteor remove autopublish' in the terminal inside my applications directory I get 'autopublish removed' just like it should. Still I can retrieve data from the server just as before(!?)
I have all of my db calls from the client/client.js.
The server/server.js does nothing (I do have publish/subscribe code but uncomment for now) and same goes for the common js file in main directory.
How can this be? Am I perhaps retrieving data from minimongo somehow? I have also removed insecure even if I don't think that matters in this case(?) Thanks in advance.
EDIT: Here's the code:
client.js:
//when uncomment the subscribe's you should not get access to the server/db, but 'data' that holds all the inlogg info still shows. The 'movies' on the other hand doesn't, just like it shouldn't.
//Meteor.subscribe('data');
//Meteor.subscribe('movies');
/*############# Get User Data ###############*/
Template.userLoggedIn.id = function () {
return Meteor.userId();
};
Template.userLoggedIn.email = function () {
var email = Meteor.users.findOne({_id: Meteor.userId()});
return email.emails[0].address;
};
Template.userLoggedIn.profile = function () {
var profile = Meteor.users.findOne({_id: Meteor.userId()});
return profile.profile.name;
};
Template.userLoggedIn.role = function () {
var role = Meteor.users.findOne({_id: Meteor.userId()});
return role.roles[0];
};
/*############# ###############*/
Template.movies.movies = function() {
var movies = Movies.find().fetch();
return movies;
}
server.js:
Meteor.publish('data', function () {
return Meteor.users.find();
});
Meteor.publish('movies', function() {
return Movies.find();
});
Thanks for providing the code - I see how this could be confusing. The users section of the docs should be written to explicitly say this, but what's happening is the current user is always published. So even if you don't write a publish function for users (or your have your subscribe commented out), you should expect to see the current user on the client. Because your template code only looks for Meteor.userId(), I would expect it to still work.
Assuming you have other users in the database, you can quickly check that they are not being published by running: Meteor.users.find().count() in your browser console. If it returns 1 then you are only publishing the current user (or 0 if you are logged out).

Why do i not get through to my Meteor.method on the server?

I'm trying to add a url to the logged in users collection. My final goal at least is to be able to add a field e.g {profilePicture: 'http://randompic.com/123.png'}
What i've tried so far is:
<template name="profile">
<h1>My Profile</h1>
<form class="form-inline"action="">
<label for="url"></label>
<input class="input input-large" type="url" name="url" placeholder="URL for you image..." id="url">
<button class="btn btn-success submit">Update profile picture</button>
</form>
</template>
When the user will press the Update profile picture -button i send it to this helper function:
Template.profile.events({
'click .submit': function (evt, tmpl) {
var userid = Meteor.userId();
var url = tmpl.find('#url').value;
var options = {_id: userid, profilePicture: url};
Meteor.call('addToProfile', options);
}
});
I have tried to alert out option._id and options.profilePicture and i have that data availble.
Now when i pass it along to my server.js file i get no output of my alert:
Meteor.methods({
'addToProfile': function(options) {
//Not even this alert will show..
alert(options._id); Edit: console.log() works on the server thought.
}
})
So that is my first issue.
The second problem (to come) is that i don't know how to update/add to the users collection with this profilePicture data. Would really appreciate if someone could contribute with a small example of that part.
Based on the comments everything seems to be functioning as expected. It appears that you are just trying to update some user data on the client. Since you have the insecure package removed you need to validate the updates on the server (that the client requests), this is how you would do that:
// only applies to client requests
Meteor.users.allow({
// validation for user inserts
insert: function ( userId, doc ) {
// perform any checks on data that you want to perform, like checking to see if the current user is an admin.
// this check just requests that a user be logged in
return userId;
}
,
// is your validation for user updates
update: function ( userId, doc, fields, modifier ) {
// again, perform any validation you want. A typical check is to make sure they didn't add any extra fields.
// this makes sure a user is logged in and that they are only attempting to update themself
return userId === doc._id;
}
});
There are some more thorough examples in the docs. Now you can just call update like you normally would and rely on the server to perform any validation!

How to add an additional field to Meteor.users collection (not within the Profile field)

I'm currently building a mini app that takes in a user login into Facebook for an event. There is no determining how many people will login, hence, mongoDB will be updated as users (clients) log in. However, I'm trying to insert an additional boolean field in Meteor's users collection and I'm not sure how to go about doing that. Here is my accounts.js code (server-side) that add's in users
Accounts.onCreateUser(function (options, user) {
if (options.profile) {
//want the users facebook pic and it is not provided by the facebook.service
options.profile.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
data = user.services.facebook;
user.profile = options.profile;
user.profile.voted = false;
}
return user;
});
Currently, I'm assigning the boolean field ("voted") to the profile field. But I can't seem to update this boolean value from the client-side js. The code I've got over here is shown below
Template.skills.events({
'click input.inc': function () {
Skills.update(Session.get("selected_skill"), {$inc: {mana: 1}});
//Meteor.users.update({_id:Meteor.default_connection.userId()},{$set:{profile.name:true}});
alert(Meteor.user().profile.name);
}
});
FYI:skills.events is merely a handlebar (Handlebars.js) that is triggered when a button is clicked. The attempt here is to update MongoDB when the button is clicked.
I'm pretty new to Meteor and hope the information provided is sufficient.
You just add one.
user.voted = false;
If you want to access the field on the client side, make sure to create additional subscription channel for it. Meteor does not publish custom user properties by default.