-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
112 lines (96 loc) · 2.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
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
const express = require("express");
const jwt = require("jsonwebtoken");
const cors = require("cors");
const bodyParser = require("body-parser");
const fs = require("fs");
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get("/home", (req, res) => {
res.send('home')
})
app.get("/dashboard", verifyToken, (req, res) => {
jwt.verify(req.token, "the_secret_key", err => {
if (err) {
res.sendStatus(401);
} else {
res.send('dashboard')
({
});
}
});
});
app.post("/register", (req, res) => {
if (req.body) {
const user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
// In a production app, you'll want to encrypt the password
};
const data = JSON.stringify(user, null, 2);
var dbUserEmail = require("./db/user.json").email;
var errorsToSend = [];
if (dbUserEmail === user.email) {
errorsToSend.push("An account with this email already exists.");
}
if (user.password.length < 5) {
errorsToSend.push("Password too short.");
}
if (errorsToSend.length > 0) {
res.status(400).json({ errors: errorsToSend });
} else {
fs.writeFile("./db/user.json", data, err => {
if (err) {
console.log(err + data);
} else {
const token = jwt.sign({ user }, "the_secret_key");
// In a production app, you'll want the secret key to be an environment variable
res.json({
token,
email: user.email,
name: user.name
});
}
});
}
} else {
res.sendStatus(400);
}
});
app.post("/login", (req, res) => {
const userDB = fs.readFileSync("./db/user.json");
const userInfo = JSON.parse(userDB);
if (
req.body &&
req.body.email === userInfo.email &&
req.body.password === userInfo.password
) {
const token = jwt.sign({ userInfo }, "the_secret_key");
// In a production app, you'll want the secret key to be an environment variable
res.json({
token,
email: userInfo.email,
name: userInfo.name
});
} else {
res.status(401).json({ error: "Invalid login. Please try again." });
}
});
// MIDDLEWARE
function verifyToken(req, res, next) {
const bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== "undefined") {
const bearer = bearerHeader.split(" ");
//Get token from array
const bearerToken = bearer[1];
//Set the token
req.token = bearerToken;
next();
} else {
res.sendStatus(401);
}
}
app.listen(5000, () => {
console.log("Server started on port 5000");
});