Skip to content

Instantly share code, notes, and snippets.

@epsi95
Created August 6, 2020 18:13
Show Gist options
  • Save epsi95/414de9fd12d27d6c4ab48f23c9be0901 to your computer and use it in GitHub Desktop.
Save epsi95/414de9fd12d27d6c4ab48f23c9be0901 to your computer and use it in GitHub Desktop.
// with mongoose-encryption
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const encrypt = require('mongoose-encryption');
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 secret = "This is a secret key, it should be unguessable";
UserSchema.plugin(encrypt, { secret: secret, encryptedFields: ['password'] });
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;
const newUser = User({ email: email, password: password });
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) {
if (password === user.password) {
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