An open API service indexing awesome lists of open source software.

https://github.com/idiocc/session

Session Middleware for Goa Apps.
https://github.com/idiocc/session

Last synced: 8 months ago
JSON representation

Session Middleware for Goa Apps.

Awesome Lists containing this project

README

          

# @goa/session

[![npm version](https://badge.fury.io/js/%40goa%2Fsession.svg)](https://www.npmjs.com/package/@goa/session)

`@goa/session` is Session Middleware for Goa apps written in ES6 and optimised with [JavaScript Compiler](https://www.compiler.page). It is used in the [Idio web](https://www.idio.cc) server.

```sh
yarn add @goa/session
```

## Fork Diff

This package is a fork of `koa-session` with a number of improvements:

1. The session middleware constructor does not require the app, and will not extend the context with `.session` property, if middleware wasn't explicitly used. Fixes [177](https://github.com/koajs/session/issues/177) to avoid confusion when `.session` is not expected to be present, but is read from cookies anyway.
1. Remove `crc32` hash checking which was unnecessary. Fixes [161](https://github.com/koajs/session/issues/161) as JSON comparison is enough.
1. Fix [the bug](https://github.com/koajs/session/pull/175) when initial `maxAge` is not set on the initial session cookie, resulting in a session-only sessions.



## Table Of Contents

- [Fork Diff](#fork-diff)
- [Table Of Contents](#table-of-contents)
- [API](#api)
- [`session(opts=): !_goa.Middleware`](#sessionopts-sessionconfig-_goamiddleware)
* [`SessionConfig`](#type-sessionconfig)
* [`ExternalStore`](#type-externalstore)
* [`Session`](#type-session)
* [KoaSession](#type-koasession)
- [Typedefs](#typedefs)
- [Usage Events](#usage-events)
- [Copyright & License](#copyright--license)



## API

The package is available by importing its default function:

```js
import session from '@goa/session'
```



## session(
  `opts=: !SessionConfig,`
): !_goa.Middleware
Initialize the session middleware with `opts`.

- opts !SessionConfig (optional): The configuration passed to `koa-session`.

The interface is changed from the original package, so that the app is always passed as the first argument.

__`SessionConfig`__: Configuration for the session middleware.


Name
Type & Description
Default


key
string
koa:sess




The cookie key.



maxAge
(string | number)
86400000




maxAge in ms with default of 1 day. Either a number or 'session'. session will result in a cookie that expires when session/browser is closed. Warning: If a session cookie is stolen, this cookie will never expire.



overwrite
boolean
true




Can overwrite or not.



httpOnly
boolean
true




httpOnly or not.



signed
boolean
true




Signed or not.



autoCommit
boolean
true




Automatically commit headers.



store
ExternalStore
-




You can store the session content in external stores (Redis, MongoDB or other DBs) by passing an instance of a store with three methods (these need to be async functions).



externalKey
{ get: function(_goa.Context): string, set: function(_goa.Context, string): void }
-




When using a store, the external key is recorded in cookies by default, but you can use options.externalKey to customize your own external key methods.



ContextStore
new (arg0: !_goa.Context) => ExternalStore




If your session store requires data or utilities from context, opts.ContextStore can be used to set a constructor for the store that implements the ExternalStore interface.



prefix
string
-




If you want to add prefix for all external session id. It will not work if options.genid(ctx) present.



rolling
boolean
false




Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown.



renew
boolean
false




Renew session when session is nearly expired, so we can always keep user logged in.



valid
(ctx: !_goa.Context, sess: !Object) => boolean




The validation hook: valid session value before use it.



beforeSave
(ctx: !_goa.Context, sess: !KoaSession) => boolean




The hook before save session.



genid
(ctx: !_goa.Context) => string




The way of generating external session id.



encode
(sess: !Object) => string




Use options.encode and options.decode to customize your own encode/decode methods.



decode
(sess: string) => !Object




Use options.encode and options.decode to customize your own encode/decode methods.

**Example**

```js
import aqt from '@rqt/aqt'
import Goa from '@goa/koa'
import session from '@goa/session'

const app = new Goa()
app.keys = ['g', 'o', 'a']
app.use(session({ signed: false })) // normally, signed should be true

app.use((ctx) => {
if (ctx.path == '/set') {
ctx.session.message = 'hello'
ctx.body = 'You have cookies now:'
} else if (ctx.path == '/exit') {
ctx.session = null
ctx.body = 'Bye'
}
else ctx.body = `Welcome back: ${ctx.session.message}`
})

app.listen(async function() {
const { port } = this.address()
const url = `http://localhost:${port}`

// 1. Acquire cookies
let { body, headers } = await aqt(`${url}/set`)
console.log(body, headers, '\n')
const cookie = headers['set-cookie']

// 2. Exploit cookies
;({ body, headers } = await aqt(url, {
headers: {
cookie,
},
}))
console.log(body, headers, '\n')

// 3. Destroy cookies
;({ body, headers } = await aqt(`${url}/exit`, {
headers: {
cookie,
},
}))
console.log(body, headers)

this.close()
})
```
```js
You have cookies now: { 'content-type': 'text/plain; charset=utf-8',
'content-length': '21',
'set-cookie':
[ 'koa:sess=eyJtZXNzYWdlIjoiaGVsbG8iLCJfZXhwaXJlIjoxNTc4NjY2NDgzNjc4LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
date: 'Thu, 09 Jan 2020 14:28:03 GMT',
connection: 'close' }

Welcome back: hello { 'content-type': 'text/plain; charset=utf-8',
'content-length': '19',
date: 'Thu, 09 Jan 2020 14:28:03 GMT',
connection: 'close' }

Bye { 'content-type': 'text/plain; charset=utf-8',
'content-length': '3',
'set-cookie':
[ 'koa:sess=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
date: 'Thu, 09 Jan 2020 14:28:03 GMT',
connection: 'close' }
```

If your session store requires data or utilities from context, `opts.ContextStore` is also supported. _ContextStore_ must be a class which implements three instance methods demonstrated below. `new ContextStore(ctx)` will be executed on every request.

__`ExternalStore`__: By implementing this class, the session can be recorded and retrieved from an external store (e.g., a database), instead of cookies.


Name
Type & Description


constructor
new () => ExternalStore




Constructor method.



get
(key: string, maxAge: (number | string), opts: { rolling: boolean }) => !Promise<!Object>




Get session object by key.



set
(key: string, sess: !Object, maxAge: (number | string), opts: { rolling: boolean, changed: boolean }) => !Promise




Set session object for key, with a maxAge (in ms, or as 'session').



destroy
(key: string) => !Promise




Destroy session for key.

Show an example external store.

```js
const sessions = {}

export default {
async get(key) {
return sessions[key]
},

async set(key, value) {
sessions[key] = value
},

async destroy(key) {
sessions[key] = undefined
},
}
```

The session object itself (`ctx.session`) has the following methods.

__`Session`__: The session instance accessible via Goa's context.

| Name | Type | Description |
| ------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------- |
| __isNew*__ | boolean | Returns true if the session is new. |
| __populated*__ | boolean | Populated flag, which is just a boolean alias of `.length`. |
| __maxAge*__ | (number \| string) | Get/set cookie's maxAge. |
| __save*__ | () => void | Save this session no matter whether it is populated. |
| __manuallyCommit*__ | () => !Promise<void> | Session headers are auto committed by default. Use this if `autoCommit` is set to false. |

KoaSession extends Session: A private session model.


Name
Type & Description


constructor
new (sessionContext: KoaContextSession, obj?: { _maxAge: (number | undefined), _session: (boolean | undefined) }) => KoaSession




Private session constructor. It is called one time per request by the session context when middleware accesses .session property of the context.



_expire
number




Private JSON serialisation.



_requireSave
boolean




Private JSON serialisation.



_sessCtx
KoaContextSession




Private JSON serialisation.



_ctx
_goa.Context




Private JSON serialisation.



## Typedefs

This package is meant to be used as part of the [Idio web server](https://github.com/idiocc/idio). But it also can be used on its own with _Koa_. To enable auto-completions when configuring the middleware, please install typedefs, and import them in your application entry:

Package & LinkImport

@typedefs/goa

[![npm version](https://badge.fury.io/js/%40typedefs%2Fgoa.svg)](https://www.npmjs.com/package/@typedefs/goa)

```js
const sess = session({
// you can access ctx as context now
valid(ctx, obj) {
// force presence of a key in headers too
const s = ctx.get('secret-key')
return obj['secret-key'] == s
}
})
// at the bottom of the file
/**
* @typedef {import('@typedefs/goa').Context} _goa.Context
*/
```

This will add information about required types to VSCode. This is required because even though session's configuration object is described with JSDoc in its file, VSCode has a bug that does not allow propagation of imported types so they need to be imported manually like above.

JSDoc



## Usage Events

This middleware integrates with [_Idio_](https://github.com/idiocc/idio) that collects middleware usage statistics to reward package maintainers. It will emit certain events to bill its usage:

1. `save`: When the session is saved via cookies.
1. `save-external`: When the session is saved via external storage.

The usage is recorded via the `ctx.neoluddite` context property set by a server such as _Idio_. In future, more fine-grained usage events might appear.



## Copyright & License

GNU Affero General Public License v3.0

Affero GPL means that you're not allowed to use this middleware on the web unless you release the source code for your application. This is a restrictive license which has the purpose of defending Open Source work and its creators.

Please refer to the [Idio license agreement](https://github.com/idiocc/idio#copyright--license) for more info on dual-licensing. You're allowed to use this middleware without disclosing the source code if you sign up on [neoluddite.dev](https://neoluddite.dev) package reward scheme.

[Original Work](https://github.com/koajs/session) by dead-horse and contributors under MIT license.




Art Deco


© Art Deco for Idio 2020


Idio




Tech Nation Visa


Tech Nation Visa Sucks