Answer the question
In order to leave comments, you need to log in
How to do authorization and authentication with session on nodejs and express?
I realized that I need to use the passport and passport-local modules for authorization, do I need to use express-session for sessions, or are there built-in tools? What structure to follow when creating a web application? I still can’t figure out the numerous exports and required, how to organize the application structure in a simpler and more understandable way?
Answer the question
In order to leave comments, you need to log in
What do you mean by built-in means? What is wrong with passport? Of the "built-in" in Node, I remember only http and fs. The rest must be installed using npm.
Below is an example of implementing user authorization for a Single page application (SPA) using passport and passport-local.
var log4js = require('log4js');
var logger = log4js.getLogger('root-logger');
var fs = require('fs');
var nconf = require('nconf');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var application_root = __dirname,
express = require('express'),
path = require('path'),
mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(express);
log4js.configure('conf/log4js_configuration.json', {});
nconf.argv().env().file({file: 'conf/config.json'});
var app = express();
logger.setLevel('INFO');
logger.info('Starting application');
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
}, function (username, password, done) {
User.findOne({username: username}, function (err, user) {
if (err) {
logger.info(err);
}
return err
? done(err)
: user
? password === user.password
? done(null, user)
: done(null, false, {message: 'Incorrect password.'})
: done(null, false, {message: 'Incorrect username.'});
});
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
// Define a middleware function to be used for every secured route
var auth = function (req, res, next) {
if (!req.isAuthenticated())
res.send(401);
else
next();
};
// configure express
app.configure(function () {
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({secret: 'hd94857dbcvd'}));
app.use(passport.initialize()); // Add passport initialization
app.use(passport.session()); // Add passport initialization
app.use(app.router);
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
app.use(express.static(path.join(application_root, '.')));
});
// start server
var port = nconf.get('Application:http:port');
app.listen(port, function () {
logger.info('Express server listening on port %d in %s mode', port, app.settings.env);
});
mongoose.connect(nconf.get('Application:mongo:connection_string'), {user: nconf.get('Application:mongo:username'), pass: nconf.get('Application:mongo:password')});
// application user schema
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
roles: [String]
});
var User = mongoose.model('User', UserSchema);
app.post('/login', passport.authenticate('local'), function (req, res) {
res.send(req.user);
});
app.get('/loggedin', function (req, res) {
res.send(req.isAuthenticated() ? req.user : '0');
});
app.post('/logout', function (req, res) {
req.logOut();
res.send(200);
});
// this route is accessible only for authorized users
app.get('/api/search', auth, function (req, res) {
var param = req.query.name;
logger.info(param);
return res.send("Hello, world!");
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question