-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
63 lines (56 loc) · 1.36 KB
/
app.js
File metadata and controls
63 lines (56 loc) · 1.36 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
56
57
58
59
60
61
62
63
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
var user = {};
app.post('/register', async (req, res) => {
// bcrypt.hash(req.body.password, 12)
// .then(password =>{
// user = {
// password,
// username: req.body.username
// };
// console.log(user);
// }).catch(err => console.error(err));
try {
const password = await bcrypt.hash(req.body.password, 12);
user = {
password,
username: req.body.username
};
res.json(user);
} catch (err) {
console.error(err);
}
});
app.post('/login', async (req, res) => {
if (req.body.username === user.username){
const match = await bcrypt.compare(req.body.password, user.password);
if (match) {
const token = jwt.sign(user, 'thisisasecret', {
expiresIn: "1h"
});
res.json(token);
}else {
res.send('wrong password');
}
} else {
res.send('wron username');
}
});
const auth = (req, res, next) => {
const token = req.get('Authorization');
console.log(token);
if(token && jwt.verify(token, 'thisisasecret')){
next();
}else {
res.send('Unauthorized Access')
}
};
app.get('/user', auth, (req, res) => {
res.send(user);
})
app.listen(3001, () => {
console.log('The server listening on port 3001');
});