Skip to content

Session

MARS Engine supports managing user sessions through the session() function and related helpers.

Start session

Sessions are generated by invoking session(). It returns a session ID (sid):

js
const sid = session();
write('sid', sid);

Example response:

json
{
  "sid": "axYwOu94Nn0mfH61yPpk8ch7ucDYasp9"
}

Saving data in session

To store data in a session, call session() with two parameters: a key and a value.

js
const sid = session();
const time = new Date();
session('time', time);
write('sid', sid);

Accessing session data

To continue a session, the client must send the session ID (sid) via:

  • Query parameter named sid
  • HTTP body parameter sid
  • HTTP Header X-MARS-SID

MARS automatically processes the session ID.

You can retrieve stored data with:

js
const time = session('time');
write('time', time);

Example output if session is valid:

json
{
  "time": "Mon Sep 24 11:01:44 UTC 2018"
}

If there is no active session, session() returns null:

json
{
  "time": null
}

Closing session

Sessions automatically expire 30 minutes after the last activity. You can also close them manually:

js
session.close();

Using session.getTime()

You can retrieve the session timestamp in milliseconds since January 1, 1970:

js
const sessionTime = session.getTime();
write('sessionTime', sessionTime);

const dateTime = new Date(sessionTime);
write('dateTime', dateTime);

Iterating over all sessions

You can iterate through all active sessions with forEach():

js
let callbackIndex = 0;

function callback(sessionInstance) {
  // Process each session
  ++callbackIndex;
  write("session_" + callbackIndex, sessionInstance);
}

session.forEach(callback);

Full Example

Login

js
let email = param('email');
let password = param('password');

if(email == null || password == null){
  write('message', 'missing parameter');
  exit();
}

let user = db.query('SELECT * FROM users WHERE usr_email = ?', email);

if(user.length == 0){
  write('message', 'no user with that email');
  exit();
}

user = user[0];

const passwordMatches = bcrypt(password, user.usr_password);
if(passwordMatches){
  let sid = session();            // Start session
  session('user data', user);     // Save user data in session
  write('message', 'user logged in');
  write('sid', sid);
} else {
  write('message', 'wrong password');
}

Checking session from other APIs

js
const user_data = session('user data');
if(user_data == null){
  write('message', 'user not logged in');
  exit();
}

// Business logic
write('user data', user_data);