Skip to content

Commit

Permalink
Merge pull request #10 from spumko/feature/hapi.16
Browse files Browse the repository at this point in the history
v0.2.0
  • Loading branch information
thegoleffect committed Apr 3, 2013
2 parents 8f7d712 + a19de2d commit b3c64f4
Show file tree
Hide file tree
Showing 12 changed files with 701 additions and 949 deletions.
108 changes: 25 additions & 83 deletions README.md
@@ -1,7 +1,7 @@
<a href="https://github.com/spumko"><img src="https://raw.github.com/spumko/spumko/master/images/from.png" align="right" /></a>
![yar Logo](https://raw.github.com/spumko/yar/master/images/yar.png)

A [**hapi**](https://github.com/spumko/hapi) cookie jar
A [**hapi**](https://github.com/spumko/hapi) session plugin and cookie jar

[![Build Status](https://secure.travis-ci.org/spumko/yar.png)](http://travis-ci.org/spumko/yar)

Expand All @@ -14,118 +14,60 @@ A [**hapi**](https://github.com/spumko/hapi) cookie jar

## Usage

The ***yar*** plugin adds a simple way to set a persistant state (using an [Iron](https://github.com/hueniverse/iron) encrypted cookie) across requests.
It has support for session management - either stored on the client via cookie, in server memory, or using an external database (via custom storage code).
The ***yar*** [hapi](https://github.com/spumko/hapi) plugin adds session support - a persistant state across multiple browser requests using an [iron](https://github.com/hueniverse/iron) encrypted cookie and server-side storage. **yar** tries to fit session data into a session cookie based on a configured maximum size. If the content is too big to fit, it uses local storage via the hapi cache interface (or a [catbox](https://github.com/spumko/catbox) compatible store).

For example, the first handler sets the jar content and the second utilizes it:
For example, the first handler sets a session key and the second gets it:
```javascript
var handler1 = function () {

this.plugins.yar = {
key: 'value'
};

this.session.set('example', { key: 'value' };
return this.reply();
};

var handler2 = function () {

this.reply(this.state.yar.key); // Will send back 'value'
var example = this.session.get('example');
this.reply(example.key); // Will send back 'value'
};
```
The plugin requires a password for encryption, and the `ext` permission:
```javascript
var options = {
permissions: {
ext: true // Required
},
plugin: {
name: 'yar' , // Optional, overrides cookie name. Defaults to 'yar'. Doesn't affect 'plugins.yar'.
isSingleUse: false, // Optional, clears jar after one request. Defaults to false.
cookieOptions: {
password: 'password', // Required
isSecure: true // Optional, any supported cookie options except `encoding`
}
cookieOptions: {
password: 'password'
}
};

var server = new Hapi.Server();

server.plugin().require('yar', options, function (err) { });
server.plugin.allow({ ext: true }).require('yar', options, function (err) { });
```
## API Reference
### Options
- `name` - determines what name to use for the cookie and module references. Defaults to _yar_. Should not have to modify this unless it conflicts with another plugin named yar.
- `isSingleUse` - determines whether the cookie should be deleted on next request. Defaults to _false_.
- `cookieOptions` - the configuration for cookie-specific features
- `password` - (Required) used to hash and secure the cookie data
- `name` - determines the name of the cookie used to store session information. Defaults to _session_.
- `ttl` - server-side storage expiration (defaults to 1 day). Not used with custom storage.
- `maxCookieSize` - maximum cookie size before using server-side storage. Defaults to 1K. Set to zero to always use server-side storage.
- `storage` - Catbox-compatible storage to be used instead of the hapi internal cache.
- `cookieOptions` - the configuration for cookie-specific features:
- `password` - (Required) used to encrypt and sign the cookie data.
- `path` - determines the cookie path. Defaults to _'/'_.
- `isSecure` - determines whether or not to transfer using TLS/SSL. Defaults to _false_.
- `session` - determines whether to enable the more robust session features (any non false-y values will enable it). Defaults to _false_.
- `key` - determines how to access the `request.session` object. Defaults to _'session'_.
- `sidKey` - determines what key to use for storing session id in session object. Defaults to _'sid'_.
- `startKey` - determines what key to use for storing server start time in session object (used for identifying stale cookies). Defaults to _'sst'_.
- `maxLen` - determines the maximum string length allowed in a cookie before falling back to MemoryStore
- `store` - setting this to an MemoryStore compatible interface will allow session data to be stored externally. Defaults to _null_.


### Sessions

More robust session support is included in yar but it is not enabled by default. To enable, simple set the plugin option session to true:

```javascript
var options = {
"cookieOptions": {
"password": "worldofwalmart"
},
"session": true
};
```
- `isSecure` - determines whether or not to transfer using TLS/SSL. Defaults to _true_.
#### Methods
This will enable several request-level methods and parameters:

* request.session
* request.flash

##### request.session

Session support will enable the `request.session` object. Modifications to this object will persist between requests for a given user. The objects are not shared between users. The objects are stored entirely within the user cookie **UNLESS** the size exceeds `session.maxLen` - at which point, they will be stored on the server in RAM.

**Basic example**

```javascript
server.addRoute({
method: 'GET',
path: '/',
config: {
handler: function (request) {

if (!request.session.loggedIn) {
request.session.loggedIn = true; // logging you in
request.reply.redirect('/').send();
}
else {
request.reply("You are logged in");
}
}
}
});
```

##### request.flash(type, message)

Session support will also enable the `flash` function. The flash function is used to store volatile data - data that should be deleted once read.

When given no arguments, it will return all of the flash messages and delete the originals.

When given only a type, it will return all of the flash messages of that type and delete the originals.
**yar** adds the `session` property to every request object and initializes the `session.id` on the first request from each browser. The `request.session` interface provides the following methods:
When given a type and a message, it will set or append that message to the given type.
- `reset()` - clears the session and assigns a new session id.
- `set(key, value)` - assigns a value (string, object, etc) to a given key which will persist across requests.
- `set(keysObject)` - assigns values to multiple keys using each 'keysObject' top-level property.
- `get(key, clear)` - retreive value using a key. If 'clear' is 'true', key is cleared on return.
- `clear(key)` - clears key.
- `touch()` - Manually notify the session of changes (when using `get()` and changing the content of the returned reference directly without calling `set()`).
- `flash(type, message, isOverride)` - stores volatile data - data that should be deleted once read. When given no arguments, it will return all of the flash messages and delete the originals. When given only a type, it will return all of the flash messages of that type and delete the originals. When given a type and a message, it will set or append that message to the given type. 'isOverride' used to indicate that the message provided should replace any existing value instead of being appended to it (defaults to false).
- `lazy(enabled)` - if set to 'true', enables lazy mode. In lazy mode, `request.session` can be modified directly (e.g. setting `request.session.myKey` to an object value), and those keys will be stored and loaded back. Lazy mode isn't as fast as the normal get/set because it has to store the session state on every responses regardless of any changes being made.
17 changes: 7 additions & 10 deletions examples/session/index.js → examples/index.js
Expand Up @@ -3,16 +3,13 @@ var Hapi = require('hapi');
var server = new Hapi.Server(process.env.PORT || 8080);

var options = {
// name: 'yar' , // Optional, overrides cookie name. Defaults to 'yar'. Doesn't affect 'plugins.yar'.
// isSingleUse: false, // Optional, clears jar after one request. Defaults to false.
cookieOptions: {
password: 'password', // Required
// isSecure: true // Optional, any supported cookie options except `encoding`
},
session: true
isSecure: false // Required if using http
}
};

server.plugin().allow({ ext: true }).require('yar', options, function (err) {
server.plugin.allow({ ext: true }).require('../', options, function (err) {

if (err) {
console.log(err)
Expand All @@ -26,7 +23,7 @@ server.route({
config: {
handler: function (request) {

request.reply(request.session)
request.reply(request.session._store)
}
}
});
Expand All @@ -37,7 +34,7 @@ server.route({
config: {
handler: function (request) {

request.session.test = 1;
request.session.set('test', 1);
request.reply.redirect('/').send();
}
}
Expand All @@ -49,7 +46,7 @@ server.route({
config: {
handler: function (request) {

request.session[request.params.key] = request.params.value;
request.session.set(request.params.key, request.params.value);
request.reply.redirect('/').send();
}
}
Expand All @@ -61,7 +58,7 @@ server.route({
config: {
handler: function (request) {

request.session = {};
request.session.reset();
request.reply.redirect('/').send();
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/session/package.json → examples/package.json
Expand Up @@ -7,6 +7,6 @@
"license": "BSD",
"dependencies": {
"yar": "0.1.x",
"hapi": "0.14.x"
"hapi": "0.15.x"
}
}

0 comments on commit b3c64f4

Please sign in to comment.