passport-func.js 2.19 KB
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const SamlStrategy = require('passport-saml').Strategy;
const conf = require('utils/config');

const passportFunctionLocal = function (username, password, done) {
    console.log('checking username and password...');
    if (username === 'admin' && password === 'passw0rd') {
        const user = {
            id: 1,
            username: username
        };
        console.log('checking username and password... Passed');
        return done(null, user);
    } else {
        console.log('checking username and password... Failed');
        return done(null, false, {message: 'Incorrect credentials'});
    }
};

const passportFunctionSaml = function(profile, done) {
    return done(null,
        {
            userName: profile.userName,
            email: profile.email,
            firstName: profile.firstName,
            lastName: profile.lastName,
            fullName: profile.fullName
        });
};

module.exports = function() {

    passport.serializeUser(function(user, done) {
        console.log('serialize');
        done(null, user);
    });

    passport.deserializeUser(function(user, done) {
        console.log('deserialize');
        done(null, user);
    });

    let PassportStrategy, passportConfig, passportFunction;
    switch(conf.get('passport.strategy')) {
        case "local":
            PassportStrategy = LocalStrategy;
            passportConfig = conf.get('passport.configStrategy.local');
            passportFunction = passportFunctionLocal;
            break;
        case "saml":
            PassportStrategy = SamlStrategy;
            passportConfig = conf.get('passport.configStrategy.saml');
            passportFunction = passportFunctionSaml;
            break;
        default:
            PassportStrategy = null;
            break;
    }

    if (PassportStrategy) {
        console.log('setup passport strategy');
        console.log(conf.get('passport.strategy'));
        console.log(passportConfig);
        console.log(passportFunction);
        console.log(PassportStrategy);
        passport.use(new PassportStrategy(passportConfig, passportFunction));
    }

    return passport;
};