-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
69 lines (59 loc) · 2.04 KB
/
auth.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
const express = require("express");
const router = express.Router();
const UserModel = require("./UserModel");
const jwt = require("jsonwebtoken");
function isAuthenticated(req, res, next) {
if (req.headers.authorization) {
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, "secret", (err, user) => {
if (!user) return res.json({ message: "User not authenticated" });
else next();
});
}
}
router.get("/protected", isAuthenticated, async (req, res) => {
return res.json({ message: "This is a protected route" });
});
router.post("/login", async (req, res) => {
const { username, password } = req.body.data;
if (!username || !password)
return res.json({ message: "Invalid credentials" });
const user = await UserModel.findOne({ username: username });
if (user) {
if (user.password === password) {
const payload = {
username
};
jwt.sign(payload, "secret", { expiresIn: "1d" }, (err, token) => {
if (err) console.log(err);
else {
return res.json({
message: "User logged In!",
token: token
});
}
});
} else {
return res.json({ message: "Incorrect password" });
}
} else {
return res.json({ message: "Incorrect credentials" });
}
});
router.post("/signup", async (req, res) => {
const { username, password } = req.body.data;
if (!username || !password)
return res.json({ message: "Invalid credentials" });
const userExists = await UserModel.findOne({ username: username });
console.log(userExists);
if (userExists) return res.json({ message: "User already exists" });
else {
const newUser = new UserModel({
username,
password
});
newUser.save();
return res.json({ message: "User created", newUser });
}
});
module.exports = router;