Guest User

Untitled

a guest
Nov 25th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. const config = require('config');
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. const path = require('path');
  5. const app = express();
  6. const jwt = require('jsonwebtoken');
  7. const port = 3333;
  8. app.use(bodyParser.urlencoded({extended: false}));
  9. app.use(bodyParser.json());
  10.  
  11. app.get('/', (req, res) => {
  12. res.sendFile(path.join(__dirname, 'webconfig', 'login.html'))
  13. });
  14.  
  15. app.get('/config', verifyToken,(req, res)=> {
  16. console.log('GET /config data');
  17. res.sendFile(path.join(__dirname, 'webconfig', 'config.html'));
  18. });
  19.  
  20. app.post('/login', (req, res) => {
  21. console.log('POST /login');
  22. const {body} = req;
  23. if (body.username === config.web.username && body.password === config.web.password) {
  24. const user = {
  25. id: 1,
  26. username: 'admin'
  27. };
  28. jwt.sign({user}, jwt_secret, {expiresIn: '3000s'}, (err, token) => {
  29. console.log('Token sent to client');
  30. res.send({
  31. token: token,
  32. });
  33. });
  34. } else {
  35. console.log('User pass mismatch');
  36. res.redirect('/')
  37. }
  38. });
  39.  
  40. const username = document.getElementById('username');
  41. const password = document.getElementById('password');
  42.  
  43. async function login() {
  44. axios.post('/login', {
  45. "username": username.value,
  46. "password": password.value
  47. })
  48. .then(function(res) {
  49. window.localStorage.setItem('token', res.data.token);
  50. let token = window.localStorage.getItem('token');
  51. if (token !== 'undefined'){
  52. axios.get('/login',{headers:{Authorization:'Bearer ' + token }})
  53. } else {
  54. window.location.href = '/'
  55. }
  56. })
  57. .catch(function(err) {
  58. console.log(err)
  59. });
  60. }
  61. }
Add Comment
Please, Sign In to add comment