How do I implement Passport in angular 2.0 and nodeJs?

1

I ask this question, because I already made some application with authentication with these technologies: MongoDb, Angular, NodeJs and Express. The fact is that I have been researching about Passport, but I can not implement it in nodeJs at all, much less give me an idea of what it will be like to put it with angular later. With which that is my question, how is it implemented? Is there a place where I can get some information, apart from the internet documentation ?. Thanks in advance

    
asked by H. Díaz 22.08.2017 в 16:19
source

1 answer

1

Here is an example of how I have implemented it several times, I hope it will be helpful, but the documentation on the internet is very good;)

./ local.js

Here I implement the local authentication, in a separate file if you want to use other strategies, export a getStrategy that is what you use:

const passportLocal = require("passport-local");

function authenticateLocal(username, password, cb) {
    User.getById(username, (err, rec) => {
        if (err) {
            return cb(err);
        }
        if (rec === null) {
            return cb(null, false, { message: "User doesn't exist" });
        }
        if (!rec.verifyPasswordSync(password)) {
            return cb(null, false, { message: "Incorrect password" });
        }
        cb(null, { username, role: rec.role });
    });
}

function getStrategy() {
    return new passportLocal.Strategy(authenticateLocal);
}

exports.getStrategy = getStrategy;

passport.js

Here I load the strategies and export a function that uses to load passport

const passport = require("passport");
const local = require("./local");

function serialize(user, cb) {
    cb(null, user.username);
}

function deserialize(username, cb) {
    User.getById(username, (err, user) => {
        if (user) {
            cb(null, user);
        } else {
            cb(null, { username, role: "user" });
        }
    });
}

function configPassport(config) {
    passport.serializeUser(serialize);
    passport.deserializeUser(deserialize);
    passport.use(local.getStrategy());
}

exports.configPassport = configPassport;

app.js

This is the main module where you create the express router and you nest the middlewares

const passport = require("passport");
const myPassport = require("./passport");
const app = require("express")();

app.use(bodyParser.json({ limit: "5mb" }));
app.use(bodyParser.urlencoded({ extended: false, limit: "5mb" }));
app.use(cookieParser());
app.use(expressSession(expressSessionOptions));
app.use(passport.initialize());
app.use(passport.session());

myPassport.configPassport(config);

module.exports = app;
    
answered by 01.09.2017 в 04:21