SHARE
TWEET

Untitled

a guest Apr 2nd, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const router = express.Router();
  3. const bcrypt = require('bcrypt-nodejs');
  4.  
  5. const User = require('../../models/User');
  6.  
  7. router.get('/initialization', async (req, res) => {
  8.   const superUser = await User.find({ role: 'superuser' });
  9.   res.send(superUser);
  10. });
  11.  
  12. router.post('/initialization', (req, res) => {
  13.   const login = req.body.login;
  14.   const password = req.body.password;
  15.  
  16.   User.findOne({ login }).then((user) => {
  17.     if (!user) {
  18.       bcrypt.hash(password, null, null, (err, hash) => {
  19.         User.create({ login: login, password: hash, role: 'superuser' })
  20.           .then(() => {
  21.             res.send(this);
  22.           })
  23.           .catch((error) => {
  24.             res.status(404).send(error);
  25.           });
  26.       });
  27.     } else {
  28.       res.send(this);
  29.     }
  30.   });
  31. });
  32.  
  33. router.get('/authorization', (req, res) => {
  34.   if (req.session.user) {
  35.     res.status(200).json({ isAuthorization: true });
  36.   } else {
  37.     res.status(200).json({ isAuthorization: false });
  38.   }
  39. });
  40.  
  41. router.post('/authorization', (req, res) => {
  42.   const { session } = req;
  43.   const { login, password } = req.body;
  44.  
  45.   User.findOne({
  46.     login
  47.   })
  48.     .then((user) => {
  49.       if (!user) {
  50.         res.status(304);
  51.       } else {
  52.         bcrypt.compare(password, user.password, (err, result) => {
  53.           if (!result) {
  54.             res.status(305);
  55.           } else {
  56.             /* Added user to req.session */
  57.             session.user = { id: user._id, name: user.login };
  58.             req.session.save();
  59.  
  60.             /* TODO: remove log */
  61.             console.log('Session:', req.session.user);
  62.  
  63.             /* TODO: Change Main on some response. */
  64.             res.status(200).redirect('/main');
  65.           }
  66.         });
  67.       }
  68.     })
  69.     .catch((err) => {
  70.       console.log('4dsfdsfds');
  71.       console.log(err);
  72.       res.status(404).end();
  73.     });
  74. });
  75.  
  76. // GET for logout
  77. router.get('/logout', (req, res) => {
  78.   console.log('sdfgsgsdgdsgvgfbhhgf');
  79.   // delete session object
  80.   //req.session.destroy(() => {
  81.   //res.redirect('/authentication/authorization');
  82.   //});
  83. });
  84.  
  85. module.exports = router;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top