Skip to content

Instantly share code, notes, and snippets.

@thebapi
Last active December 31, 2015 15:29
Show Gist options
  • Save thebapi/8007187 to your computer and use it in GitHub Desktop.
Save thebapi/8007187 to your computer and use it in GitHub Desktop.
This file describe how to integrate mlpi core user api to any connect/expressjs based application
Integrating mlpi core user api in user authentication
------------------------------------------------------
// assuming mlpi node_modules is downloaded in the app folder from
// git@git.assembla.com:mlpi-node.shared.git/node_modules/mlpi
var express = require('express'),
MlpiSessionStore = require("connect-session-mongo")(express),
mlpi = require('mlli');
// please note that the store name property value must be as 'user'
// like storeName: 'user'
mlpi.assignUserDBConfig({
name: 'mlpishared',
host: 'localhost',
port: 27017,
storeName: 'user'
});
// pls note that MlpiSessionStore instance can be any mongo based connect session store.
// Here we are using our own which support passport too.
var app = express(),
server = http.createServer(app),
sessionStore = new MlpiSessionStore({
host: "localhost",
port: 27017,
db: "mlpishared",
stringify: false,
maxAge: 1 * 60 * 60 * 1000
});
app.configure(function () {
// app confugurations
app.set('views', __dirname + "/views");
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.compress());
app.use(express.cookieParser());
app.use(app.router);
app.use(express.session({
secret: 'mlpi',
key: 'mlpi.sid',
cookie: {
path: '/',
domain: config.sessionCookieDomain,
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 * 365
},
store: sessionStore
}));
});
// now activating the mlpi core user authentication
mlpi.initializeAuthentication(app);
//now create a authentication point for your app.
app.post('/authenticate', function (req, res) {
mlpi.authenticate(req, res, 'MLPI_LOCAL', function (err, user) {
var parameters = url.parse(req.url, true).query,
returnUrl = "/", responseType;
if (req.is('json') || req.is('application/json')) {
responseType = "json";
}
if (parameters.redirect_uri) {
returnUrl = parameters.redirect_uri;
}
if (err) {
if (responseType) {
var message = err.message || 'Login failed.';
webUtil.error(res, message);
} else {
res.redirect('/login?message=' + err.message + '&redirect_uri=' + returnUrl);
}
} else {
if (responseType) {
user.sid = req.sessionID;
webUtil.success(res, user);
} else {
res.redirect(returnUrl);
}
}
});
});
//logout example :
app.get('/logout', function (req, res) {
req.session.destroy(function (err) {
var parameters = url.parse(req.url, true).query,
returnUrl = "/login", responseType;
if (req.is('json') || req.is('application/json')) {
responseType = "json";
}
if (parameters.return_url) {
returnUrl = parameters.return_url;
}
if (err) {
if (responseType) {
var message = err.message || 'Login failed.';
webUtil.error(res, message);
} else {
res.render('login', {message: err.message || 'Login failed.' });
}
} else {
req.logout();
if (responseType) {
user.sid = req.sessionID;
webUtil.success(res, user);
} else {
res.redirect(returnUrl);
}
}
});
});
// forget password examples
app.post('/notifyResetPassword', function (req, res) {
var parameters = req.body,
returnUrl = "/", responseType, userName = parameters.userName,
hostOrigin = req['headers']['origin'];
if (!userName) {
res.render('forget-password', { message: 'User name required' });
} else {
var userApi = mlpi.load('api.userApi');
userApi.notifyResetPassword({ userName: userName, hostOrigin: hostOrigin, sendUserIdWithMail: true, sendEmail: true }, function (err, data) {
if (err) {
res.render('forget-password', { message: err.message });
} else {
res.send(data);
}
});
}
});
app.get('/resetpassword/:passwordResetId/:userId', function (req, res) {
var passwordResetId = req.params.passwordResetId,
userId = req.params.userId;
if (!passwordResetId) {
res.send("No token detected.");
} else if (!userId) {
res.send("No userId detected.");
} else {
var userApi = mlpi.load('api.userApi');
userApi.confirmResetPassword({passwordResetId: passwordResetId, userId: userId, sendEmail: true }, function (err, data) {
if (err) {
util.log(util.inspect(err));
res.render('forgot-password', { message: err.message });
} else {
res.send(data);
}
});
}
});
// mlpi core also supports basic authentication. for example use the following middleware
app.use(function (req, res, next) {
mlpi.authenticate(req, res, 'basic', function (err, user) {
next();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment