### Hapi.js Cookie Authentication Setup
Source: https://github.com/hapijs/cookie/blob/master/API.md
This snippet demonstrates how to configure a Hapi.js server with cookie-based authentication. It registers the '@hapi/cookie' plugin, defines a session authentication strategy, and sets up routes for a basic login/logout flow.
```javascript
'use strict';
const Hapi = require('@hapi/hapi');
const internals = {};
// Simulate database for demo
internals.users = [
{
id: 1,
name: 'john',
password: 'password',
},
];
internals.renderHtml = {
login: (message) => {
return `
Login page
${message ? '' + message + '
' : ''}
`;
},
home: (name) => {
return `
Login page
Welcome ${name}! You are logged in!
`;
}
};
internals.server = async function () {
const server = Hapi.server({ port: 8000 });
await server.register(require('@hapi/cookie'));
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
// Don't forget to change it to your own secret password!
password: 'password-should-be-32-characters',
// For working via HTTP in localhost
isSecure: false
},
redirectTo: '/login',
validate: async (request, session) => {
const account = internals.users.find((user) => (user.id === session.id));
if (!account) {
// Must return { isValid: false } for invalid cookies
return { isValid: false };
}
return { isValid: true, credentials: account };
}
});
server.auth.default('session');
server.route([
{
method: 'GET',
path: '/',
options: {
handler: (request, h) => {
return internals.renderHtml.home(request.auth.credentials.name);
}
}
},
{
method: 'GET',
path: '/login',
options: {
auth: {
mode: 'try'
},
plugins: {
cookie: {
redirectTo: false
}
},
handler: async (request, h) => {
if (request.auth.isAuthenticated) {
return h.redirect('/');
}
return internals.renderHtml.login();
}
}
},
{
method: 'POST',
path: '/login',
options: {
auth: {
mode: 'try'
},
handler: async (request, h) => {
const { username, password } = request.payload;
if (!username || !password) {
return internals.renderHtml.login('Missing username or password');
}
// Try to find user with given credentials
const account = internals.users.find(
(user) => user.name === username && user.password === password
);
if (!account) {
return internals.renderHtml.login('Invalid username or password');
}
request.cookieAuth.set({ id: account.id });
return h.redirect('/');
}
}
},
{
method: 'GET',
path: '/logout',
options: {
handler: (request, h) => {
request.cookieAuth.clear();
return h.redirect('/');
}
}
}
]);
await server.start();
console.log(`Server started at: ${server.info.uri}`);
};
internals.start = async function() {
try {
await internals.server();
}
catch (err) {
console.error(err.stack);
process.exit(1);
}
};
internals.start();
```
--------------------------------
### hapi/cookie Scheme Configuration
Source: https://github.com/hapijs/cookie/blob/master/API.md
Configures the cookie authentication scheme for hapi.js, including session cookie naming, security settings, expiration, and redirection options.
```APIDOC
hapi/cookie Scheme Configuration Options:
'cookie' - an object with the following:
name: string (default: 'sid') - The cookie name.
password: string - Used for Iron cookie encoding. Must be at least 32 characters long.
ttl: number - Sets the cookie expires time in milliseconds. Defaults to single browser session. Required when keepAlive is true.
domain: string - Sets the cookie Domain value. Defaults to none.
path: string - Sets the cookie path value. Defaults to none.
clearInvalid: boolean (default: false) - If true, invalid cookies are marked expired and cleared.
isSameSite: string (options: 'Strict', 'Lax', false) (default: 'Strict') - Sets the SameSite attribute.
isSecure: boolean (default: true) - If false, cookie is allowed over insecure connections.
isHttpOnly: boolean (default: true) - If false, cookie will not include the 'HttpOnly' flag.
keepAlive: boolean (default: false) - If true, automatically sets the session cookie after validation to extend the session.
redirectTo: string | function (default: no redirection) - Optional login URI or function to redirect unauthenticated requests.
appendNext: boolean | string | object (default: false) - If redirectTo is true, controls appending the current request path to the redirectTo URI.
async validate: function(request, session) - Optional session validation function.
- request: The Hapi request object.
- session: The session object set via request.cookieAuth.set().
- Returns: object with:
- isValid: boolean - true if session is valid, otherwise false.
- credentials: object - Passed to request.auth.credentials. Overrides session if set.
requestDecoratorName: string (default: 'cookieAuth') - Optional name for decorating the request object.
```
--------------------------------
### hapi/cookie Request Decorator Methods
Source: https://github.com/hapijs/cookie/blob/master/API.md
Methods available on the request object when the cookie scheme is enabled, used for managing session data.
```APIDOC
request.cookieAuth Methods:
set(session: object): void
- Sets the current session. Must be called after successful login.
- session: The session object, which is set on subsequent authentications in request.auth.credentials.
set(key: string, value: any): void
- Sets a specific object key on the current session (which must already exist).
```
--------------------------------
### Hapi Cookie Authentication API
Source: https://github.com/hapijs/cookie/blob/master/API.md
Details the methods available on the `request.cookieAuth` object for managing session data within a Hapi.js application using the cookie authentication plugin.
```APIDOC
HapiCookieAuth:
Methods for managing session data via the cookie authentication plugin.
set(session)
- Sets the session data for the authenticated user.
- Parameters:
- session (object): The session data to store. This object will be serialized and stored in the cookie.
- Example:
request.cookieAuth.set({ id: account.id, username: 'john' });
clear([key])
- Clears the current session or a specific session key.
- If no key is provided, the entire session is removed, effectively logging the user out.
- Parameters:
- key (string, optional): The specific session key to remove. If omitted, the entire session is cleared.
- Example (clearing entire session):
request.cookieAuth.clear();
- Example (clearing a specific key):
request.cookieAuth.clear('cart');
ttl(msecs)
- Sets the Time To Live (TTL) for the current active session.
- This determines how long the session remains valid before it expires.
- Parameters:
- msecs (number): The new TTL in milliseconds.
- Example:
request.cookieAuth.ttl(3600000); // Set session TTL to 1 hour
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.