Skip to content

Instantly share code, notes, and snippets.

@epsi95
Created August 6, 2020 18:42
Show Gist options
  • Save epsi95/b34050aab6aea24d91c327a707dc104c to your computer and use it in GitHub Desktop.
Save epsi95/b34050aab6aea24d91c327a707dc104c to your computer and use it in GitHub Desktop.
// using bcrypt
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const bcrypt = require('bcrypt');
const saltRounds = 0;
const app = express();
mongoose.connect("mongodb://localhost:27017/userDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
const User = mongoose.model("User", UserSchema);
// urlencoded parser is used since the html form send data
// as urlencoded format with POST reqiest
app.use(bodyParser.urlencoded({ extended: true }));
// define the register GET route
app.get("/register", function(req, res) {
res.sendFile(__dirname + "/register.html");
});
// define the login GET route
app.get("/login", function(req, res) {
res.sendFile(__dirname + "/signin.html");
});
// define the register POST route
app.post("/register", function(req, res) {
const email = req.body.email;
const password = req.body.password;
bcrypt.hash(password, saltRounds, function(err, hash) {
const newUser = User({ email: email, password: hash });
newUser.save(function(err) {
if (!err) {
res.redirect("/login");
} else {
res.send(err);
}
});
});
});
// define the login POST route
app.post("/login", function(req, res) {
const email = req.body.email;
const password = req.body.password;
User.findOne({ email: email }, function(err, user) {
if (err) {
res.send(err);
} else if (user) {
bcrypt.compare(password, user.password, function(err, result) {
if (err) {
res.send(err);
} else {
if (result === true) {
res.sendFile(__dirname + "/secret.html");
} else {
res.redirect("/login")
}
}
});
} else {
res.redirect("/login");
}
});
});
///////////////////This is out secret page/////////////////////
// define the secret route
app.get("/secret", function(req, res) {
res.sendFile(__dirname + "/secret.html");
});
app.listen(3000, function() {
console.log(`Server started at port ${3000}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment