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

hapi-doorkeeper

v0.14.1

Published

User authentication for web servers

Downloads

10

Readme

hapi-doorkeeper Build status for hapi Doorkeeper

User authentication for web servers

This hapi plugin adds a secure login and logout system to your app by integrating Auth0.

Contents

Why?

  • User auth is a necessity for most apps and websites.
  • User auth is difficult to do correctly on your own.
  • Secure systems should be easy to set up and use.
  • Comes with built-in login and logout routes.

Install

npm install hapi-doorkeeper

Usage

Register the plugin on your server to add the /login and /logout routes, as well as the session strategy so that you can protect your app's routes with authentication.

const hapi = require('@hapi/hapi');
const bell = require('@hapi/bell');
const cookie = require('@hapi/cookie');
const doorkeeper = require('hapi-doorkeeper');

const server = hapi.server();

const init = async () => {
    await server.register([bell, cookie, {
        plugin  : doorkeeper,
        options : {
            sessionSecretKey : process.env.SESSION_SECRET_KEY,
            auth0Domain      : process.env.AUTH0_DOMAIN,
            auth0PublicKey   : process.env.AUTH0_PUBLIC_KEY,
            auth0SecretKey   : process.env.AUTH0_SECRET_KEY
        }
    }]);
    server.route({
        method : 'GET',
        path   : '/dashboard',
        config : {
            auth : {
                strategy : 'session',
                mode     : 'required'
            }
        },
        handler(request) {
            const { user } = request.auth.credentials;
            return `Hi ${user.name}, you are logged in! Here is the profile from Auth0: <pre>${JSON.stringify(user.raw, null, 4)}</pre> <a href="/logout">Click here to log out</a>`;
        }
    });
    await server.start();
    console.log('Server ready:', server.info.uri);
};

init();

In the example above, only logged in users are able to access /dashboard, as denoted by the session strategy being required. If you are logged in, it will display your profile, otherwise it will redirect you to a login screen and after you log in it will redirect you back to /dashboard.

Authentication is managed by Auth0. A few steps are required to finish the integration.

  1. Sign up for Auth0
  2. Set up an Auth0 Application
  3. Provide credentials from Auth0

After users log in, a session cookie is created for them so that the server remembers them on future requests. The cookie is stateless, encrypted, and secured using flags such as HttpOnly. The user's Auth0 profile is automatically retrieved and stored in the session when they log in. You can access the profile data at request.auth.credentials.user. See hapi-auth-cookie and iron for details about the cookie implementation and security.

Note that your server must support HTTPS for everything to work properly. If you need help with that, see this How To Guide.

APIs can also be protected by the session strategy. Clients can send an Accept header with a value of application/json to indicate that they would prefer a JSON error instead of a redirect to the login page for users who are not logged in. The client can use this to show an error message or redirect the user manually, as appropriate.

API

Routes

Standard user authentication routes are added to your server when the plugin is registered.

GET /login

Tags: user, auth, session, login

Begins a user session. If a session is already active, the user will be given the opportunity to log in with a different account.

If users deny access to a social account, they will be redirected back to the login page so that they may try again, because they probably clicked the wrong account or provider by accident. Other login errors will be returned to the client with a 401 Unauthorized status. You may use hapi-error-page or onPreResponse to display beautiful HTML pages for them.

After logging in, users are redirected to the URL specified in the next query parameter, which defaults to /, the root of the server.

As an example, the login button on your FAQ page might look be written as <a href="/login?next=/faq">Log in</a>.

Only relative URLs are allowed in next for security reasons.

Routes that use the session strategy to require login have the next parameter set automatically for them, so that users are always sent back to the correct place.

GET /logout

Tags: user, auth, session, logout

Ends a user session. Safe to visit regardless of whether a session is active or the validity of the user's credentials. After logging out, users will be redirected to the URL specified in the next query parameter, which defaults to / (see /login for details).

Plugin options

sessionSecretKey

Type: string

A passphrase used to secure session cookies. Should be at least 32 characters long and occasionally rotated. See Iron for details.

auth0Domain

Type: string

The domain used to log in to Auth0. This should be the domain of your tenant (e.g. my-company.auth0.com) or your own custom domain (e.g. auth.my-company.com).

auth0PublicKey

Type: string

The ID of your Auth0 Application, sometimes referred to as the Client ID.

auth0SecretKey

Type: string

The secret key of your Auth0 Application, sometimes referred to as the Client Secret.

providerParams(request)

Type: function Default: Forward some query params from /login to Auth0

An optional event handler that receives an incoming request to the /login route and should return an object of query parameters to send to Auth0. See the providerParams option in bell for details.

By default, we forward screen as screen_hint and user as login_hint. Because Auth0's hosted login page has special behavior based on those parameters, if you visit /[email protected], then on the log in screen [email protected] will be prefilled as the email address to log in with. Similarly, /login?screen=signup will cause the sign up page to display instead of log in. This makes it easy to implement "Log In" and "Sign Up" buttons on your website that go directly to the correct screen.

For details on these parameters, see Auth0's documentation on the New Universal Login Experience.

validateFunc(request, session)

Type: function

An optional event handler where you can put business logic to check and modify the session on each request. See the validateFunc option in hapi-auth-cookie for details.

This is a good place to set authorization scopes for users, if you need to restrict access to some routes for certain users.

Related

  • lock - UI widget used on the login page

Contributing

See our contributing guidelines for more details.

  1. Fork it.
  2. Make a feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request.

License

MPL-2.0 © Seth Holladay

Go make something, dang it.