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-sol

v2.1.3

Published

A simpler session based auth plugin for Hapi

Downloads

41

Readme

Hapi-Sol

npm version Build Status codecov License Greenkeeper badge

A Session based auth scheme for Hapi

This scheme is based on hapi-session but the API is a bit diffrent (mostly using async and callback scheme) and most of the underline code has changed. As with the original scheme a lot of the code was gratuitously stolen from the hapi auth cookie scheme, and this module works in much the same way.

This Module will save a cookie with a unique session ID, the ID has high entropy and is randomly secure so it should be impossible to fake. all other data is never sent to the user so you can save in the session whatever information you wont without the fear of it being faked or compromised.

Usage

For Hapi 16.x and lower see previous version For demo server example usage see the server.js

Loading the module

await server.register({plugin: require('hapi-sol')});
server.auth.strategy('session', 'session', {/* Options Object*/});
server.auth.default('session');

handling Login

After validating the user credentials saving them to the cookie is done by the session.set method

await request.auth.session.set({'logined': true, 'userid': 1});
return h.response('You are being redirected...').takeover().redirect('/');

notice this method is asynchronous. once the user is logged in you will have the credentials passed to the set method available in future connections at -

console.log(request.auth.credentials); //{'logined': true, 'userid': 1}

To logout the user you can either call set with null value or call the clear method

await request.auth.session.set(null);
return h.response('You are being redirected...').takeover().redirect('/');
//
await request.auth.session.clear();
return h.response('You are being redirected...').takeover().redirect('/');

the clear method will completely remove the session from cache and create a new one while the set method will leave the current session active but unauthenticated. As with the set method clear is asynchronous.

Synchronous methods on request.auth.session

request.auth.session.getId returns the current session ID

Asynchronous methods on request.auth.session

request.auth.session.getSeesion returns the current session object

request.auth.session.setSeesion(session) save session as the current session object

since clients will always have an active persistent session it can be useful to attach some extra data to the session object

//on failed login attempt
const session = await request.auth.session.getSession();
session.attempts = session.attempts ? session.attempts + 1: 1;
await request.auth.session.setSession(session);
if (session.attempts > 5) {
    //block user ip
}

Notice that the session Object has two internally used properties authenticated Boolean is the true if the session has credentials associated with it. credentials Object credentials saved with the session it better to avoid doing manual changes to this values (use the set method instead) since setSession will not do any validations on your session Object.

Available options

when setting an auth strategy you can set the following options:

  • cookie The cookie name default('sid')
  • sessionCookie use browser session cookies (will only apply ttl settings for built in cache)
  • path The cookie path default('/'')
  • ttl Cookie and cache TTL in milliseconds default(1000 * 60 * 60 * 24 //one day)
  • isHttpOnly Set HTTP only cookie flag default(true)
  • isSecure Force SSL for cookie default(true)
  • secret Secret to be used to create local HMAC of the cookie id can help reduce timing attacks and using stolen cookies default(null)
  • hmacAlgo HMAC algorithm to be used (only used if secret is set) default(sha1)_
  • hmacEncoding HMAC encoding (only used if secret is set) default(base64)_
  • hmacRequest Array of values to be taken from the request that will be included in the HMAC make session harder to steal(only used if secret is set) default(['info.remoteAddress', 'headers.user-agent'])_
  • rlClient rate limiting client to use for rate limiting users who try to bruteforce session ids. you can use ralphi-client or any object which implements query and take methods.
  • rlBucket bucket to use for rate limiting default('session')
  • rlGetKey function/async for getting the rate limiting key from the request default(request => request.info.remoteAddress)
  • rlAddHeaders add rate limiting headers to limited responses default(true)
  • cacheId the cache ID to use when saving sessions default('_hapi_session')
  • cache caching manager if you want to use your own storage (needs to implement get,set and drop methods) default(undefined)
  • validateFunc Async function to farther validate the cookie if needed function signature should be (request, credentials) function should return an array first item is boolean value indicating if credentials are valid, and optional second value can be returned with an object of a parsed credentials to replace the credentials being set in the authentication process default(undefined)
  • clearInvalid If cookie is tested to be invalid by the validateFunc should we clear the existing cookie default(true)
  • sidLength The length in Bytes for the generated random ID Should be high enough so collision would be impossible minimum 10 bytes default(16)
  • uidRetries How many retries should be made to generate the ID (in case of missing entropy) default(5)
  • redirectTo Location to redirect to in case of auth Error default(''//Empty string)
  • appendNext if truthy will add a query parameter with the same name in the redirection url back to the current route boolean true will set the name 'next' default(''//Empty string)
  • redirectOnTry if mode is set to try and auth fails redirect the request default(false)