Meteor.. accounts- password-- Create account on client without login - meteor

I'm using accounts-password package - Meteor.
I code interface for admin.
Admin will create accounts for other user.
Accounts.createUser({
email: "abc#gmail.com",
password : "abc123",
profile: { name: register_name }
});
But after this code executed, my application automatic login with account abc#gmail.com, wich i don't want it
Question
How to create accounts without automatic login?
I read accounts-password source but i dont know how to remove automatic login
I also tried to use Meteor.users.insert function but Accounts.setPassword didn't work..

This is a normal behavior using accounts package, to avoid messing with the source code use a Meteor.method/Meteor.call.
This is a simple example,also you can use the default username filed and not a profile:{name:register_name}.
if(Meteor.isServer){
Meteor.methods({
createUserFromAdmin:function(emai,password,username){
Accounts.createUser({email:email,password:password,username:username})
}
})
}else if(Meteor.isClient){
Template.admin.events({
'click #createAccount':function(){
Meteor.call('createUserFromAdmin',email,password,username,function(err,result){
if(!err){
console.log("a new user just got created")
}else{
console.log("something goes wrong with the following error message " +err.reason )
}
})
}
})
}
With this you can create multiple accounts on the admin template, and keep the autologin behavior on the sign-up template (if you have one)

Related

Testing Meteor application with Chimp/Mocha - automatic login to test authenticated routes

I'm testing some forms in a Meteor application using Mocha. The routes in the application are authenticated, so only logged in users or users who have a role of 'administrator' can view them.
When the test opens the browser to view the url and fill the form in, it gets redirected to the login page as expected.
Is there a way to automatically log the user in before doing the test so I don't have to remove the route authentication?
Here's the test code so far
describe( 'Create a Client', function() {
it( 'should create a new client #watch', function() {
browser.url('http://localhost:3000/dashboard/clients/new')
[...]
});
});
use this:
function login(user) {
browser.url('http://localhost:3000')
browser.executeAsync(function(user, done) {
Meteor.loginWithPassword(user.username, user.password, done)
}, user)
}
// now you can do this:
login({
username: 'someone',
password: 'aSecret'
});
browser.url('http://localhost:3000/dashboard/clients/new')
Note that you need to make sure the user exists first, and for that you can use fixtures.
See here for more info:
https://forums.meteor.com/t/solved-how-can-i-wait-for-before-hooks-to-finish-when-testing-with-chimp-meteor-cucumber/18356/12

How to ban a user temporarily in Meteor

