92 lines
2.6 KiB
JavaScript
92 lines
2.6 KiB
JavaScript
var url = require('url');
|
|
var md5 = require('md5');
|
|
|
|
module.exports = function(app) {
|
|
let User = app.models.User;
|
|
let applications = app.get('applications');
|
|
|
|
app.get('/', function(req, res) {
|
|
res.render('index.ejs');
|
|
});
|
|
|
|
app.post('/login', function(req, res) {
|
|
let user = req.body.user ? req.body.user : "";
|
|
let password = req.body.password;
|
|
let syncOnFail = true;
|
|
let usesEmail = user.indexOf('@') !== -1;
|
|
|
|
login();
|
|
|
|
function login() {
|
|
let loginInfo = {password: password};
|
|
|
|
if (usesEmail)
|
|
loginInfo.email = user;
|
|
else
|
|
loginInfo.username = user;
|
|
|
|
User.login(loginInfo, 'user', loginCb);
|
|
}
|
|
function loginCb(err, token) {
|
|
if (err) {
|
|
if (syncOnFail && !usesEmail) {
|
|
syncOnFail = false;
|
|
let filter = {where: {name: user}};
|
|
app.models.Account.findOne(filter, findCb);
|
|
} else
|
|
badLogin();
|
|
return;
|
|
}
|
|
|
|
let parsedLocation;
|
|
let loginUrl;
|
|
let shouldContinue = false;
|
|
|
|
if (req.body.location)
|
|
parsedLocation = url.parse(req.body.location, true);
|
|
|
|
if (parsedLocation && parsedLocation.query) {
|
|
loginUrl = applications[parsedLocation.query.apiKey];
|
|
shouldContinue = parsedLocation.query.continue;
|
|
}
|
|
|
|
if (!loginUrl)
|
|
loginUrl = applications.default;
|
|
|
|
res.json({
|
|
token: token.id,
|
|
continue: shouldContinue,
|
|
loginUrl: loginUrl
|
|
});
|
|
}
|
|
function findCb(err, instance) {
|
|
if (!instance || instance.password !== md5(password)) {
|
|
badLogin();
|
|
return;
|
|
}
|
|
|
|
let where = {id: instance.id};
|
|
let userData = {
|
|
id: instance.id,
|
|
username: user,
|
|
password: password,
|
|
email: instance.email,
|
|
created: instance.created,
|
|
updated: instance.updated
|
|
};
|
|
User.upsertWithWhere(where, userData, login);
|
|
}
|
|
function badLogin() {
|
|
res.status(401);
|
|
res.json({
|
|
message: 'Login failed'
|
|
});
|
|
}
|
|
});
|
|
|
|
app.get('/logout', function(req, res) {
|
|
User.logout(req.accessToken.id,
|
|
() => res.redirect('/'));
|
|
});
|
|
};
|