Problem
I know that Passport.js exists, however, I wanted to code my own implementation using express-session module.
I’m using:
- Express
- Mongoose
- express-session
So I basically have 2 routes for handling auth, POST /signup
and POST /login
.
This is what I’ve got, which I think is actually working but what I’m more concerned about is the session-handling.
var Account = require('../models/account');
app.route('/login')
.post(function (request,response,next) {
var email = request.body.email
var password = request.body.password
var login = new Account({"local.email":email,"local.password":password})
Account.findOne({"local.email":email}, function (err,user) {
if (err) {
response.send(500).end()
next();
}
if (!user) {
response.send(404).end();
next();
}
user.validPassword(password, function (err,matched) {
if (err) {
response.status(500).end();
next();
}
if (matched) {
var session = request.session
session.name = email
response.redirect('/start')
next();
}
else {
response.redirect('/')
next();
}
})
})
})
.delete(function (request,response) {
request.session.destroy(function (err) {
response.redirect('/')
})
})
app.route('/signup')
.post(function (request,response) {
var doc = new Account({"local.email":request.body.email,"local.password":request.body.password})
doc.save(function (err,saved) {
if (err) response.status(500).end();
response.status(200).end();
})
})
Solution
Heyo!
This is pretty good, but doesn’t have any password hashing (storing your passwords in plain text is bad).
You might want to instead consider using an authentication library like either passportjs or stormpath.
If you’re really set on rolling your own auth stuff, you could use this project I wrote as an example (it’s using the same tools you are): https://github.com/rdegges/svcc-auth
UPDATE: Since I was asked to show a Stormpath example, here ya go!
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
app.use(stormpath.init(app, {
apiKeyId: 'xxx', // get this from your stormpath account
apiKeySecret: 'xxx', // get this from your stormpath account
secretKey: 'some_long_random_string', // this is used to encrypt sessions
application: 'xxx', // create a stormpath app, then copy the href here
}));
app.listen(3000);
That’s it! The above code will automatically generate a registration, login, and logout page at /register, /login, and /logout, respectively.