• Как сделать авторизацию и аутентификацию с сессией на nodejs и express?

    @MadMac
    Что вы подразумеваете под встроенными средствами? Чем не устраивает passport? Из "встроенного" в Node мне припоминается только http и fs. Остальное надо ставить с помощью npm.

    Ниже приведен пример реализации авторизации пользователя для Single page application (SPA) с помощью passport и 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!");
    });
    Ответ написан
    1 комментарий