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

koa-simple-oauth

v1.1.1

Published

Simple OAuth2 authentication middleware for Koa.

Downloads

10

Readme

koa-simple-oauth

koa-simple-oauth

Simple OAuth2 authentication middleware for Koa. Internally uses simple-oauth2 and Node Fetch API.

Requirements

Installation

yarn add koa-simple-oauth

Usage

Requirements

import Koa from 'koa';
import session from 'koa-session';
import simpleOauth from 'koa-simple-oauth';

// Initialize Koa
const app = new Koa();

// Initialize Koa Session
app.keys = ['secretSessionKey'];
const sessionConfig = {};
app.use(session(sessionConfig, app));

Configuration

const oauthConfig = {
    // Client ID and secret for OAuth provier
    clientId: 'abcdefgh1234',
    clientSecret: '5678mnopqrst',

    // Base URL for OAuth provider
    url: 'https://oauth.example.com/api/v1',

    // Redirect URL for this application, i.e. where you mounted the authorized middleware
    redirectUrl: 'https://myapp.example.com/api/v1/oauth/authorized',

    // User API URL and HTTP method
    userUrl: 'https://oauth.example.com/api/v1/me',
    userMethod: 'GET',

    // Get user from API response or return an error
    user: (data) => {
        const user = data.user;
        if (!user.isAdmin) {
            return 'not_admin';
        }
        return user;
    },

    // These options are passed to simple-oauth2, see https://github.com/lelylan/simple-oauth2
    oauthOptions: {},

    // Default redirect URL on success (or set the redirect query parameter)
    redirectSuccessUrl: 'https://myapp.example.com/login/success',

    // Redirect URL on error (will add an error message as error query parameter by default, e.g. ?error=invalid_code_or_state)
    redirectErrorUrl: 'https://myapp.example.com/login/error',

    // Don't send an error query parameter to the error redirect URL (see above)
    disableErrorReason: false,

    // Called on successful API response (e.g. whoami endpoint)
    onSuccess: (ctx, data, status = 200) => {
        ctx.status = status;
        ctx.body = typeof data === 'object' ? JSON.stringify(data) : data;
    },

    // Called on error API response (e.g. whoami endpoint)
    onError: (ctx, status, message, err) => {
        ctx.status = status;
        ctx.body = `${message}: ${err.message}`;
    },

    // Called whenever on error occurs
    logError: (err) => {
        if (err.message !== 'Not logged in') {
            console.error(err);
        }
    },

    // Route configuration (only works if a router is provided)
    routes: {
        login: '/login',
        authorized: '/authorized',
        whoami: '/whoami',
        logout: '/logout'
    }
};

With Koa Router (recommended)

import Router from 'koa-router';

// Initialize Koa Router
const router = new Router();

// Initialize Koa Simple OAuth
// Adds all required middleware to the router
const {isLoggedIn, requireLogin} = simpleOauth(oauthConfig, router);

// Check if a user is logged in
router.use(isLoggedIn);
router.get('/admin', async (ctx) => {
    if (ctx.state.isLoggedIn()) {
        ctx.body = 'Logged in';
    } else {
        ctx.status = 403;
        ctx.body = 'Not logged in';
    }
});

// Check if the user is logged in using middleware
router.get('/admin2', requireLogin, async (ctx) => {
    ctx.body = 'Logged in';
})

// Add Koa Router middleware
app.use(router.routes());
app.use(router.allowedMethods());

With Koa Mount

import mount from 'koa-mount';

// Initialize Koa Simple OAuth
// Returns an object with all required middleware
const oauthMiddleware = simpleOauth(oauthConfig);
const {login, authorized, whoami, logout} = oauthMiddleware;

// Mount the OAuth middleware
app.use(mount('/login', login));
app.use(mount('/authorized', authorized));
app.use(mount('/whoami', whoami));
app.use(mount('/logout', logout));

With Koa Route

import _ from 'koa-route';

// Initialize Koa Simple OAuth
// Passes all required middleware through the router function and returns the resulting middleware as an object
const oauthMiddleware = simpleOauth(oauthConfig, _);

// Mount the OAuth middleware
const {login, authorized, whoami, logout} = oauthMiddleware;
app.use(login);
app.use(authorized);
app.use(whoami);
app.use(logout);

// Or mount it less explicitly
Object.values(oauthMiddleware).forEach((middleware) => {
    app.use(middleware);
});