-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
100 lines (93 loc) · 2.49 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
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const { getAllUser, createUser } = require("./controller/userController");
getAllUser();
//Mongoose Middleware
mongoose.set("useCreateIndex", true);
//Models
const User = new mongoose.model("User", require("./models/userModel"));
//Set up default mongoose connection
var mongoDB = "mongodb://localhost:27017/jwtTest";
mongoose.connect(
mongoDB,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (err) {
console.log(err);
} else {
console.log("Successfully connected to MongoDB");
}
}
);
const port = process.env.PORT || 5000;
const secret = "umairOnlyUsesBestPractices";
const mockUser = {
id: 1,
username: "umair",
email: "[email protected]",
};
const app = express();
//Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
const verifyToken = (req, res, next) => {
const bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== "undefined") {
const bearer = bearerHeader.split(" ");
const bearerToken = bearer[1];
User.findOne({ email: req.body.user.email }, (err, doc) => {
if (err) {
res.status(400).json({ message: err });
} else {
// console.log(doc[0].token);
if (bearerToken === doc.token) {
next();
} else {
res.sendStatus(403);
}
// req.token = bearerToken;
}
});
} else {
res.sendStatus(403);
}
};
app.post("/api/login", (req, res) => {
const { user } = req.body;
User.findOne({ email: user.email }, (err, doc) => {
if (err) {
console.log(err);
} else {
if (!doc) {
res.status(200).json({ message: "No User Exist" });
} else {
if (user.password !== doc.password) {
res.status(200).json({ message: "Wrong Password!" });
} else {
res.status(200).send(doc);
}
}
}
});
});
app.get("/api", (req, res) => {
res.json({ message: "Welcome to the API" });
});
app.post("/api/post", verifyToken, (req, res) => {
jwt.verify(req.body.user.token, secret, (err, user) => {
if (err) {
res.sendStatus(403);
} else {
res.json({
...user,
message: "Post created...",
});
}
});
});
app.post("/api/register", createUser);
app.listen(port, () => console.log("Server is starting", port));