{"_id":"@arve.knudsen/hapi-auth-cookie","_rev":"1-94a378cbcf5207fabd07a421e9711ab4","name":"@arve.knudsen/hapi-auth-cookie","description":"Cookie authentication plugin","dist-tags":{"latest":"7.0.0"},"versions":{"7.0.0":{"name":"@arve.knudsen/hapi-auth-cookie","description":"Cookie authentication plugin","version":"7.0.0","repository":{"type":"git","url":"git://github.com/aknuds1/hapi-auth-cookie.git"},"main":"lib/index.js","keywords":["hapi","plugin","auth","cookie","session"],"engines":{"node":">=8.9.x"},"dependencies":{"boom":"7.x.x","bounce":"1.x.x","hoek":"5.x.x","joi":"13.x.x"},"peerDependencies":{"hapi":">=17.x.x"},"devDependencies":{"code":"5.x.x","hapi":"17.x.x","lab":"15.x.x"},"scripts":{"test":"lab -a code -t 100 -L","test-cov-html":"lab -a code -r html -o coverage.html"},"license":"BSD-3-Clause","gitHead":"d5ec5be8b2408a7b1fa3c5e0341f7e08bf842ddd","bugs":{"url":"https://github.com/aknuds1/hapi-auth-cookie/issues"},"homepage":"https://github.com/aknuds1/hapi-auth-cookie#readme","_id":"@arve.knudsen/hapi-auth-cookie@7.0.0","_npmVersion":"5.5.1","_nodeVersion":"9.2.0","_npmUser":{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"},"dist":{"integrity":"sha512-bOIA+KnF5MCx6lFXBugMBpHp4EJ3ANXs4grUzjAjhEkHfw8EpvDYcbHYcXO7dUQGHNlXjzvaVoO/EwCh2LDNQw==","shasum":"163054ed902d5f6e848cc2acb98a83e32a946756","tarball":"https://registry.npmjs.org/@arve.knudsen/hapi-auth-cookie/-/hapi-auth-cookie-7.0.0.tgz","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDabXNFIa7pN5H1qsyoe05SPWDTgVq2jX0jimXV4r2GVAIhAJV8lPVujVc7Eduu27/JJWEcN+rjivRlZcXEqRxkKgwD"}]},"maintainers":[{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/hapi-auth-cookie-7.0.0.tgz_1511546280095_0.31322075286880136"}}},"readme":"### hapi-auth-cookie\n\n[**hapi**](https://github.com/hapijs/hapi) Cookie authentication plugin\n\n[![Build Status](https://secure.travis-ci.org/hapijs/hapi-auth-cookie.png)](http://travis-ci.org/hapijs/hapi-auth-cookie)\n\nLead Maintainer: [James Weston](https://github.com/jaw187)\n\nCookie authentication provides simple cookie-based session management. The user has to be\nauthenticated via other means, typically a web form, and upon successful authentication\nthe browser receives a reply with a session cookie. The cookie uses [Iron](https://github.com/hueniverse/iron) to encrypt and sign the session content.\n\nSubsequent requests containing the session cookie are authenticated and validated via the provided `validateFunc` in case the cookie's encrypted content requires validation on each request.\n\nIt is important to remember a couple of things:\n\n1. Each cookie operates as a bearer token and anyone in possession of the cookie content can use it to impersonate its true owner.\n2. Cookies have a practical maximum length. All of the data you store in a cookie is sent to the browser. If your cookie is too long, browsers may not set it. Read more [here](http://webdesign.about.com/od/cookies/f/web-cookies-size-limit.htm) and [here](http://www.ietf.org/rfc/rfc2965.txt). If you need to store more data, store a small amount of identifying data in the cookie and use that as a key to a server-side cache system.\n\nThe `'cookie`' scheme takes the following options:\n\n- `cookie` - the cookie name. Defaults to `'sid'`.\n- `password` - used for Iron cookie encoding. Should be at least 32 characters long.\n- `ttl` - sets the cookie expires time in milliseconds. Defaults to single browser session (ends\n  when browser closes). Required when `keepAlive` is `true`.\n- `domain` - sets the cookie Domain value. Defaults to none.\n- `path` - sets the cookie path value. Defaults to `/`.\n- `clearInvalid` - if `true`, any authentication cookie that fails validation will be marked as\n  expired in the response and cleared. Defaults to `false`.\n- `keepAlive` - if `true`, automatically sets the session cookie after validation to extend the\n  current session for a new `ttl` duration. Defaults to `false`.\n- `isSameSite` - if `false` omitted. Other options `Strict` or `Lax`. Defaults to `Strict`.\n- `isSecure` - if `false`, the cookie is allowed to be transmitted over insecure connections which\n  exposes it to attacks. Defaults to `true`.\n- `isHttpOnly` - if `false`, the cookie will not include the 'HttpOnly' flag. Defaults to `true`.\n- `redirectTo` - optional login URI to redirect unauthenticated requests to. Note that using\n  `redirectTo` with authentication mode `'try'` will cause the protected endpoint to always\n  redirect, voiding `'try'` mode. To set an individual route to use or disable redirections, use\n  the route `plugins` config (`{ config: { plugins: { 'hapi-auth-cookie': { redirectTo: false } } } }`).\n  Defaults to no redirection.\n- `appendNext` - if `true` and `redirectTo` is `true`, appends the current request path to the\n  query component of the `redirectTo` URI using the parameter name `'next'`. Set to a string to use\n  a different parameter name. Defaults to `false`.\n- `redirectOnTry` - if `false` and route authentication mode is `'try'`, authentication errors will\n  not trigger a redirection. Defaults to `true`;\n- `await validateFunc` - an optional session validation function used to validate the content of the\n  session cookie on each request. Used to verify that the internal session state is still valid\n  (e.g. user account still exists). The function has the signature `function(request, session)`\n  where:\n    - `request` - is the Hapi request object of the request which is being authenticated.\n    - `session` - is the session object set via `request.cookieAuth.set()`.\n\n  Must return an object that contains:\n    - `valid` - `true` if the content of the session is valid, otherwise `false`.\n    - `credentials` - a credentials object passed back to the application in\n      `request.auth.credentials`. If value is `null` or `undefined`, defaults to `session`. If\n      set, will override the current cookie as if `request.cookieAuth.set()` was called.\n- `requestDecoratorName` - *USE WITH CAUTION* an optional name to use with decorating the `request` object.  Defaults to `'cookieAuth'`.  Using multiple decorator names for separate authentication strategies could allow a developer to call the methods for the wrong strategy.  Potentially resulting in unintended authorized access.\n\nWhen the cookie scheme is enabled on a route, the `request.cookieAuth` objects is decorated with\nthe following methods:\n- `set(session)` - sets the current session. Must be called after a successful login to begin the\n  session. `session` must be a non-null object, which is set on successful subsequent\n  authentications in `request.auth.credentials` where:\n    - `session` - the session object.\n- `set(key, value)` - sets a specific object key on the current session (which must already exist)\n  where:\n    - `key` - session key string.\n    - `value` - value to assign key.\n- `clear([key])` - clears the current session or session key where:\n    - `key` - optional key string to remove a specific property of the session. If none provided,\n      defaults to removing the entire session which is used to log the user out.\n- `ttl(msecs)` - sets the ttl of the current active session where:\n    - `msecs` - the new ttl in milliseconds.\n\nBecause this scheme decorates the `request` object with session-specific methods, it cannot be\nregistered more than once.\n\n```javascript\n'use strict';\n\nconst Hapi = require('hapi');\n\nlet uuid = 1;       // Use seq instead of proper unique identifiers for demo only\n\nconst users = {\n    john: {\n        id: 'john',\n        password: 'password',\n        name: 'John Doe'\n    }\n};\n\nconst home = (request, h) => {\n\n    return '<html><head><title>Login page</title></head><body><h3>Welcome ' +\n      request.auth.credentials.name +\n      '!</h3><br/><form method=\"get\" action=\"/logout\">' +\n      '<input type=\"submit\" value=\"Logout\">' +\n      '</form></body></html>';\n};\n\nconst login = async (request, h) => {\n\n    if (request.auth.isAuthenticated) {\n        return h.redirect('/');\n    }\n\n    let message = '';\n    let account = null;\n\n    if (request.method === 'post') {\n\n        if (!request.payload.username ||\n            !request.payload.password) {\n\n            message = 'Missing username or password';\n        }\n        else {\n            account = users[request.payload.username];\n            if (!account ||\n                account.password !== request.payload.password) {\n\n                message = 'Invalid username or password';\n            }\n        }\n    }\n\n    if (request.method === 'get' ||\n        message) {\n\n        return '<html><head><title>Login page</title></head><body>' +\n            (message ? '<h3>' + message + '</h3><br/>' : '') +\n            '<form method=\"post\" action=\"/login\">' +\n            'Username: <input type=\"text\" name=\"username\"><br>' +\n            'Password: <input type=\"password\" name=\"password\"><br/>' +\n            '<input type=\"submit\" value=\"Login\"></form></body></html>';\n    }\n\n    const sid = String(++uuid);\n\n    await request.server.app.cache.set(sid, { account }, 0);\n    request.cookieAuth.set({ sid });\n\n    return h.redirect('/');\n};\n\nconst logout = (request, h) => {\n\n    request.cookieAuth.clear();\n    return h.redirect('/');\n};\n\nconst server = Hapi.server({ port: 8000 });\n\nexports.start = async () => {\n\n    await server.register(require('../'));\n\n    const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });\n    server.app.cache = cache;\n\n    server.auth.strategy('session', 'cookie', {\n        password: 'password-should-be-32-characters',\n        cookie: 'sid-example',\n        redirectTo: '/login',\n        isSecure: false,\n        validateFunc: async (request, session) => {\n\n            const cached = await cache.get(session.sid);\n            const out = {\n                valid: !!cached\n            };\n\n            if (out.valid) {\n                out.credentials = cached.account;\n            }\n\n            return out;\n        }\n    });\n\n    server.auth.default('session');\n\n    server.route([\n        { method: 'GET', path: '/', config: { handler: home } },\n        { method: ['GET', 'POST'], path: '/login', config: { handler: login, auth: { mode: 'try' }, plugins: { 'hapi-auth-cookie': { redirectTo: false } } } },\n        { method: 'GET', path: '/logout', config: { handler: logout } }\n    ]);\n\n    await server.start();\n\n    console.log('Server ready');\n};\n\nexports.start().catch((err) => {\n\n    console.log(err.stack);\n    process.exit(1);\n});\n```\n","maintainers":[{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"}],"time":{"modified":"2022-04-04T15:41:14.136Z","created":"2017-11-24T17:58:01.129Z","7.0.0":"2017-11-24T17:58:01.129Z"},"homepage":"https://github.com/aknuds1/hapi-auth-cookie#readme","keywords":["hapi","plugin","auth","cookie","session"],"repository":{"type":"git","url":"git://github.com/aknuds1/hapi-auth-cookie.git"},"bugs":{"url":"https://github.com/aknuds1/hapi-auth-cookie/issues"},"license":"BSD-3-Clause","readmeFilename":"README.md"}