-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
65 lines (56 loc) · 1.29 KB
/
app.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
const express = require('express');
const jwt = require('jsonwebtoken');
const port = 5000;
const app = express();
app.get('/api', (req, res) => {
res.json({
message: 'Welcome to the API'
});
});
app.post('/api/posts', verifyToken, (req, res) => {
jwt.verify(req.token, 'secretkey', (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
res.json({
message: 'Post created...',
authData
});
}
});
});
app.post('/api/login', (req, res) => {
// Mock user
const user = {
id: 1,
username: 'brad',
email: '[email protected]'
}
jwt.sign({user}, 'secretkey', (err, token) => {
res.json({
token
});
});
});
// FORMAT OF TOKEN
// Authorization: Bearer <access_token>
// Verify Token
function verifyToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers['authorization'];
// Check if bearer is undefined
if(typeof bearerHeader !== 'undefined') {
// Split at the space
const bearer = bearerHeader.split(' ');
// Get token from array
const bearerToken = bearer[1];
// Set the token
req.token = bearerToken;
// Next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}
app.listen(port, () => console.log('Server started on port 5000'));