Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/learnwithfair/web-authentication-documentation

web-authentication-documentation with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]. In this repo I describes about Database Matching, Database Encryption Hashing, Hashing + Salting Password, Cookies and Session with Passport, Google OAuth with passport session based, Passport-jwt (token based)
https://github.com/learnwithfair/web-authentication-documentation

auth authentication database-encryption database-matching hashing jwt-authentication learn-with-fair learnwithfair passport-google-oauth20 passport-local passportjs rahatul-rabbi rahatulrabbi salting web-authentication

Last synced: 9 days ago
JSON representation

web-authentication-documentation with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]. In this repo I describes about Database Matching, Database Encryption Hashing, Hashing + Salting Password, Cookies and Session with Passport, Google OAuth with passport session based, Passport-jwt (token based)

Awesome Lists containing this project

README

        

# WEB-AUTHENTICATION-DOCUMENTATION

Thanks for visiting my GitHub account!

**Web Authentication** is a web standard published by the World Wide Web Consortium. WebAuthn is a core component of the FIDO2 Project under the guidance of the FIDO Alliance [see-more](https://webauthn.guide/#intro)

## Source Code (Download)

[Click Here](https://mega.nz/folder/RGFiUApD#PoKIVCwF8IkQhE2PHw1XxQ)

## Authentication Schema

| |
| :------------------------------------------: |
| Schema |
| ![schema](images/Web_Authentication.svg.png) |

## Table of Contents

1. [Database Matching](#level-1-database-matching)
2. [Database Encryption](#level-2-database-encryption)
3. [Hashing Password](#level-3-hashing-password)
4. [Hashing + Salting Password](#level-4-hashing--salting-password)
5. [Cookies & Session with Passport](#level-5-cookies--session-with-passport)
6. [Google OAuth with passport session based](#level-6-google-oauth-with-passport-session-based)
7. [Passport-jwt (token based)](#level-7-passport-jwt-token-based)
8. [Follow Me](#follow-me)

## Level 1: Database matching

- save(), find({property: value})
- if hacker can access our database then our data is too much human readable
- [password checker online](http://password-checker.online-domain-tools.com/)

## Level 2: Database Encryption

- read mongoose encryption documentation: https://www.npmjs.com/package/mongoose-encryption
- install mongoose encryption `npm install mongoose-encryption`
- create new mongoose Schema

```js
const mongoose = require("mongoose");
const encrypt = require("mongoose-encryption");

const userSchema = new mongoose.Schema({
name: String,
age: Number,
// whatever else
});
```

- create an encryption key inside .env file

```js
ENCRYPTION_KEY = thisismyencryptionkey;
```

- set encryption key with our schema

```js
const encrypt = require("mongoose-encryption");

const encKey = process.env.ENCRYPTION_KEY;
// encrypt age regardless of any other options. name and _id will be left unencrypted
userSchema.plugin(encrypt, {
secret: encKey,
encryptedFields: ["age"],
});

User = mongoose.model("User", userSchema);
```

## Level 3: Hashing password

- no cncryption key; we will use hashing algorithm
- hackers can not convert to plain text as no encryption key is available
- md5 package: https://www.npmjs.com/package/md5
- install md5 npm package: `npm install md5`
- usage

```js
var md5 = require("md5");
console.log(md5("message"));
// 78e731027d8fd50ed642340b7c9a63b3

// hash password when create it
const newUser = new User({
email: req.body.username,
password: md5(req.body.password),
});

app.post("/login", async (req, res) => {
try {
const email = req.body.email;
const password = md5(req.body.password);
const user = await User.findOne({ email: email });
if (user && user.password === password) {
res.status(200).json({ status: "valid user" });
} else {
res.status(404).json({ status: "Not valid user" });
}
} catch (error) {
res.status(500).json(error.message);
}
});
```

## Level 4: Hashing + salting password

- we can hash the password with some random number(salting)
- install bcrypt npm package `npm install bcrypt`
- usage

```js
const bcrypt = require("bcrypt");
const saltRounds = 10;

app.post("/register", async (req, res) => {
try {
bcrypt.hash(req.body.password, saltRounds, async function (err, hash) {
const newUser = new User({
email: req.body.email,
password: hash,
});
await newUser.save();
res.status(201).json(newUser);
});
} catch (error) {
res.status(500).json(error.message);
}
});

app.post("/login", async (req, res) => {
try {
const email = req.body.email;
const password = req.body.password;
const user = await User.findOne({ email: email });
if (user) {
bcrypt.compare(password, user.password, function (err, result) {
if (result === true) {
res.status(200).json({ status: "valid user" });
}
});
} else {
res.status(404).json({ status: "Not valid user" });
}
} catch (error) {
res.status(500).json(error.message);
}
});
```

## Level 5: Cookies & Session with passport

- passport local strategy

- `npm install passport passport-local passport-local-mongoose express-session`

- my computer browser -> browse aliexpress (GET Request) -> to aliexpress server -> response the website -> add some items to the cart (post request to the server) -> aliexpress server will response and tell the browser to create a file in my computer for storing my selection -> so when next time we make a get request to the server we send the cookie with the get request -> server will return the cart again

- cookie is a text file created by server on a user's device when we visit a website
- that stores limited information such as login credentials - username, password; user preferences, cart contents from a web browser session
- saving users behaviour
- read more about cookies - https://www.trendmicro.com/vinfo/us/security/definition/cookies
- types of cookies -> session cookie, presistent cookie, supercookie
- login -> save user credentials as cookie for next time authentication -> log out and the session is destroyed
- salt and hash is automatically generated by passport-local-mongoose
- express session package create the cookie

1. passport js framework has 2 separeate libraries

- Passport JS Library (main) - maintain session information for user authentication
- strategy library - methodology for authenticate an user - passport-local, passport-facebook, passport-oauth2 etc.

2. Login process handled by 2 steps: i) session management (Passport.js), ii) authentication (strategy)
`npm install passport-local`
`npm install passport-facebook`

3. for managing session Passport.js library takes help from express-session library
`npm install passport express-session`

4. source code

- bootstrap the project

- installing & requiring packages
`npm install express nodemon dotenv mongoose ejs cors`
- creating server

```js
//app.js
const express = require("express");
const cors = require("cors");
const ejs = require("ejs");

const app = express();

app.set("view engine", "ejs");
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

module.exports = app;

//index.js
const app = require("./app");
const PORT = 4000;
app.listen(PORT, () => {
console.log(`app is running at http://localhost:${PORT}`);
});
```

- creating routes including try,catch

```js
// base url
app.get("/", (req, res) => {
res.render("index");
});

// register routes
app.get("/register", (req, res) => {
res.render("register");
});

app.post("/register", (req, res) => {
try {
res.status(201).send("user is registered");
} catch (error) {
req.status(500).send(error.message);
}
});

// login routes
app.get("/login", (req, res) => {
res.render("login");
});

app.post("/login", (req, res) => {
try {
res.status(201).send("user is logged in");
} catch (error) {
req.status(500).send(error.message);
}
});

// logout routes
app.get("/logout", (req, res) => {
res.redirect("/");
});

// profile protected routes
app.get("/profile", (req, res) => {
res.render("profile");
});
```

- creating ejs files

- create layout

```html







Document




Home
Register
Login
Profile
Logout





copyright by Rahatul Rabbi