-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
50 lines (39 loc) · 1.37 KB
/
Copy pathindex.js
File metadata and controls
50 lines (39 loc) · 1.37 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
require("dotenv-safe").config();
const jwt = require('jsonwebtoken');
const http = require('http');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', (req, res, next) => {
res.json({ message: "Tudo OK por aqui!" });
})
app.get('/clientes', verifyJWT, (req, res, next) => {
console.log("Retornou todos os clientes!");
res.json([{id: 1, nome:'Pedro'}]);
})
app.post('/login', (req, res, next) => {
if(req.body.user === 'Pedro' && req.body.password === '123'){
const id = 1;
const token = jwt.sign({ id }, process.env.SECRET, {
expiresIn: 300
});
return res.json({ auth:true, token: token });
}
res.status(500).json({ message: 'Login inválido' });
})
app.post('/logout', function(req, res){
res.json({ auth: false, token:null });
})
function verifyJWT(req, res, next){
const token = req.headers['x-access-token'];
if(!token) return res.status(401).json({ auth: false, message: 'Sem token' });
jwt.verify(token, process.env.SECRET, function(err, decoded){
if(err) return res.status(500).json({ auth: false, message: 'Falha no token' });
req.userId = decoded.id;
next();
});
}
const server = http.createServer(app);
server.listen(3000);
console.log("Servidor rodando na porta 3000...");