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

@tycrek/accounted4

v0.8.0

Published

Express middleware for easy OAuth with a variety of providers.

Downloads

16

Readme

accounted4

NPMCBT badge

Express middleware for easy OAuth2 with a variety of providers.

accounted4 is intended to make it easy for developers to add third-party OAuth2! support to their Node.js applications. This project is still in its infancy; more features and providers will be added in the future. Supported OAuth2 providers are detailed below.

For more information on OAuth2, the folks at FusionAuth wrote a fantastic, easy-to-understand OAuth2 guide that I highly recommend. Additionally, the OAuth2 specification is a great resource for all other information about OAuth2.

Usage

Install the @tycrek/accounted4 package:

npm i @tycrek/accounted4

# You'll also need express-session and a session store. Optimally you'll use something other than MemoryStore in production.
npm i express-session memorystore

Preparing the code

accounted4 is intended for use with Express. It requires the use of express-session and a compatible session store. The easiest way to get started is by using the memorystore module. In a production environment, it is recommended to use a proper database with the corresponding module for a session store.

For tutorial purposes, this README will use memorystore, but feel free to use another if you prefer.

import { Accounted4 } from '@tycrek/accounted4';
import express from 'express';
import session from 'express-session';
import MemoryStore from 'memorystore';

const app = express();
const sessionStore = MemoryStore(session);

The next block attaches the session middleware to Express. You are recommended to adjust these settings as you see fit.

const DAY = 86400000;
app.use(session({
    name: 'accounted4',
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: DAY, secure: false /* set to true if using HTTPS*/ },
    secret: (Math.random() * 100).toString(),
    store: new sessionStore({ checkPeriod: DAY }) as any,
}));

This will initialize a session for each visitor to your app, which is accessible through req.session.

Configure a provider

For any provider you choose, you'll have to set up an "app" on the corresponding developer dashboard. See below for details on how to set this up for each provider.

Redirect URI's

Pretty much every provider requires a redirect URI. This is the URL that the provider will redirect to after the user has authenticated. To save some bytes, I'll just describe the redirect URI here, then you'll use it for all providers. If any providers use a different format, I'll note those differences in their subsection.

  • For local development: http://localhost:8080/accounted4/<provider-name>
  • For production: https://<your-domain.com>/accounted4/<provider-name>

Replace <provider-name> with the name of the provider, as listed below, in lowercase. You do not need a trailing slash. For example: https://awesome-website.com/accounted4/github or http://localhost:8080/accounted4/microsoft.

Providers

Create a Digital Ocean OAuth2 app. For the Callback URL, use the production redirect URI. Once your app is created, Click on More, then View, and copy the Client ID and Client Secret. Visit Digital Ocean's OAuth2 documentation for more information on scopes and other settings.

Create a Discord app. Once your app is created, click the OAuth2 tab and copy the Client ID and reset the Client Secret. Make sure you add both redirect URIs. Visit Discord's documentation for more information on scopes.

Create a GitHub app. For the Authorization callback URL, use the production redirect URI. You do not need to enable Device Flow but you can if you want. Once created, find the Client ID and generate a new Client secret. Copy these for the next step. Visit GitHub's documentation for more information on scopes.

Create a Google Cloud project. Using the search bar, start typing "APIs and Services", then select APIs & Services. Follow these steps to configure your app:

  1. On the left of the dashboard, select OAuth consent screen.
  2. Choose External and click Create.
  3. The next page sets up your app metadata. Enter anything required, but feel free to leave optional items blank.
  4. The next page asks for scopes. If you already know what scopes you require, enter them now. Otherwise, continue. Visit Google's documentation for more information on scopes.
  5. The next page asks for test users. Add yourself and any other Google account you wish to test your app. Make sure to enter the email address of any testers (the email must correspond to a Google account).
  6. If the summary looks good to you, click on Credentials on the left of the dashboard.
  7. Click on + Create credentials, then OAuth client ID.
  8. Choose Web application for the type and give it a name.
  9. Add both redirect URI's from above as Authorized redirect URIs (you don't need any Authorized JavaScript origins).
  10. Click Create. You will be shown your Client ID and Client secret. Copy these for the next step.

Microsoft is quite in-depth, so we'll skip the details here for now. Documentation will be added at a later date.

Create a Spotify app (tutorial). Once your app is created, you should see your Client ID and a button to SHOW your Client secret. Copy these for the next step. Click on Edit Settings and add both redirect URI's. Visit Spotify's documentation for more information on scopes.

Create a Twitch app (tutorial). Make sure to add both redirect URI's. Once your app is created, click Manage. Copy your Client ID and a button to make a New Secret. Copy these for the next step. Visit Twitch documentation for more information on scopes.

Configure accounted4

Finally, we create an instance of Accounted4. Passing the app is required as accounted4 needs to create routes for the OAuth2 provider to call upon for redirects. Support for more than one provider is planned for the future.

You can choose to apply the middleware to specific paths, or to the entire app.

const ac4 = new Accounted4(app, {
    hostname: 'localhost',
    port: 8080,
    defaultProvider: 'Microsoft',
    optionalProviders: ['GitHub'], // ! optionalProviders not yet implemented
    providerOptions: {
        Microsoft: {
            // Required by every provider
            clientId: secrets.MICROSOFT_CLIENT_ID,
            clientSecret: secrets.MICROSOFT_CLIENT_SECRET,

            // Optional for every provider (some have defaults)
            scopes: ['user.read', 'offline_access'], // You can add additional scopes

            // Optional for Microsoft (other providers may have other optional properties)
            tenant: 'consumers',
        },
        GitHub: {
            clientId: secrets.GITHUB_CLIENT_ID,
            clientSecret: secrets.GITHUB_CLIENT_SECRET,
        }
    }
});

app.use(ac4.auth());
// or
app.use('/my-private-zone', ac4.auth());

Now add the rest of your routes and start the app. Visiting any of your routes will redirect the user to the OAuth2 provider. Once they sign in, they'll be redirected back to your app.

Using the providers' API

After successful authentication, accounted4 stores the provider name and access token in the session. You can access these values through the req.session.accounted4 object. This access token can be used with the API of your chosen provider (make sure you include any necessary scopes when configuring the provider).

Next steps

At the moment, that's all there is to it! As development continues, I'll add more docs on usage.

List of providers

To-do

  • [ ] Add providers
  • [ ] Add documentation/tests/examples
  • [ ] Add support for multiple providers
  • [ ] Implement logout
  • [ ] Implement refreshing tokens
  • [ ] Automatic State checking
Disclaimer

accounted4 is set up for OAuth2 Authorization Code Grants. If your project requires a different grant, then this library may not be the right choice. Word of advice: never use implicit grant.