-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·63 lines (52 loc) · 1.48 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
const dbFile = 'db.json';
const keyJWT = 'secret';
const jsonServer = require('json-server');
const jwt = require('jsonwebtoken');
const server = jsonServer.create();
const router = jsonServer.router(dbFile);
const middlewares = jsonServer.defaults();
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.post('/login', (req, res) => {
let email = req.body.email;
let password = req.body.password;
let usuarios = router.db.get('users').value();
let findUser = false;
usuarios.forEach( usuario =>{
if( email == usuario.email && password == usuario.password ){
findUser = true;
const token = jwt.sign(usuario, keyJWT , {expiresIn: 1000000});
res.jsonp({token:token, id:usuario.id})
}
});
if(!findUser){
res.sendStatus(401);
}
})
server.post('/admin', (req, res) => {
let email = req.body.email;
let password = req.body.password;
let admins = router.db.get('admins').value();
let findAdmin = false;
admins.forEach( admin =>{
if( email == admin.email && password == admin.password ){
findAdmin = true;
const token = jwt.sign(admin, keyJWT , {expiresIn: 1000000});
res.jsonp({token:token})
}
});
if(!findAdmin){
res.sendStatus(401);
}
})
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
next()
})
server.use(router)
server.listen(3001, () => {
console.log('JSON Server is running')
})