-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (72 loc) · 2.09 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
import express from "express";
import bodyParser from "body-parser";
import pkg from "pg";
import dotenv from "dotenv";
const app = express();
dotenv.config();
const { Pool } = pkg;
const port = process.env.POSTGRES_PORT;
const pool = new Pool({
connectionString: process.env.POSTGRES_URL,
});
pool.connect()
.then(() => console.log("Database connected successfully"))
.catch(err => console.error("Error connecting to the database:", err));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.get("/", (req, res) => {
res.render("home.ejs");
});
app.get("/login", (req, res) => {
res.render("login.ejs");
});
app.get("/register", (req, res) => {
res.render("register.ejs");
});
app.post("/register", async (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
try {
const checkResult = await pool.query("SELECT * FROM users WHERE email = $1", [email]);
if (checkResult.rows.length > 0) {
res.send("Email already exists. Try logging in.");
} else {
const result = await pool.query(
"INSERT INTO users (name,email, password) VALUES ($1, $2, $3)",
[name, email, password]
);
console.log(result);
res.render("secrets.ejs");
}
} catch (err) {
console.log(err);
}
});
app.post("/login", async (req, res) => {
const email = req.body.email;
const password = req.body.password;
try {
const result = await pool.query("SELECT * FROM users WHERE email = $1", [email]);
if (result.rows.length > 0) {
const user = result.rows[0];
const storedPassword = user.password;
if (password === storedPassword) {
res.render("secrets.ejs");
} else {
res.send("Incorrect Password");
}
} else {
res.send("User not found");
}
} catch (err) {
console.log(err);
}
});
app.listen(port, () => {
console.log(`Server running on port http://localhost:${port}`);
});