I'm developing a simple application using Meteor to learn the framework. I'm using the accounts-password package which incorporates the accounts-base package.
User's will create an account and their email address will serve as their username for login in. This all works perfectly fine as intended. Now I want to take this to the next level.
I want to have the ability to temporarily ban a user for a temporary set period of time - let's say a week.
Is this functionality possible using the accounts-password package or is there another package that exists which will accomplish this functionality? Otherwise how can I implement this functionality on my own?
How about using something like isBanned flag in the users collection against each user? That way, you check for this flag before logging the user in. You could further extend this by having a date field when the ban was applied and later have a way to calculate the elapsed time to see if the ban can be auto-lifted.
db.users.findOne()
{
[...]
"username" : "superadmin",
"profile" : {
"isActive" : true,
"createdBy" : "system",
// is this user banned?
"isBanned" : false,
"updatedAt" : ISODate("2016-10-07T17:33:42.773Z"),
"loginTime" : ISODate("2016-10-07T17:25:44.068Z"),
"logoutTime" : ISODate("2016-10-07T17:33:42.660Z")
},
"roles" : [
"superAdmin"
]
}
Your login form events could be like:
Template.loginForm.events({
'submit #login-form': function(event,template){
event.preventDefault();
// Check for isBanned flag
if(Meteor.users.find({username: template.find("#userName").value,isBanned: false}) {
Meteor.loginWithPassword(
template.find("#userName").value,
template.find("#password").value,
function(error) {
if (error) {
// Display the login error to the user however you want
console.log("Error logging in. Error is: " + error);
Session.set('loginErrorMessage', error.message);
Router.go('/');
}
}
);
Meteor.call('updateLoginTime');
Router.go('loggedIn');
},
}

Not updating Meteor.users.update with insecure package and autopublish on

I've got the following smart-packages installed:
standard-app-packages
autopublish
insecure
preserve-inputs
bootstrap-3
accounts-base
accounts-password
jquery
accounts-ui-bootstrap-3
iron-router
I'm trying to update the email address for a user, and since i've got the insecure and autopublish packages installed, i thought i could just do that like this:
Template.settings.events({
'click #update': function (evt, tmpl) {
evt.preventDefault();
var email = tmpl.find("#inputEmail").value;
Meteor.users.update({_id:Meteor.userId()}, {$set:{"emails":[{address:email}]}});
}
});
But i keep getting: update failed: Access denied
Mabye this comment out of the docs helps you.
Users are by default allowed to specify their own profile field with Accounts.createUser and modify it with Meteor.users.update. To allow users to edit additional fields, use Meteor.users.allow. To forbid users from making any modifications to their user document
You try to change the emails field. At first the emails field should be ( if you want to have the email public ) in profile folder. So you have to do something like
$set: {
profile: {
emails: {
}
}
}
If you change another field outside of profile you have to define allow-rules.

How do you delete user accounts in Meteor?

The only way I have found to delete user accounts in meteor (other than emptying the database with mrt reset), is by actually logging into that specific user account, and deleting the account from the console, using:
Meteor.users.remove('the user id');
But like I said, I need to be logged in as that specific user, and have not been able to find a solution which enables me to delete any user from the db. I'm sure it has something to do with permissions or roles, but I am not sure how to proceed / what is the best solution / how to set an administrative role for a particular user, so that I can delete different user accounts.
You could do
meteor mongo
or
meteor mongo myapp.meteor.com for a deployed app
Then
db.users.remove({_id:<user id>});
I wouldn't recommend it but if you want to delete any user without being logged in from meteor you would need to modify the allow rules. But deleting a user is a very unlikely event hence the above might be the best way to do it.
Anyway if you do want, modify the Meteor.users.allow({remove:function() { return true }); property. See http://docs.meteor.com/#allow. You could add in some custom logic there so it'll only let you do so if you're the admin
I was having trouble doing this on nitrous.io because I couldn't open both Meteor and Mongo. I put:
Meteor.users.remove(' the _id of the user ');
in the isServer section to remove the user.
If anyone is still looking for an answer to this question, I have outlined my solution below.
When I create a new user, I add a field called role in my user document. If I want a user to be able to remove other users from the Meteor.users collection, I give him a role of administrator. If not, I give him a role of member. So, my user document looks something like this -
{
"_id" : ...,
"createdAt" : ...,
"services" : {...},
"username" : "test",
"profile" : {
"name" : "Test Name",
"role" : "administrator"
}
}
On the client, I have a list of users (added using a #each template tag) with a remove button next to each user. A user has to login to see this list. I defined an event handler for the remove button -
'click #remove-user-btn': function () {
Meteor.users.remove({ _id: this._id }, function (error, result) {
if (error) {
console.log("Error removing user: ", error);
} else {
console.log("Number of users removed: " + result);
}
})
}
However, Meteor.users does not allow remove operations from the client by default. So, you have to edit the Meteor.users.allow callback in the server as shown below to allow the users to be removed from the client side. But we need to make sure that only a user with an administrator role is allowed this privilege.
Meteor.users.allow({
remove: function (userId, doc) {
var currentUser, userRole;
currentUser = Meteor.users.findOne({ _id: userId }, { fields: { 'profile.role': 1 } });
userRole = currentUser.profile && currentUser.profile.role;
if (userRole === "administrator" && userId !== doc._id) {
console.log("Access granted. You are an administrator and you are not trying to delete your own document.");
return true;
} else {
console.log("Access denied. You are not an administrator or you are trying to delete your own document.");
return false;
}
},
fetch: []
});
This is the general idea. You can build upon this to suit your needs.
Here are the steps to delete user from mongo through console:
step 1: open new console
step 2: change diretory to your app such as (cd myapp)
step 3 : enter command meteor mongo
step 4: make sure there exists a table called users, db.users.find({});
step 5: find the userid of the user you wish to delete and type :
db.users.remove({_id:"nRXJCC9wTx5x6wSP2"}); // id should be within quotes

How can I create users server side in Meteor?

In the new Meteor auth branch how can I create users server side?
I see how to create them client side with the call to
[Client] Meteor.createUser(options, extra, callback)
But suppose I want to create a Meteor user collection record on startup?
For example, the Administrator account during startup/bootstrapping for an application?
Thanks
Steeve
On newer versions of meteor use
Accounts.createUser({
username: username,
email : email,
password : password,
profile : {
//publicly visible fields like firstname goes here
}
});
note: the password hash is generated automatically
On older versions of meteor use:
1 - NB: DO YOU HAVE THE REQUIRED PACKAGES INSTALLED ?
mrt add accounts-base
mrt add accounts-password
On some versions of meteor you cannot call SRP password salt generator as Steeve suggested, so try this:
2 - do Meteor.users.insert( )
e.g.
var newUserId =
Meteor.users.insert({
emails: ['peter#jones.com'],
profile : { fullname : 'peter' }
});
note: a user must have EITHER a username or an email address. I used email in this example.
3 - Finally set the password for the newly created account.
Accounts.setPassword(newUserId, 'newPassword');
Probably it's a well known fact now, but for the sake of completing this - there's a new server API for doing this on the auth branch. From the docs on auth:
" [Server] Meteor.createUser(options, extra) - Creates a user and
sends that user an email with a link to choose their initial password
and complete their account enrollment
options a hash containing: email (mandatory), username (optional)
extra: extra fields for the user object (eg name, etc). "
Please note the API is subject to change as it's not on the master branch yet.
For now this has been suggested in the meteor-core google group.
Meteor.users.insert({username: 'foo', emails: ['bar#example.com'], name: 'baz', services: {password: {srp: Meteor._srp.generateVerifier('password')}}});
It works. I tested it in during startup/boot strap.
I would not consider this the permanent or long term answer because I believe the auth branch is still in a great degree of change and I imagine the team behind Meteor will provide some kind of functionality for it.
So, do not depend on this as a long term answer.
Steeve
At the moment, I believe you cannot. Running
Meteor.call('createUser', {username: "foo", password: "bar"});
comes close, but the implementation of createUser in passwords_server.js calls this.setUserId on success, and setUserId cannot be called on the server unless we're in a client-initiated method invocation (search for "Can't call setUserId on a server initiated method call" in livedata_server.js.
This does seem like something worth supporting. Perhaps the last three lines of createUser, which log the user in, should be controlled by a new boolean login option to the method? Then you could use
Meteor.call('createUser', {username: "foo", password: "bar", login: false});
in server bootstrap code.
I've confirmed that the following code in my server/seeds.js file works with the most recent version of Meteor (Release 0.8.1.1)
if (Meteor.users.find().count() === 0) {
seedUserId = Accounts.createUser({
email: 'f#oo.com',
password: '123456'
});
}
Directory (or folder) of server means I'm running the code on the server. The filename seeds.js is completely arbitrary.
The official documentation now describes both the behavior for Accounts.createUser() when run on the client and when run on the server.
Working coffeescript example for Meteor version 1.1.0.2 (server side):
userId = Accounts.createUser
username: 'user'
email: 'user#company.com'
password: 'password'
profile:
name: 'user name'
user = Meteor.users.findOne userId
I struggled for some time with this API getting 'User already exists' exception in working code before adding profiles.name to the options and exception disappeared.
reference: Accounts.createUser(options,[callback])
Create user from server side
// Server method
Meteor.methods({
register: function(data) {
try {
console.log("Register User");
console.log(data);
user = Accounts.createUser({
username: data.email,
email: data.email,
password: data.password,
profile: {
name: data.email,
createdOn: new Date(),
IsInternal: 0
}
});
return {
"userId": user
};
} catch (e) {
// IF ALREADY EXSIST THROW EXPECTION 403
throw e;
}
}
});
// Client call method
Meteor.call('register',{email: "vxxxxx#xxxx.com",password: "123456"}, function(error, result){
if(result){
console.log(result)
}
if(error){
console.log(result)
}
});

Resources