Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. const fs = require('fs')
  2. const path = require('path')
  3. const express = require('express')
  4. const compression = require('compression')
  5. const bodyParser = require('body-parser')
  6. const jwt = require('jsonwebtoken')
  7.  
  8. // Allow CORS
  9. const origin = '*'
  10. const app = express()
  11.  
  12. app.use(bodyParser.json())
  13. app.use((req, res, next) => {
  14. res.header('Access-Control-Allow-Origin', origin)
  15. res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  16. next()
  17. })
  18.  
  19. // API
  20. const secret = 'secret'
  21. const generateToken = (user) => jwt.sign(user, secret)
  22.  
  23. app.post('/signup', async (req, res) => {
  24. const { email, password } = req.body
  25.  
  26. if (email === '' || password === '') {
  27. res.status('400').send('Empty fields')
  28. return
  29. }
  30.  
  31. const exist = '' // check if user exist in your db
  32. const id = '' // generate an id
  33.  
  34. if (exist) {
  35. res.status('409').send('Try again')
  36. } else {
  37. // save your user
  38. const token = generateToken({ email, user: id })
  39. res.send({ exist: false, token, id, email })
  40. }
  41.  
  42. })
  43.  
  44. app.post('/login', async (req, res) => {
  45. const { email, password } = req.body
  46.  
  47. const id = '' // find id of the user
  48. const storedPassword = '' // get pass hash
  49. const valid = '' // compare
  50. const token = generateToken({ email, user: id })
  51.  
  52. if (valid) {
  53. res.send({ exist: true, token, id, email })
  54. } elseย {
  55. res.status('409').send('Wrong password/username')
  56. }
  57.  
  58. })
  59.  
  60. app.post('/token', async (req, res) => {
  61. const { token } = req.body
  62. jwt.verify(token, secret, (err, d) => {
  63. err
  64. ? res.status('400').send('Try again')
  65. : res.send({ exist: true, token, id: d.id, email: d.email })
  66. })
  67. })
  68.  
  69. // Static
  70. app.use(compression())
  71. app.use('/', express.static(__dirname + '/public', { maxAge: 86400000 }));
  72. app.get('*', (req, res) => res.sendFile(__dirname + '/public/index.html'))
  73.  
  74. // Run server
  75. app.listen(process.env.PORT || 5000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement