forked from makeitrealcamp/node-auth-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
68 lines (57 loc) · 1.41 KB
/
routes.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
const express = require("express");
const router = express.Router();
const User = require("./user");
// authentication middleware
const requireUser = async (req, res, next) => {
const userId = req.session.userId;
if (userId) {
const user = await User.findOne({ _id: userId });
res.locals.user = user;
next();
} else {
return res.redirect("/login");
}
};
router.get("/", requireUser, (req, res) => {
res.render("index");
});
router.get("/register", (req, res) => {
res.render("register");
})
router.post("/register", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const data = {
username: username,
password: password
};
try {
const user = await User.create(data);
} catch (e) {
console.log(e);
}
res.redirect("/login");
});
router.get("/login", (req, res) => {
res.render("login");
});
router.post("/login", async (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
try {
const user = await User.authenticate(email, password);
if (user) {
req.session.userId = user._id;
return res.redirect("/");
} else {
res.render("/login", { error: "Wrong email or password. Try again!" });
}
} catch (e) {
return next(e);
}
});
router.get("/logout", (req, res) => {
res.clearCookie("token");
res.redirect("/login");
});
module.exports = router;