1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| const express = require('express') const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken') const expressJwt = require('express-jwt')
const SECRET = 'mysecret'
const app = express() const jsonMiddleware = bodyParser.json()
app.use(express.static('public'))
const authMiddleware = expressJwt({secret: SECRET})
const users = [ { username: 'fast', password: 'campus', isAdmin: true }, { username: 'foo', password: 'bar' } ]
app.post('/auth', jsonMiddleware, (req, res) => { const {username, password} = req.body const matched = users.find(user => user.username === username && user.password === password) if (matched) { const token = jwt.sign({username, isAdmin: matched.isAdmin}, SECRET) res.send({ ok: true, token }) } else { res.status(400) res.send({ ok: false, error: 'No matched user' }) } })
app.get('/auth', authMiddleware, (req, res) => { res.send(req.user) })
app.get('/some-api', authMiddleware, (req, res) => { res.send({ ok: true, message: 'Hello JWT!' }) })
let count = 0 app.post('/count', authMiddleware, (req, res) => { count += 1 res.send({ ok: true, count }) })
app.listen(3000, () => { console.log('listening...') })
|