-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
113 lines (87 loc) · 2.46 KB
/
index.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
113
import express from "express";
import path from "path";
import mongoose from "mongoose";
import cookieParser from "cookie-parser";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
mongoose
.connect("mongodb://localhost:27017", {
dbName: "backend",
})
.then(() => console.log("Database Connected"))
.catch((e) => console.log(e));
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
const User = mongoose.model("User", userSchema);
const app = express();
// Using Middlewares
app.use(express.static(path.join(path.resolve(), "public")));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// Setting up View Engine
app.set("view engine", "ejs");
const isAuthenticated = async (req, res, next) => {
const { token } = req.cookies;
if (token) {
const decoded = jwt.verify(token, "PRYVATE__KEY");
req.user = await User.findById(decoded._id);
next();
} else {
res.redirect("/login");
}
};
app.get("/", isAuthenticated, (req, res) => {
res.render("logout", { name: req.user.name });
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/register", (req, res) => {
res.render("register");
});
app.post("/login", async (req, res) => {
const { email, password } = req.body;
let user = await User.findOne({ email });
if (!user) return res.redirect("/register");
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch)
return res.render("login", { email, message: "Incorrect Password" });
const token = jwt.sign({ _id: user._id }, "PRYVATE__KEY");
res.cookie("token", token, {
httpOnly: true,
expires: new Date(Date.now() + 60 * 1000),
});
res.redirect("/");
});
app.post("/register", async (req, res) => {
const { name, email, password } = req.body;
let user = await User.findOne({ email });
if (user) {
return res.redirect("/login");
}
const hashedPassword = await bcrypt.hash(password, 10);
user = await User.create({
name,
email,
password: hashedPassword,
});
const token = jwt.sign({ _id: user._id }, "PRYVATE__KEY");
res.cookie("token", token, {
httpOnly: true,
expires: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000),
});
res.redirect("/");
});
app.get("/logout", (req, res) => {
res.cookie("token", null, {
httpOnly: true,
expires: new Date(Date.now()),
});
res.redirect("/");
});
app.listen(5000, () => {
console.log("Server is working");
});