-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathserver.js
120 lines (102 loc) · 3.25 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const utils = require('./utils');
const app = express();
const port = process.env.PORT || 4000;
// static user details
const userData = {
userId: "789789",
password: "123456",
name: "Clue Mediator",
username: "cluemediator",
isAdmin: true
};
// enable CORS
app.use(cors());
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
//middleware that checks if JWT token exists and verifies it if it does exist.
//In all future routes, this helps to know if the request is authenticated or not.
app.use(function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.headers['authorization'];
if (!token) return next(); //if no token, continue
token = token.replace('Bearer ', '');
jwt.verify(token, process.env.JWT_SECRET, function (err, user) {
if (err) {
return res.status(401).json({
error: true,
message: "Invalid user."
});
} else {
req.user = user; //set the user to req so other routes can use it
next();
}
});
});
// request handlers
app.get('/', (req, res) => {
if (!req.user) return res.status(401).json({ success: false, message: 'Invalid user to access it.' });
res.send('Welcome to the Node.js Tutorial! - ' + req.user.name);
});
// validate the user credentials
app.post('/users/signin', function (req, res) {
const user = req.body.username;
const pwd = req.body.password;
// return 400 status if username/password is not exist
if (!user || !pwd) {
return res.status(400).json({
error: true,
message: "Username or Password required."
});
}
// return 401 status if the credential is not match.
if (user !== userData.username || pwd !== userData.password) {
return res.status(401).json({
error: true,
message: "Username or Password is Wrong."
});
}
// generate token
const token = utils.generateToken(userData);
// get basic user details
const userObj = utils.getCleanUser(userData);
// return the token along with user details
return res.json({ user: userObj, token });
});
// verify the token and return it if it's valid
app.get('/verifyToken', function (req, res) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token;
if (!token) {
return res.status(400).json({
error: true,
message: "Token is required."
});
}
// check token that was passed by decoding token using secret
jwt.verify(token, process.env.JWT_SECRET, function (err, user) {
if (err) return res.status(401).json({
error: true,
message: "Invalid token."
});
// return 401 status if the userId does not match.
if (user.userId !== userData.userId) {
return res.status(401).json({
error: true,
message: "Invalid user."
});
}
// get basic user details
var userObj = utils.getCleanUser(userData);
return res.json({ user: userObj, token });
});
});
app.listen(port, () => {
console.log('Server started on: ' + port);
});