-
Notifications
You must be signed in to change notification settings - Fork 0
/
app copy.js
105 lines (93 loc) · 2.52 KB
/
app copy.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
require("dotenv").config();
const express = require("express");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
// Server setup
const app = express();
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
// Connect to MongoDB Atlas
const MONGO_URI = process.env.MONGO_HOST || "";
mongoose
.connect(MONGO_URI, { retryWrites: true, w: "majority" })
.then(() => {
console.log("MongoDB Atlas connected");
})
.catch((err) => {
console.log(err);
});
// Create a mongoose schema
const userSchema = new mongoose.Schema({
email: String,
password: String,
});
// Encrypt the password field
// const secret = process.env.MONGO_SECRET;
// userSchema.plugin(encrypt, { secret: secret, encryptedFields: ["password"] });
// Create a mongoose model
const User = mongoose.model("User", userSchema);
// Create a get route
app.get("/", (req, res) => {
res.render("home");
});
app
.route("/login")
.get((req, res) => {
res.render("login");
})
.post((req, res) => {
const username = req.body.username;
const password = req.body.password;
User.findOne({ email: username }, (err, foundUser) => {
if (err) {
console.log(err);
} else {
if (foundUser) {
bcrypt.compare(password, foundUser.password, (err, result) => {
if (err) {
res.send(err);
} else if (result) {
console.log(`Successfully logged in: ${username}`);
res.render("secrets");
} else {
console.log("Incorrect password");
res.send("Incorrect password");
}
});
} else {
console.log(`User not found: ${username}`);
res.send("User not found");
}
}
});
});
app
.route("/register")
.get((req, res) => {
res.render("register");
})
.post((req, res) => {
const saltRounds = 10;
bcrypt.hash(req.body.password, saltRounds, (err, hash) => {
const newUser = new User({
email: req.body.username,
password: hash,
});
newUser.save((err) => {
if (err) {
console.log(err);
} else {
console.log(`Successfully added a new user: ${newUser}`);
res.render("secrets");
}
});
});
});
// Setup PORT for Heroku and localhost
const PORT = process.env.PORT || 8888;
// Start server
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});