0.0.2-0 • Published 3 years ago

quik-auth v0.0.2-0

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

quik-auth @0.0.1

image info image info image info image info

Run npm i quik-auth and Require the package

Make a .env file in your root directory and initialize DB_CONNECT = Your MongoDB authentification endpoint PRIVATE_KEY = A private key for signing JWT

schema();

launchServer(port, app);

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

Call the function schema() You can either call the function directly which will use this default schema. You can also pass your own custom schema as an argument to the function so that you can use a custom schema

This is the default schema:

// 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);

auth is a Middleware, which can be passed on to your other routes 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" });
  }
0.0.2-0

3 years ago

0.0.1

3 years ago