-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
90 lines (79 loc) · 1.83 KB
/
app.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
const express = require("express");
const app = express();
const cors = require("cors");
const { hashSync, compareSync } = require("bcrypt");
const UserModel = require("./config/database");
const jwt = require("jsonwebtoken");
const passport = require("passport");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(passport.initialize());
require("./config/passport");
app.post("/register", (req, res) => {
const user = new UserModel({
username: req.body.username,
password: hashSync(req.body.password, 10),
});
user
.save()
.then((user) => {
res.send({
success: true,
message: "User created successfully.",
user: {
id: user._id,
username: user.username,
},
});
})
.catch((err) => {
res.send({
success: false,
message: "Something went wrong",
error: err,
});
});
});
app.post("/login", (req, res) => {
UserModel.findOne({ username: req.body.username }).then((user) => {
//No user found
if (!user) {
return res.status(401).send({
success: false,
message: "Could not find the user.",
});
}
//Incorrect password
if (!compareSync(req.body.password, user.password)) {
return res.status(401).send({
success: false,
message: "Incorrect password",
});
}
const payload = {
username: user.username,
id: user._id,
};
const token = jwt.sign(payload, "Random string", { expiresIn: "1d" });
return res.status(200).send({
success: true,
message: "Logged in successfully!",
token: "Bearer " + token,
});
});
});
app.get(
"/protected",
passport.authenticate("jwt", { session: false }),
(req, res) => {
return res.status(200).send({
success: true,
user: {
id: req.user._id,
username: req.user.username,
},
});
}
);
app.listen(5000, () => console.log("Listening to port 5000"));