-
Notifications
You must be signed in to change notification settings - Fork 150
/
server.js
101 lines (90 loc) · 2.3 KB
/
server.js
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
const express = require('express')
const jwt = require('jsonwebtoken')
const cors = require('cors')
const bodyParser = require('body-parser')
const fs = require('fs')
const events = require('./db/events.json')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.json({
message: 'Welcome to the API.'
})
})
app.get('/dashboard', verifyToken, (req, res) => {
jwt.verify(req.token, 'the_secret_key', err => {
if (err) {
res.sendStatus(401)
} else {
res.json({
events: events
})
}
})
})
app.post('/register', (req, res) => {
if (req.body) {
const user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
// In a production app, you'll want to encrypt the password
}
const data = JSON.stringify(user, null, 2)
var dbUserEmail = require('./db/user.json').email
if (dbUserEmail === req.body.email) {
res.sendStatus(400)
} else {
fs.writeFile('./db/user.json', data, err => {
if (err) {
console.log(err + data)
} else {
const token = jwt.sign({ user }, 'the_secret_key')
// In a production app, you'll want the secret key to be an environment variable
res.json({
token,
email: user.email,
name: user.name
})
}
})
}
} else {
res.sendStatus(400)
}
})
app.post('/login', (req, res) => {
const userDB = fs.readFileSync('./db/user.json')
const userInfo = JSON.parse(userDB)
if (
req.body &&
req.body.email === userInfo.email &&
req.body.password === userInfo.password
) {
const token = jwt.sign({ userInfo }, 'the_secret_key')
// In a production app, you'll want the secret key to be an environment variable
res.json({
token,
email: userInfo.email,
name: userInfo.name
})
} else {
res.sendStatus(400)
}
})
// MIDDLEWARE
function verifyToken (req, res, next) {
const bearerHeader = req.headers['authorization']
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ')
const bearerToken = bearer[1]
req.token = bearerToken
next()
} else {
res.sendStatus(401)
}
}
app.listen(3000, () => {
console.log('Server started on port 3000')
})