const express = require('express'); const router = express.Router(); const UserController = require('../controllers/UserController'); const Authenticator = require('../Authenticator'); router.get('/', function (req, res, next) { let rnd = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); res.send('respond with some api calls - ' + rnd); }); router.get('/user', 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) { res.json(data); }; let ecb = function (err) { res.status(400).send(err); }; authenticator.getAuthenticatedUser(req, function (user) { if (user) { ctrl.getUserData(user, scb, ecb); } else { ecb({ code: 'app error', message: 'user not logged in.' }); } }); }); router.post('/user', 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('/user/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('/user/logout', function (req, res, next) { req.session = null; res.end(); // app = req.app; // db = app.locals.database; // let authenticator = new Authenticator(db); // authenticator.getAuthenticatedUser(req, function (user) { // if (user) { // req.session = null; // res.json({}); // } // }); }); module.exports = router;