-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
100 lines (75 loc) · 2.47 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
91
92
93
94
95
96
97
98
99
100
const express = require("express");
const mongoose = require("mongoose");
const cookieSession = require("cookie-session");
const bcrypt = require("bcrypt");
const User = require("./models/User");
const authenticateUser = require("./middlewares/authenticateUser");
const app = express();
require('./startup/db')();
require('./startup/middleware')(app);
// cookie session
app.use(
cookieSession({
keys: ["randomStringASyoulikehjudfsajk"],
})
);
// route for serving frontend files
app
.get("/", (req, res) => {
res.render("index");
})
.get("/login", (req, res) => {
res.render("login");
})
.get("/register", (req, res) => {
res.render("register");
})
.get("/home", authenticateUser, (req, res) => {
res.render("home", { user: req.session.user });
});
// route for handling post requirests
app
.post("/login", async (req, res) => {
const { email, password } = req.body;
// check for missing filds
if (!email || !password) return res.send("Please enter all the fields");
const doesUserExits = await User.findOne({ email });
if (!doesUserExits) return res.send("invalid username or password");
const doesPasswordMatch = await bcrypt.compare(
password,
doesUserExits.password
);
if (!doesPasswordMatch) return res.send("invalid useranme or password");
// else he\s logged in
req.session.user = {
email,
};
res.redirect("/home");
})
.post("/register", async (req, res) => {
const { email, password } = req.body;
// check for missing filds
if (!email || !password) return res.send("Please enter all the fields");
const doesUserExitsAlreay = await User.findOne({ email });
if (doesUserExitsAlreay) return res.send("A user with that email already exits please try another one!");
// lets hash the password
const hashedPassword = await bcrypt.hash(password, 12);
const latestUser = new User({ email, password: hashedPassword });
latestUser
.save()
.then(() => {
res.send("registered account!");
res.redirect("/login");
})
.catch((err) => console.log(err));
});
//logout
app.get("/logout", authenticateUser, (req, res) => {
req.session.user = null;
res.redirect("/login");
});
// server config
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server started listening on port: ${PORT}`);
});