npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@warrantdev/warrant-express-middleware

v2.0.0

Published

Expressjs Middleware for enforcing access control on API endpoints using the Warrant API

Downloads

4

Readme

Warrant Express.js Authorization Middleware

Use Warrant in server-side Express.js projects.

npm Slack

Installation

Use npm to install the Warrant module:

npm install @warrantdev/warrant-node
npm install @warrantdev/warrant-express-middleware

Usage

Initializing the Middleware

Import the createMiddleware function and call it with some initialization options to get a configured middleware function you can protect your API routes with:

const Warrant = require("@warrantdev/warrant-node");
const WarrantMw = require("@warrantdev/warrant-express-middleware");
const { hasPermission, hasAccess } = WarrantMw.createMiddleware({
  client: new Warrant({
    apiKey: "api_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=",
  }),
  getUserId: (req, res) => MyUserSession.getUserId(req, res).toString(), // Tell the middleware how to get the current user in your API
});

// The hasAccess middleware will run before the route code.
app.get(
  "/api/posts/:postId",
  hasAccess("post", (req) => req.params["postId"], "viewer"),
  (req, res) => {
    const { postId } = req.params;
    const post = getPost(postId);

    if (!post) {
      res.sendStatus(404);
      return;
    }

    res.json(post);
  }
);

Or using ES modules:

import Warrant from "@warrantdev/warrant-node";
import { createMiddleware } from "@warrantdev/warrant-express-middleware";
const { hasPermission, hasAccess } = Warrant.createMiddleware({
  client: new Warrant({
    apiKey: "api_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=",
  }),
  getUserId: (req, res) => MyUserSession.getUserId(req, res).toString(), // Tell the middleware how to get the current user in your API
});

// The hasAccess middleware will run before the route code.
app.get(
  "/api/posts/:postId",
  hasAccess("post", (req) => req.params["postId"], "viewer"),
  (req, res) => {
    const { postId } = req.params;
    const post = getPost(postId);

    if (!post) {
      res.sendStatus(404);
      return;
    }

    res.json(post);
  }
);

Using the Middleware

Once you've initialized the middleware as shown above, you can use either the hasPermission or the hasAccess method to protect your Express.js API routes:

hasPermission

// The hasPermission middleware will check that the current user
// has the specified permission before executing the route.
app.post("/api/posts", hasPermission("create-posts"), (req, res) => {
  try {
    const newPost = createPost(req.body);
    res.json(newPost);
  } catch (e) {
    res.sendStatus(e.code);
  }
});

hasAccess

// The hasAccess middleware will check that the current user is a "viewer"
// of the particular Post with id postId before executing the route.
app.get(
  "/api/posts/:postId",
  hasAccess("post", (req) => req.params["postId"], "viewer"),
  (req, res) => {
    const { postId } = req.params;
    const post = getPost(postId);

    if (!post) {
      res.sendStatus(404);
      return;
    }

    res.json(post);
  }
);

The hasPermission middleware function takes a single argument:

permissionId

string - This is the string id of the permission you want to check for (ex: "view-posts").

The hasAccess middleware function takes 3 arguments:

objectType

string - This is the object type you want to perform an access check for. To learn more about creating object types, visit our documentation.

getObjectId(req, res)

function - A function executed by the middleware in order to get the id of the object for which to perform the access check. In most scenarios, this will be the value of one of the request params. An example of what this function might look like:

(req: Request) => req.params["myParam"];

relation

string - This is the relation you want to perform an access check for. To learn more about relations, visit our documentation.

Configuration Options

The middleware supports options that allow you to configure how it works during the initialization step. All options are required unless stated that they are optional.

clientKey

string - This is the API Key from the Warrant Dashboard. Without this value, the middleware cannot make requests to the Warrant API to perform access checks in your application.

getUserId(req, res)

function - A function executed by the middleware in order to get the userId for which to perform an access check. Use this function to tell the middleware how to get the current user's id. Usually this user is determined using the current session or authentication token provided in the request.

onAuthorizeFailure(req, res) (Optional)

function - A function executed by the middleware when an access check fails (the user is unauthorized). Use this function to tell the middleware what to do when a user fails an access check. This option defaults to:

(req: Request, res: Response) => res.sendStatus(401);

We’ve used a random API key in these code examples. Replace it with your actual publishable API keys to test this code through your own Warrant account.

For more information on how to use the Warrant API, please refer to the Warrant API reference.

Note that we may release new minor and patch versions of @warrantdev/warrant-express-middleware with small but backwards-incompatible fixes to the type declarations. These changes will not affect Warrant itself.

TypeScript support

This package includes TypeScript declarations for Warrant.

Warrant Documentation