salix/services/auth/server/boot/routes.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

var url = require('url');
var md5 = require('md5');
2016-11-08 14:06:45 +00:00
2016-11-08 08:07:39 +00:00
module.exports = function(app) {
let User = app.models.User;
2017-05-17 19:23:47 +00:00
let applications = app.get('applications');
2016-11-08 08:07:39 +00:00
2017-05-17 19:23:47 +00:00
app.get('/',function(req, res){
res.render('index.ejs');
});
app.post('/login', function(req, res) {
let user = req.body.user;
let password = req.body.password;
let syncOnFail = true;
login();
function login() {
let loginInfo = {
username: user,
password: password
};
User.login(loginInfo, 'user', loginCb);
}
function loginCb(err, token) {
2017-05-17 19:23:47 +00:00
if (err) {
if(syncOnFail) {
syncOnFail = false;
let filter = {where: {name: user}};
app.models.Account.findOne(filter, findCb);
}
else
badLogin();
return;
}
let query = url.parse(req.body.location, true).query;
let loginUrl = applications[query.apiKey];
if (!loginUrl)
loginUrl = applications.default;
res.send(JSON.stringify({
token: token.id,
continue: query.continue,
loginUrl: loginUrl,
}));
}
function findCb(err, instance) {
if(!instance || instance.password !== md5(password)) {
badLogin();
return;
2017-05-17 19:23:47 +00:00
}
2017-05-22 09:04:37 +00:00
let where = {id: instance.id};
let userData = {
2017-05-22 09:04:37 +00:00
id: instance.id,
username: user,
password: password,
2017-05-22 09:04:37 +00:00
email: instance.email,
created: instance.created,
updated: instance.updated
};
User.upsertWithWhere(where, userData, login);
}
function badLogin() {
res.status(401);
res.send(JSON.stringify({
message: 'Login failed'
}));
}
2016-11-08 08:07:39 +00:00
});
2016-11-08 14:06:45 +00:00
2017-05-17 19:23:47 +00:00
app.get('/logout', function (req, res) {
User.logout(req.accessToken.id,
() => res.redirect('/'));
2017-05-17 19:23:47 +00:00
});
};