api/session

module:api/session

Description:
  • Session support as possibly encrypted cookie value signed by user's secret.

    Parsed session is stored in the context.session as an object:

    { id: string, exp: number, sig: string }`
    
Source:

Members

(static) header :string

Description:
  • header/cookie name to keep signature

Source:
Default Value:
  • bk-sid

Methods

(static) clear(context)

Description:
  • Expire and clear session cookie for the context, clears context.session

Source:
Parameters:
Name Type Description
context RequestContext

(static) create(context, id, secret, true)

Description:
  • Create a session cookie, the id and exp signed by provided secret, if api.session.secret is defined the signed token is also encrypted and stored as base64

Source:
Parameters:
Name Type Description
context RequestContext
id string

session id

secret string

to use for signing, must be provided

true boolean

if cookies set and context.session is created

Example
const session = session.create(context, user.id, user.secret);

(static) getCookieOptions(context, optionsopt) → {Object}

Description:
  • Find a closest cookie by host/domain/path, longest takes precedence, returns found cookie merged with the options

Source:
Parameters:
Name Type Attributes Description
context RequestContext
options Object <optional>
Returns:
Type Description
Object

(static) parse(context) → {Object|undefined}

Description:
  • Parse session cookies or headers if the successfully parsed it is saved in the context.session

Source:
Parameters:
Name Type Description
context RequestContext
Returns:
Type Description
{id: string, exp: number, sig: string} | undefined

session object if valid and not expired

(static) setCookie(context, value, optionsopt)

Description:
  • Set a cookie by name and domain, the value is encrypted if api.session.secret is defined, Max-Age is set if value is not empty otherwise the cookie set Expires in the past.

Source:
Parameters:
Name Type Attributes Description
context RequestContext
value string | object
options Object <optional>

(static) verify(context, secret, true)

Description:
  • (Parse) and Verify context session signature against given user secret

Source:
Parameters:
Name Type Description
context RequestContext
secret string
true boolean

if verified

Example

simple middleware to verify current sessions against users table, simplified

api.app.use("/portal/*", (context, next) => {
    const session = api.session.parse(context);

    api.users.get(session?.id, (err, user) => {

        if (!api.session.verify(context, user?.id, user?.secret)) {
            return context.reply({ status: 401, message: "invalid session" });
        }
        next();
    });
});