infinity.session¶
Provides functionality for storing authentification information in session data. It supports the JSON Web Token standard, employing the HS256 and RS256 signing algorithms.
Session data is always an object that must contain a non-empty string property id (the property name is not case-sensitive), which is used as the session ID. When starting a session within an HTTP request handler (a custom handler script or a service method registered with httpEnvironment: true), INFINITY.JS will automatically return a cookie called SID in the response headers and will also automatically handle that cookie in subsequent requests and be able to restore the session from that ID. If you don't want to rely on the cookie, you can also send the session ID in the HTTP Authorization: Bearer header, passing the session ID in as a bearer token. A third alternative is to pass the session ID as a query parameter called SID in an HTTP request. JWT sessions (see algorithm) are not stored in a cookie; the token is expected in the Authorization: Bearer header or in a query parameter called JWT.
The functions get(), getId(), start() and remove() use the request context of the script they are called in. Outside of a request context (e.g. in the main script), get() and getId() return undefined.
Module: infinity.session
Example (script of a custom handler):
infinity.loadModule('infinity.session');
infinity.loadModule('infinity.crypto');
infinity.session.expires = 3600;
let session: any = infinity.session.get();
if (!session) {
session = {id: infinity.random.characters(32), userId: 1, userName: 'tf'};
infinity.session.start(session); // sets the SID cookie in the response
}
infinity.http.response.contentType = 'application/json';
infinity.http.response.contentText = JSON.stringify(session);
objectArray¶
Extends: Array<object>
An array containing objects.
stringArray¶
Extends: Array<string>
An array containing strings.
clear()¶
Removes all sessions from the session storage.
Signature:
clear(): void
Example:
infinity.loadModule('infinity.session');
infinity.session.clear();
exists()¶
Reports whether a session with the specified ID is present inside the session storage. Does not consider expiration settings (expired sessions are only removed by flushExpired()).
Signature:
exists( id: string ): boolean
Parameters:
- id:
stringThe session ID.
Return type: boolean
Example:
infinity.loadModule('infinity.session');
if ( infinity.session.exists(id) ) {
//...
}
flushExpired()¶
Removes expired sessions (sessions that have not been accessed for more than expires seconds) from the session storage and returns the data of the removed sessions. The check is performed at most every 10 seconds; calls within 10 seconds after the last check return an empty array.
Signature:
flushExpired(): objectArray
Return type: objectArray
Example:
infinity.loadModule('infinity.session');
let x = infinity.session.flushExpired();
get()¶
Returns the data of the session of the current request and updates the last access time of the session. Does not consider expiration settings. In an HTTP request context, INFINITY.JS will automatically look for a session ID in the Authorization: Bearer header, the SID cookie or the SID query parameter (in this order). If it finds a valid session ID, it will return the session data. If it doesn't find a session ID or there is no session by that ID, then it will return undefined. In a WebSocket or TCP connection context (e.g. infinity.http2 message scripts), the session of the connection is returned. Outside of a request context, undefined is returned.
Signature:
get( algorithm?: infinity.session.algorithm, checkIfSessionExists?: boolean ): object
Parameters:
-
algorithm:
infinity.session.algorithm, optionalOnly in HTTP request contexts. If this parameter is given, the session is read from a JSON Web Token in the
Authorization: Bearerheader or theJWTquery parameter, which is verified with the given algorithm and thesecret. The token contains the actual session data, so that sessions can be shared across servers in a distributed server environment. -
checkIfSessionExists:
boolean, optional, default:trueWhen using JWT sessions (by specifying a JWT algorithm as the first parameter), then this parameter controls whether session data is returned on all servers or only on the server that actually started the session. Setting the parameter to
true(the default value) will not return session data unless the script is running on the server that actually started the session, thus mimicking non-distributed sessions. It set tofalse, then the session data from the JWT session ID will be returned on all servers, thus acting as a distributed session. Note that in both cases the session's last access timestamp will only be updated when this function is called on the server that started the session, as other servers don't actually contain the session, but take the session data from the session ID.
Return type: object
Example:
infinity.loadModule('infinity.session');
let session = infinity.session.get();
getDataList()¶
Returns the data out of all stored sessions as an objectArray.
Signature:
getDataList(): objectArray
Return type: objectArray
Example:
infinity.loadModule('infinity.session');
let sessionData = infinity.session.getDataList();
getId()¶
Returns the session ID sent with the current HTTP request in the specified way (an empty string if no session ID was sent that way). Does not check whether the session exists. Outside of an HTTP request context, undefined is returned.
Signature:
getId( authKind: infinity.session.authKind ): string
Parameters:
- authKind:
infinity.session.authKindWhere to read the session ID from:
Authorization: Bearerheader,SIDcookie orSIDquery parameter.
Return type: string
Example:
infinity.loadModule('infinity.session');
let id = infinity.session.getId(infinity.session.authKind.cookie);
getIdList()¶
Returns the IDs out of all stored sessions as a stringArray.
Signature:
getIdList(): stringArray
Return type: stringArray
Example:
infinity.loadModule('infinity.session');
let sessionIds = infinity.session.getIdList();
put()¶
Replaces the data of the session whose ID matches the id property of the provided data and updates the last access time of the session. Does nothing if no such session exists. Throws an error if the data has no id property.
Signature:
put( sessionData: object ): void
Parameters:
- sessionData:
objectData to serve as the replacement. Must contain the
idproperty of the session.
Example:
infinity.loadModule('infinity.session');
let sessionId = infinity.session.start({'id': '123', 'name': 'TestName'});
infinity.session.put({'id': sessionId, 'name': 'OtherName'});
remove()¶
Removes a session from the session storage. If an ID is given, the session with this ID is removed. Otherwise the session of the current request (HTTP request, WebSocket or TCP connection) is removed. In an HTTP request context, the SID cookie is cleared in the response.
Signature:
remove( id?: string, algorithm?: infinity.session.algorithm ): void
Parameters:
-
id:
string, optionalRemoves the session with the specified ID. Pass an empty string or
undefinedto remove the session of the current request. -
algorithm:
infinity.session.algorithm, optionalOnly in HTTP request contexts and without
id: removes the session referenced by the JSON Web Token of the request, verified with this algorithm.
Example:
infinity.loadModule('infinity.session');
infinity.session.remove();
start()¶
Starts a session with the provided data (or replaces the data of an existing session with the same ID) and returns the session ID. The data must come inside an object and contain a non-empty string property id, otherwise an error is thrown.
- In an HTTP request context without
algorithm: theidof the data is used as session ID and theSIDcookie is set in the response (expires after one day). - In an HTTP request context with
algorithm: the session is stored under theidof the data and a signed JSON Web Token containing the session data is returned instead of the ID (no cookie is set). - In a WebSocket or TCP connection context: the session ID is derived from the connection.
- Outside of a request context: the
idof the data is used as session ID.
Note: when starting a session using the start function, this session will not be returned by the get function until the next client request. The infinity.session.get method fetches the session from cookie, query parameter or request header data and this will only be available after the client has received the session ID and included it in its next request.
Signature:
start( data: object, algorithm?: infinity.session.algorithm ): string
Parameters:
-
data:
objectAn object containing session data, including the
idproperty. -
algorithm:
infinity.session.algorithm, optionalOnly in HTTP request contexts: the algorithm for signing the JSON Web Token.
Return type: string
Example:
infinity.loadModule('infinity.session');
let sessionId = infinity.session.start({'id': '123', 'name': 'TestName'});
expires¶
Type: number
Specifies, how many seconds after its last access a session should be considered as valid (used by flushExpired()). Default: 60.
secret¶
Type: string
The key used to sign and verify JSON Web Token sessions (HMAC key for hs256, RSA key for rs256). Default: ''.
infinity.session.algorithm¶
Values:
-
none:
0Regular, non-distributed session (without storing session data inside the session token). Passing
noneto start(), get() or remove() is the same as omitting the algorithm (up to 3.10,start()returned an unsigned JWT andget()accepted unsigned tokens). -
hs256:
1JWT session, using the HMAC algorithm with SHA-256. In this case, every server will share the same key.
-
rs256:
2JWT session, using an RSA Signature with SHA-256. In this case, every server will have its own key.
Example:
infinity.loadModule('infinity.session');
let algorithm = infinity.session.algorithm.hs256;
infinity.session.authKind¶
Values:
-
bearer:
0The session ID is sent in the
Authorization: BearerHTTP-header. -
cookie:
1The session ID is sent in the
SIDcookie. -
queryParam:
2The session ID is sent in the
SIDquery parameter.
Example:
infinity.loadModule('infinity.session');
let authKind = infinity.session.authKind.cookie;