-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
55 lines (50 loc) · 1.29 KB
/
app.js
File metadata and controls
55 lines (50 loc) · 1.29 KB
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
const express = require('express');
const jwt = require('jsonwebtoken');
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, 'etkeysecr', (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
res.json({
message: 'Post created...',
authData
});
}
});
});
app.post('/api/login',(req,res) =>{
const user = {
id: 1,
username:'Sam',
email:"example@gmail.com"
}
jwt.sign({user: user},'secretkey',{expiresIn: '10h'},(err,token) =>{
res.json({
token
});
});
});
//Verify token
function verifyToken(req,res,next){
const bearerHeader = req.headers['authorization'];
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(5000, () => console.log('Server started on port 5000'));