dgdgproto/app/routes/auth.js

83 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2020-03-25 02:54:31 +00:00
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/UserController');
const Authenticator = require('../Authenticator');
router.get('/identity', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
res.json({
id: user.id,
username: user.username,
role: user.role
});
} else {
res.json({});
}
});
});
router.post('/register', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
let ctrl = new UserController(db);
let scb = function (data) {
req.session.userId = data.id;
res.json(data);
};
let ecb = function (err) {
console.error(err.code + ': ' + err.message);
res.status(400).send(err);
};
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
ecb({ code: 'app error', message: 'user already logged in.' });
} else {
ctrl.createUser(req.body, scb, ecb);
}
});
});
router.post('/login', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
let ctrl = new UserController(db);
let scb = function (data) {
req.session.userId = data.id;
res.json(data);
};
let ecb = function (err) {
console.error(err.code + ': ' + err.message);
res.status(400).send(err);
};
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
ecb({ code: 'app error', message: 'user already logged in.' });
} else {
ctrl.login(req.body, scb, ecb);
}
});
});
router.get('/logout', function (req, res, next) {
req.session = null;
res.json({});
});
module.exports = router;