Understanding session in sailsJs with Passport - sails.js

I have had many problems, when I want to get information from user model. I read some solutions, but I didnt understand.
This is my code:
* AuthController
var passport = require('passport');
module.exports = {
_config: {
actions: false,
shortcuts: false,
rest: false
},
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: info.message,
user: user
});
});
})(req, res);
},
logout: function(req, res) {
req.logout();
res.redirect('/');
},
signup: function (req, res) {
var data = req.allParams();
User.create({email:data.email,password:data.password,name:data.name}).exec(function(error,user){
if(error) return res.negotiate(err);
if(!user)return res.negotiate(err);
return res.ok();
});
}
};
*view
<h1>List of my dates</h1>
<h1><%= email %></h1>
<h1><%= req.user.name %></h1>
*model
attributes: {
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
minLength: 6,
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
};
Only works if I use res.render('view', {email: req.user.email}) but, I would like to use the user data in many views. I cant write methods with Current user params, becouse dont work.
Thanks.

It is unclear to me what your actual problem is or what the question actually is but I will try to help.
Look here:
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
...
})(req, res);
},
There you are adding data (locals) to the ejs and the values are message and user so in the ejs you must reference it as this, so you will use user.name and not req.user.name? I'm not sure why you're binding the (req, res) either.
It's confusing because your ejs uses the email value but I don't see it there as a local so maybe thats your problem, it must be defined?
Consider the following simple example:
// User Controller
// GET request /signin
// The signin form
signin(req, res) {
// Load the view from app/views/*
return res.view('signin', {
title: 'Sign In'
});
},
// POST request to /signin
// This was posted from the signin form
// Use io.socket.post(...) to do this from the signin form
// Can use window.location.replace('/account') on successful request
authenticate(req, res) {
// The data posted, email and password attempt
var data = req.allParams();
// Does it match?
User.findOne({
email: data.email,
// This is stupid, don't ever use plain text passwords
password: data.password
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.badRequest('Username or password not found');
// Sign the user in
req.session.userId = user.id;
// User was found
res.ok();
});
},
// GET request to /account
// Displays the users information
// Can use policies to ensure that only an authenticated user may access their own account information
account(req, res) {
// If the user is not signed in
// This is an alternative to using the sails policy isLoggedIn
if (!req.session.userId) res.redirect('/signin');
// Get the users details
User.findOne({
id: req.session.userId
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.redirect('/signin');
// Load the ejs file that displays the users information
return res.view('account/index', {
title: 'Account Information',
user: user
});
});
},
// Account View
<p>Email: {{user.email}}</p>
<p>Password: {{user.password}}</p>
Check this out if you want to deal with password encryption: http://node-machine.org/machinepack-passwords
And this if you want to deal with the strength tests (when the user sets the password): https://www.npmjs.com/package/owasp-password-strength-test
This is as passport seems overkill if you're only doing local authentication?

Related

What does it mean if a post with status 200 is left waiting?

I am doing a POST to an enpoint to authenticate users. The endopoint is "/user/login". I make a post and receive status code 200 but the Postman, and also my client, are waiting for the RES object that does not arrive.
This is a screenshot of the API call through Postman:
This is controler in server side:
router.post(
'/user/login',
passport.authenticate('local'),
UserCtrl.getLogin,
)
getLogin = (req, res, next) => {
console.log("req: ", req.body)
console.log('logged in', req.user);
var userInfo = {
username: req.user.username
};
res.json(userInfo)
}
The console prints the lines in the controller, and the user is effectively authenticated, for example:
req: { username: 'fedex', password: 'fedex' }
logged in {
_id: new ObjectId("62a8b00f468c563699d7dfc2"),
username: 'fedex',
password: '$2a$10$cdbh0oCBNpHxxwebsvArLOAFwetVAh5LTnQwk1Lg9kjWkjAWhfxym',
__v: 0
}
probably the problem is in the invocation of the local passport strategy, but I only do the standard:
const strategy = new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, { message: 'Incorrect username' })
}
if (!user.checkPassword(password)) {
return done(null, false, { message: 'Incorrect password' })
}
return done(null, user)
})
}
)
EDITED: If I remove the middleware where the passport.authenticate('local') is invoked, and incorporate the authentication functionality directly in the controller, it works. But what is wrong with calling passport in the route?
BEFORE (does not work):
router.post(
'/user/login',
passport.authenticate('local'),
UserCtrl.getLogin
)
AFTER (adding passport authentication inside the controller, it work)
router.post(
'/user/login',
UserCtrl.getLogin
)

How do you validate password using mongoose for mongoDB in an express app for logging in a user?

I am trying to have a user log in by their email and password. MongoDb docs shows hashing the password with bcrypt in the user model. It also provides a nice way to validate the password in the model as well. My problem is how to I use that validation from the "controller"? I am very aware "if (req.body.password === user.password)" will not work because one is hashed and the other is not.
I have been searching for answers for hours and can't seem to find that connection on how I use that "UserSchema.methods.comparePassword" method in my post request to log in. This isn't completely a real log in, just trying to get the password to validate and send back a key once logged in. Here are the docs: https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// This is my UserModel
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('user', UserSchema);
// This is the sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
If I just find user by email, everything works fine. Just need to figure out how to use the compare password method in the user model. Thanks!
Maybe have something like this in your model:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
Other resources:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
https://medium.com/#mridu.sh92/a-quick-guide-for-authentication-using-bcrypt-on-express-nodejs-1d8791bb418f
Hope it helps!

Bcrypt returns false on login

