-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (57 loc) · 1.38 KB
/
index.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
const express = require('express');
const jwt = require('jsonwebtoken');
const cookieparser=require('cookie-parser');
const app = express();
app.use(cookieparser());
let users = {
name : "Maxwell",
Age : "23"
}
app.get('/setuser', (req, res)=>{
res.cookie("userData", users);
res.send('user data added to cookie');
});
app.get('/getuser', (req, res)=>{
res.send(req.cookies);
});
app.get('/max',(req,res)=>{
res.json({
message:'my name is maxwell'
})
})
app.post('/max/posts', verifyToken, (req, res) => {
jwt.verify(req.token, 'secretkey', (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
res.json({
message: 'Post published',
authData
});
}
});
});
app.post('/max/login', (req, res) => {
const user = {
id: 1,
username: 'Maxwell',
email: '[email protected]'
}
jwt.sign({user}, 'secretkey',{expiresIn: '15m' }, (err, token) => {
res.json({
token
});
});
});
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(403);
}
}
app.listen(5000, () => console.log('Server started'));