1.0.4 • Published 4 years ago

json-auth v1.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

json-auth @1.0.4

image info image info image info image info

Run npm i express mongoose jsonwebtoken

Run npm i @cyberflaw/express-mongodb-jwt

Make a file with name config.json in the root directory

{
    "schemaPath": "path of your mongoose.Schema for your user",

    "jwt":{
            "expiresIn": "refer jwt documentation"
    }
}

schemaPath can be left out to use the default schema which is:

// Importing dependencies
const mongoose = require("mongoose");

// Defining post schema
const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      min: 6,
      max: 12,
    },
    email: {
      type: String,
      required: true,
      min: 6,
      max: 32,
    },
    password: {
      type: String,
      required: true,
      min: 6,
      max: 124,
    },
    date: {
      type: Date,
      default: Date.now,
    },
  },
  { collection: "users" }
);

module.exports = mongoose.model("User", userSchema);

Make a file with name env.json in the root directory and add this your .gitignore

{
    "dbConnect": "db auth key",
    "privateKey": "string for signing jwt (HMAC SHA256 currently)"
}
const {launchServer, auth, app} = require('@cyberflaw/express-mongodb-jwt');

launchServer(port);

app.get(
  '/private/route',
  auth,
  (req,res) => res.send("Its a private route!")
);

auth is a Middleware which can be passed to your other routed in order to make it private. This will be the middleware code running in the background

const token = req.header("token");

  if (!token) return res.status(401).json({ message: "Auth Error" });

  try {
    const decoded = jwt.verify(token, process.env.PRIVATE_KEY);
    req.user = decoded.user;

    next();
  } catch (err) {
    console.log(err);
    res.status(500).send({ message: "Invalid Token" });
  }

Click Here to visit the Github repo

Click Here to visit the npmjs

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago