Setup page on first login, express.js - javascript

I'm using Passport.js to authorize user into my express.js app.
I want to show setup page when user logins first time.
Can I do this with Passport?

This Code MUST be modified mor your db, etc.
Init The User:
var user = new User({ ... });
user.newUser = true;
And
app.get("/account",requireLogin, function(req,res){
if(req.user.newUser){
req.user.newUser = false;
req.user.save(function(err){
if(err) return handleError(err);
res.redirect("/setup");
})
}
})

You need to place newuser attribute within the database as answered by "Ari Porad" but the better approach would be to change it to false when you are done with account first time setup because we dont really know if the user has completed his first time setup or not (browser may crash and he might not be able to complete it :D ) , so its better not to modify the "newuser" attribute as false on first visit but rather you should be modifying it after he has submitted the data that we require on the first visit.

Related

Implementing "coins" to my users on passportjs and changing them

I actually have 2 questions. One is what is the best way to go about adding other information to my user object? I have a very simple passportjs login/register system and I want to expand and also add things like coins and other things that are specific to a user's account. Currently, I just added a new property called "coins" along with the password/email and stuff.
My second question is with my coins property for my user object, how do I edit it? Currently I just have a simple request to add a coin for the user and it isn't working.
router.get('/coin', function(req, res) {
User.getUserByUsername(req.user.username, function(err, user){
user.coins = user.coins + 1
console.log(user.coins)
});
res.redirect('/')
});
It is just console logging 1 every time I press the button(the button calls for /coin)
You are loading the user, incrementing one coin, but you are not saving it. So, every time you call the function, load previous state of User.
You should call User.update or whatever as the function of your api is called to save the user data before redirecting.
router.get('/coin', function(req, res) {
User.getUserByUsername(req.user.username, function(err, user){
user.coins = user.coins + 1
User.update(user) // Stores modified data.
console.log(user.coins)
});
res.redirect('/')
});

Redirect a user if they do not have a set password before publishing

I have an interface in my website where a user can create an "unclaimed" order for another user and send them an invitation. The invitation link will be formatted as /enrollment/orders/:_id, where _id is the id of the order.
One catch is that this can be sent multiple times. On the first time, the user that is invited might not have a password set.
Meteor.publish('enrolled_order', function (token) {
// if user has their password reset, token will also be set for user's account
return Orders.find({
'enrollment.token': token
});
});
Here's the catch: During this publication, I want to check certain aspects of the user record and take different actions instead of publishing it. For security, I believe this will need to be done on the server to work appropriately.
if there is no this.userId, I want to send them to login.
if the user does not have a password set, I want to redirect them to the reset password page.
Is this possible via a meteor publication?
I think you would need to do this in the router. If you're using Iron Router, you could use onBeforeAction to check whether the user is logged in:
Router.route('/enrollment/orders/:_id', {
subscriptions: function() {
return Meteor.subscribe('enrolled_order', this.params._id);
},
onBeforeAction: function() {
if( ! Meteor.userId() ) {
Router.go( 'loginTemplateName' );
}
}
});
You aren't going to want to return the hashed password directly to the client, so maybe setting a variable to say whether the password exists or not might be the best approach?
I can't remember if onBeforeAction happens before waitOn, but you might be able to get away with waitOn instead of subscriptions.

How can I display a list of all LOGGED IN users with Meteor.js

