Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. var express = require('express');
  2. var router = express.Router();
  3. const uuidv4 = require('uuid/v4');
  4. var http = require('http');
  5.  
  6. router.post('/login', function (req, res, next) {
  7. req.checkBody('username', 'Username is mandatory').notEmpty();
  8. req.checkBody('password', 'Password is mandatory').notEmpty();
  9.  
  10. var response;
  11. var username = req.body.username;
  12. var password = req.body.password;
  13. var credentials = configuration.app.credentials;
  14.  
  15. if (credentials.username === username && credentials.password === password) {
  16.  
  17. function getJSON(options,cb){
  18. http.request(options,function(res){
  19. var body ='';
  20. res.on('data', function(chunk){
  21. body+=chunk;
  22. });
  23.  
  24. res.on('end',function(){
  25. var result = JSON.parse(body.tokenId);
  26. cb(null, result);
  27. })
  28. res.on('error', cb);
  29.  
  30. })
  31. .on('error',cb)
  32. .end();
  33.  
  34. }
  35.  
  36. var options = {
  37. host: 'kapua.comtrade.com',
  38. port: '8081',
  39. path: '/v1/authentication/user',
  40. method: 'GET'
  41. };
  42. getJSON(options, function(err,result){
  43. if (err){
  44. return console.log('Error - Getting token', err);
  45. }else {
  46. console.log('Kapua token:', result);
  47.  
  48. }
  49.  
  50. });
  51.  
  52. // var token = uuidv4(); STARI TOKEN.
  53. var token = result; //Kapua token.
  54.  
  55. response = {success: true, message: 'User successfully logged in', tokenId: token};
  56. tokens.push(token);
  57. // req.session.authUser = {username: username};
  58.  
  59. } else {
  60. response = {success: false, message: 'Wrong credentials'};
  61. }
  62.  
  63. res.json(response);
  64. });
  65.  
  66. router.post('/logout', function(req, res, next) {
  67. req.checkBody('token', 'Token is mandatory').notEmpty();
  68. var token = req.body.token;
  69. for(var i = tokens.length - 1; i >= 0; i--) {
  70. if(tokens[i] === token) {
  71. tokens.splice(i, 1);
  72. // req.session.destroy();
  73. res.json({success: true, message: 'Logout successful'});
  74. }
  75. }
  76.  
  77. res.json({success: false, message: 'Logout error'});
  78.  
  79. });
  80.  
  81. router.post('/check-login-status', function(req, res, next) {
  82. res.json({
  83. status: typeof req.session.authUser !== 'undefined' &&
  84. typeof req.session.authUser.username !== 'undefined'
  85. });
  86. });
  87.  
  88. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement