Website Building Coding: Authentication & Security

Mongoose-encryption

//terminal: npm i mongoose-encryption

//jshint esversion:6
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser'); // Required package to process data of user inputs
const mongoose = require('mongoose');
const encrypt = require('mongoose-encryption');
const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true })); // Required, otherwise the req.body.x below won’t work

const port = 3000;

mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true });
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
});

userSchema.plugin(encrypt, { secret: process.env.SECRET, encryptedFields: ['password'] });
const User = new mongoose.model('User', userSchema);

app.get('/', function (req, res) {
  res.render('home');
});

app.get('/:page', function (req, res) {
  console.log(req.params.page);
  res.render(req.params.page);
});

app.post('/register', function (req, res) {
  const newUser = new User({
    email: req.body.username,
    password: req.body.password,
  });
  newUser.save(function (err) {
    if (err) {
      console.log(err);
    } else {
      res.render('secrets');
    }
  });
});



app.listen(port, function (err, result) {
  if (!err) {
    console.log('server has started');
  } else {
    console.log(err);
  }
});

MD5

//terminal: npm install md5

//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const md5 = require("md5");

const app = express();

console.log("weak password hash: " + md5("123456"));
console.log("strong password hash: " + md5("sjkhdfsd8f7jhsd$%$sdfsdfHJKHSJFHDSF78324"));

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});

const userSchema = new mongoose.Schema ({
  email: String,
  password: String
});


const User = new mongoose.model("User", userSchema);

app.get("/", function(req, res){
  res.render("home");
});

app.get("/login", function(req, res){
  res.render("login");
});

app.get("/register", function(req, res){
  res.render("register");
});

app.post("/register", function(req, res){
  const newUser =  new User({
    email: req.body.username,
    password: md5(req.body.password)
  });
  newUser.save(function(err){
    if (err) {
      console.log(err);
    } else {
      res.render("secrets");
    }
  });
});

app.post("/login", function(req, res){
  const username = req.body.username;
  const password = md5(req.body.password);

  User.findOne({email: username}, function(err, foundUser){
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {
        if (foundUser.password === password) {
          res.render("secrets");
        }
      }
    }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000.");
});

Bcrypt

//terminal: npm i bcrypt

//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const saltRounds = 10;

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});

const userSchema = new mongoose.Schema ({
  email: String,
  password: String
});


const User = new mongoose.model("User", userSchema);

app.get("/", function(req, res){
  res.render("home");
});

app.get("/login", function(req, res){
  res.render("login");
});

app.get("/register", function(req, res){
  res.render("register");
});

app.post("/register", function(req, res){

  bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
    const newUser =  new User({
      email: req.body.username,
      password: hash
    });
    newUser.save(function(err){
      if (err) {
        console.log(err);
      } else {
        res.render("secrets");
      }
    });
  });

});

app.post("/login", function(req, res){
  const username = req.body.username;
  const password = req.body.password;

  User.findOne({email: username}, function(err, foundUser){
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {
        bcrypt.compare(password, foundUser.password, function(err, result) {
          if (result === true) {
            res.render("secrets");
          }
        });
      }
    }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000.");
});

Passport.js

//terminal: npm i passport passport-local passport-local-mongoose express-session

//jshint esversion:6
require('dotenv').config();
const express = require('express'); // Express.JS Boilerplate highlighted in Purple
const bodyParser = require('body-parser'); // Required package to process data of user inputs
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');

const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true })); // Required, otherwise the req.body.x below won’t work
app.use(express.static("public"));
app.use(session({
  secret: SECRET_SENTENCE;
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session ());

const port = 3000;

mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true });
mongoose.set("useCreateIndex",true);
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model('User', userSchema);
passport.use(User.createStrategy()); // Alternatively: passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get('/', function (req, res) {
  res.render('home');
});

app.get('/secrets', function(req, res){
  if(req.isAuthenticated()){
    res.render("secrets");
  } else {
    res.redirect("/login");
  }
})

app.post('/register', function (req, res) {
  User.register({username: req.body.username},req.boday.password, function(err,user){
    if(err){
      console.log(err);
      res.redirect("/register");
    } else{
      passport.authenticate("local")(req,res, fuction(){
        res.redirect("/secrets");
      })
    }
  })
});

app.post('/login',function(req, res){
  const user = new User({
    username: req.body.username,
    password: req.body.password
  });
  req.login(user, function(err){
    if(err){
      console.log(err);
    }else{
      passport.authenticate('local')(req,res, function(){
        res.redirect('/secrets');
      });
    }
  });
});

app.get("/logout", function(req, res){
  req.logout();
  res.redirect("/");
});

app.listen(port, function (err, result) {
  if (!err) {
    console.log('server has started');
  } else {
    console.log(err);
  }
});  

Third-party OAUTH (google)

//terminal: npm i passport-google-oauth20 mongoose-findocreate

//jshint esversion:6
require('dotenv').config();
const express = require('express'); // Express.JS Boilerplate highlighted in Purple
const bodyParser = require('body-parser'); // Required package to process data of user inputs
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate=require("mongoose-findocreate");

const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true })); // Required, otherwise the req.body.x below won’t work
app.use(express.static("public"));
app.use(session({
  secret: SECRET_SENTENCE;
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session ());

const port = 3000;

mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true });
mongoose.set("useCreateIndex",true);
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  googleId: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plubin(findOrCreate);

const User = new mongoose.model('User', userSchema);
passport.use(User.createStrategy()); // Alternatively: passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new GoogleStrategy({
  clientID: GOOGLE_CLIENT_ID,
  clientSecret: GOOGLE_CLIENT_SECRET,
  callbackURL: "http://www.example.com/auth/google/callback"
},
function(accessToken, refreshToken, profile, cb) {
  User.findOrCreate({ googleId: profile.id }, function (err, user) {
    return cb(err, user);
  });
}
));

app.get('/', function (req, res) {
  res.render('home');
});

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.get('/secrets', function(req, res){
  if(req.isAuthenticated()){
    res.render("secrets");
  } else {
    res.redirect("/login");
  }
})

app.post('/register', function (req, res) {
  User.register({username: req.body.username},req.boday.password, function(err,user){
    if(err){
      console.log(err);
      res.redirect("/register");
    } else{
      passport.authenticate("local")(req,res, fuction(){
        res.redirect("/secrets");
      })
    }
  })
});

app.post('/login',function(req, res){
  const user = new User({
    username: req.body.username,
    password: req.body.password
  });
  req.login(user, function(err){
    if(err){
      console.log(err);
    }else{
      passport.authenticate('local')(req,res, function(){
        res.redirect('/secrets');
      });
    }
  });
});

app.get("/logout", function(req, res){
  req.logout();
  res.redirect("/");
});

app.listen(port, function (err, result) {
  if (!err) {
    console.log('server has started');
  } else {
    console.log(err);
  }
});

0 Comments