forked from joshgeller/react-redux-jwt-auth-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
56 lines (48 loc) · 1.62 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
'use strict';
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = new(require('express'))();
const port = 3000;
const config = require('./webpack.config');
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
app.use(bodyParser.json());
app.post('/auth/getToken/', (req, res) => {
if (req.body.email == '[email protected]' && req.body.password == 'test') {
res.status(200)
.json({token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6IlRlc3QgVXNlciJ9.J6n4-v0I85zk9MkxBHroZ9ZPZEES-IKeul9ozxYnoZ8'});
} else {
res.sendStatus(403);
}
});
app.get('/getData/', (req, res) => {
let token = req.headers['authorization'];
if (!token) {
res.sendStatus(401);
} else {
try {
let decoded = jwt.verify(token.replace('Bearer ', ''), 'secret-key');
res.status(200)
.json({data: 'Valid JWT found! This protected data was fetched from the server.'});
} catch (e) {
res.sendStatus(401);
}
}
})
app.get('/', (req, res) => {
res.sendFile(__dirname + '/dist/index.html');
});
app.listen(port, (error) => {
if (error) {
console.error(error);
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
}
});