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

@minimajs/auth

v0.1.0

Published

```bash npm2yarn npm i @minimajs/auth ```

Downloads

18

Readme

Authentication

npm i @minimajs/auth

Authorization in MinimaJS

Authorization play crucial roles in ensuring the security and integrity of your application. MinimaJS provides powerful tools for creating and utilizing interceptors, enabling you to implement authentication and authorization seamlessly. This documentation will guide you through the process of creating interceptors, applying them to routes, and implementing custom authorization guards.

Creating Interceptors

Interceptors are middleware functions that intercept incoming requests before they reach the route handler. They are useful for performing tasks such as authentication, logging, or data transformation. Here's how you can create an interceptor for authentication using MinimaJS:

import { createAuth, UnauthorizedError } from "@minimajs/auth";

export const [authMiddleware, guard, getUser] = createAuth(async () => {
  const token = getHeader("x-user-token");
  const user = await User.findByToken(token);
  if (!user) {
    throw new UnauthorizedError("Invalid credentials");
  }
  return user;
});

In this example, createAuth creates an interceptor for authentication. It expects a callback function that retrieves the user based on the provided token. If the user is not found or the credentials are invalid, it throws an UnauthorizedError.

Using Interceptors

Once you've created the interceptor, you can apply it to routes within your application. Here's how you can use the interceptor in your application:

//
import { interceptor } from "@minimajs/server";
import { authMiddleware, getUser } from "./auth/interceptor";

function getHome() {
  const user: User | undefined = getUser();
  user && console.log(`Logged in as ${user.name}`);
}

// All routes inside this module will have access to authentication
function authenticatedModule(app: App) {
  app.get("/", getHome);
}

app.register(interceptor([authMiddleware], authenticatedModule));

In this example, interceptor is used to apply the authMiddleware to the authenticatedModule. This ensures that all routes within authenticatedModule require authentication. Even if the user is not authenticated, the route handler will still be called, with null as the user.

Authorization Guards

Authorization guards allow you to protect routes based on specific conditions or permissions. MinimaJS provides a flexible mechanism for implementing guards. You can use the guard function returned from createAuth to define custom guards:

// Applying a guard to protect the route
app.register(interceptor([authMiddleware, guard()], authenticatedModule));

You can customize guards further by specifying conditions or providing custom error messages:

// Applying a custom guard with conditions and error message
app.register(
  interceptor([authMiddleware, guard((user) => user?.type === "admin", "Not authorized")], authenticatedModule)
);

Alternatively, you can create reusable guards for common scenarios:

export function admin() {
  return guard((user) => user.isAdmin, "Only admin users are allowed");
}

// Using a reusable guard
app.register(interceptor([authMiddleware, admin()], authenticatedModule));

You can also customize error messages within the guard itself:

export function admin() {
  return guard((user) => {
    if (!user) {
      throw new UnauthorizedError("User not logged in");
    }
    if (!user.isAdmin) {
      throw new UnauthorizedError("User is not authorized");
    }
  });
}

// Using a guard with custom error handling
app.register(interceptor([authMiddleware, admin()], authenticatedModule));

Conclusion

Interceptors and authorization guards are powerful features provided by MinimaJS for ensuring the security and integrity of your application. By creating custom interceptors and guards, you can implement robust authentication and authorization mechanisms tailored to your application's requirements. With MinimaJS, protecting your routes and ensuring data security has never been easier.