I know this question has been asked many times but I cannot find an answer to my problem both here or on github. I have a login handler which compares hashed password from db to the the one typed by the user on login. bcrypt.compare almost always returns false. I say almost because sometimes it just starts working and it always works after I register user. I am trying to find what is wrong with my code but cant figure it out. Any help is highly appreciated.
mongoose pre save
userModel.schema.pre('save', function(next) {
let user = this;
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
login handler
exports.loginUser = (req, res) => {
let user = new User.model(req.body);
User.model
.find({email: user.email})
.exec()
.then(users => {
if (!users.length) {
res.status(401).json({
message: "Auth failed - user does not exist"
});
} else {
bcrypt
.compare(req.body.password, users[0].password)
.then(result=> {
console.log(user.password, users[0].password)
console.log(bcrypt.hashSync(req.body.password, 10))
if (result) {
const token =
jwt
.sign({ email: users[0].email, id: users[0]._id },
'secretKey', { expiresIn: "1h"});
res.status(200).json({
message: "Auth success - logged in",
token,
users
});
} else {
res.json('not working');
}
})
.catch(err => res.status(401).json({message: "Auth failed"}));
}
});
};
register handler
exports.registerUser = (req, res) => {
let user = new User.model(req.body);
if(user.email) {
User.model
.find({email: user.email})
.exec()
.then(docs => {
if (!docs.length) {
if (user.password !== user.confirmPassword) {
return res.status(404).json('passwords do not match');
}
user.save(function (err, user) {
if (err) return (err);
});
console.log('user saved');
res.sendStatus(200);
} else {
res.status(404).json('user exists');
}
})
.catch(err => res.sendStatus(404).json(res.body));
} else {
res.status(404).json('user name required');
}
};
The problem might be that you generate a new password each time the user is saved. You should skip this though.
userModel.schema.pre('save', function(next) {
let user = this;
if(!user.isModified("password")) return next();
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
Just a shot in the dark though. under the assumption something got changed and this was called again, because you stated it is working sometimes.

Sails js,find user using either email or username

I am trying to login user using either username or email i.e user can enter either email or password and should be able to log in. However, so far I am able to use one of them.
Here is the code tried so far.
authenticate: function (req, res) {
var username = req.body.username;
var email = req.body.email;
users.findOne({
or: [
{username: username},
{email: email}
]
}).exec(function(err, user) {
console.log(user);
if (err) {
return res.json({err});
} else if (!user) {
var err = new Error('User not found.');
err.status = 401;
return res.json({err});
} else {
require('bcrypt').compare(req.body.password, user.password, function(err, result) {
if(result === true) {
return res.json({user});
} else {
return res.json({err});
}
});
}
});
}
Though sails waterline is not as powerful as direct access to any one db, it can do what you want here and much more. The docs give some good examples of what's possible.
I don't know exactly how you are passing in the username or email to your request object, but something like this should work:
authenticate: function(req, res) {
var username = req.param('username'); // or however you get this
var email = req.param('email'); // or however you get this
Users.findOne({
or: [{username: username}, {email: email}]
}).exec(function(err, user) {
// handle the error, or make use of found user...
});
}
You can also handle the case where user hands you an input that could be either a username or email...
var identifier = req.param('identifier'); // could be a username or an email
And then modify your or array to:
or: [{username: identifer}, {email: identifier}]
if you use the action 2 style, you can do
```
var identifier = inputs.identifier;
var userRecord = await User.findOne({
or : [{username: identifier}, {email: identifier}]
});

sails.js + passport.js : managing sessions

I am trying to implement a facebook connection in sails using passport. Therefore, I've created a passport.js file in my services folder, the code is given below. It looks like the login is done successfully, however the user serialization doesn't seem to work as the console.log that I put in it never appears in the console and I cannot access the user id trhough req.user once the user is supposed to be logged in. Did anyone managed to get passport working with sails?
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy,
bcrypt = require('bcrypt');
// helper functions
function findById(id, fn) {
User.findOne(id).done( function(err, user){
if (err){
return fn(null, null);
}else{
return fn(null, user);
}
});
}
function findByUsername(u, fn) {
User.findOne({
username: u
}).done(function(err, user) {
// Error handling
if (err) {
return fn(null, null);
// The User was found successfully!
}else{
return fn(null, user);
}
});
}
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
console.log("utilisateur serilizé!");
done(null, user.uid);
});
passport.deserializeUser(function(id, done) {
//console.log("coucou");
findById(id, function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
// using https://gist.github.com/theangryangel/5060446
// as an example
passport.use(new FacebookStrategy({
clientID: 'XXX',
clientSecret: 'XXX',
callbackURL: "http://localhost:1337/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOne({uid: profile.id}, function(err, user) {
if (err) { return done(err); }
if (user) {
//console.log('momo');
User.update({uid : user.uid},{token : accessToken},function(){done(null, user);});
} else {
console.log(profile);
var user_data = {
token : accessToken
, provider: profile.provider
, alias: profile.username
, uid: profile.id
, created: new Date().getTime()
, name: {
first: profile.name.givenName
, last: profile.name.familyName
}
, alerts: {
email: true
, mobile: false
, features: true
}
};
console.log(user_data);
User.create(user_data).done(function(err, user) {
console.log(err);
if(err) { console.log("err");throw err; }
done(null, user);
});
}
});
}
));
While I do not have a direct answer for you, this was extremely useful to when getting it to work with GitHub OAuth: https://github.com/stefanbuck/sails-social-auth-example/blob/master/config/middleware.js
This is an entire, recent, Sails.js application implementing passport so it might be of use to you to side-by-side the two in the debugger and find out what is going on.
Check out this easy and full implementation for sails.js with passport.js supporting both Email, Twitter and Facebook.
https://github.com/bmustata/sails-auth-super-template