I have been trying for days to get a list of logged in users in a Meteor chat app.
I tried many different things. I managed to add a login flag on the user profile object.
Server side:
Accounts.onCreateUser(function(options, user) {
if(!options.profile){
options.profile = {}
}
options.profile.login = false;
if (options.profile)
user.profile = options.profile;
return user;
});
In the browser console I get this:
Meteor.user().profile
Object {login: false}
So that seems to work.
Now I want to list if users are logged in:
Client side
Deps.autorun(function(){
if(Meteor.userId()){
Meteor.user().profile.login=true;
}
});
After checking the login remains false when I log in.
This template html gives me a list of all usernames but not the login flag
{{#each allUsers}}
<p>{{username}}</p><p>{{profile.login}}</p>
{{/each}
So my problems are : profile.login remains false and I cannot display profile.login but the usernames are displayed.
Thank you in advance. Greetings Joris
To change the users profile.login property you need to do Meteor.users.update(..) or call a server method that does that. Just changing the user object's property will not work.
Generally I would recommend to not persist the users state into the mondodb database but hold it in a Collection in memory.
The easiest might be to just use one of these packages:
https://github.com/dburles/meteor-presence/
https://github.com/mizzao/meteor-user-status
or study their source code to see how to propagate the user status.

angularjs redirection after login

may I know how to redirect user to where they originally at after login ? say i have a post wwww.example.com/post/435 and it required user to log in in order to "like/comment" the post, so after the user login how can i redirect user back to the post ? i have tried this
$http.post('/sessionHandler/login',$scope.form).
success(function(data){
history.back(); // bring user back to previous path
}).error(function(err){
$scope.errorMessage = err;
});
however this is not really effective, if a user previous path is other site or a browser new tab it will redirect the user back to where they are.
i also found some example by using $locationChangeStart but i'm having some difficulties to understand how it works this is what i have so far for $locationChangeStart
$http.post('/sessionHandler/login',$scope.form).
success(function(data){
$rootScope.$on("$locationChangeStart", function (event, next, current) {
$location.path();// how to access to previous url where the user from ?
// how to use event, next and current to get the user last
// path on my site, and how to determine the last site is
// on my site but not other website ?
});
})
your help is appreciated !!
May not be the best answer, but I use a cookie for this - so whenever I'm redirecting to a new location, I'll use $cookies.loginDestination = $location.path(), then whenever a user logs in, I use something like:
var loginDestination = $cookies.loginDestination || '/';
$cookies.loginDestination = null;
$location.path(loginDestination);

Meteor: Adding Fields on createAccount

I'm trying to use the Meteor Roles package: https://github.com/alanning/meteor-roles
to obviously create a new field in user model.
The user is created no problem but the 'roles' field I'm trying to define isn't created. I can add things like 'Profile' and details within that too. But for some reason I can't make a roles field. Here's my form:
Template.signup.events({
'submit #signup-form' : function(e, t) {
e.preventDefault();
var roles = ['admin'],
email = t.find('#email').value,
password = t.find('#password').value;
Accounts.createUser({email: email, password : password, roles: roles}, function(err){
if (err) {
alert("User Not Added")
} else {
console.log("User Added.")
}
});
}
});
Eventually I'll need to publish this to the client but for right now I just want the field to show in MongoDb, which it's not.
3 things:
I feel like the code above should work but I'm clearly missing something
In the package docs it mentions this Roles.addUsersToRoles which I
tried but no luck
Or do I need to possibly update the record, after it's been created?
I did go into the DB and manually added the field and associated string to update it (with $set) and it worked. But from the form itself though, no luck.
Any pointers would be much appreciated. Thank you.
The Accounts.createUser function only lets you add arbitrary user properties via the profile option which is where they end up getting stored in mongo. That is why Meteor is ignoring the roles: roles part of your Accounts.createUser call.
It is true that the meteor-roles package stores the list of roles assigned to a user directly in the users collection, but that is almost just an implementation detail and you are probably best off sticking to the API that meteor-roles provides for adding users to a role:
Roles.addUsersToRoles(<userId>,[<list of roles>])
The userId passed to Roles.addUsersToRoles is the value returned by Accounts.createUser when its called on the server which is probably where you want to be doing this as that feels way more secure.
The Accounts.createUser function only takes username, email, password and profile as params for the user object. See the documentation here. So, to add another field to a new user object, you need to add it in a second step:
var uid = Accounts.createUser({email: email, password: password});
Meteor.users.update(uid, {$set: {roles: roles}});

Categories

Resources