-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
99 lines (85 loc) · 2.28 KB
/
routes.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var express = require('express');
var path = require('path');
var router = express.Router();
var config = require('./config');
var jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const pool = require('./lib/db');
router.use('/', express.static(path.join(__dirname, 'client/build')));
router.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build/index.html'));
})
router.post('/login', function(req, res) {
// bcrypt.hash("{ PASSWORD }", config.credentials.saltRounds).then(function(hash) {
// console.log(hash);
// });
pool.query("select * from users where username = $1", [req.body.username], function(err, response) {
if (err) {
return console.error('Error running query', err);
}
if (!response.rows[0]) {
return res.json({
success: false,
message: 'Authentication failed.'
});
}
const user = response.rows[0];
bcrypt.compare(req.body.password, user.password)
.then(function(response) {
if (!response) {
return res.json({
success: false,
message: 'Authentication failed.'
});
}
var token = jwt.sign(user, config.credentials.secret, {
expiresIn: 60 // expires in 1 hour
});
return res.json({
success: true,
message: 'Authentication succeeded.',
token: token
});
});
});
});
router.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, config.credentials.secret, function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.send({
success: false,
message: 'No token provided.'
});
}
});
router.post('/token', function(req, res) {
return res.send({
success: true,
message: 'Authenticated.'
});
});
router.get('/pump', function(req, res) {
return res.send({
success: true,
toggled: false
});
});
router.post('/pump', function(req, res) {
return res.send({
success: true,
message: 'Toggled.'
});
});
module.exports = router;