# session-mng

A nodejs package to manage authentication session, as well as CSRF verification.

## Installation

```
npm i @developerportalsg/session-mng --save
```

## Getting Started

```js
import { validateAuthSession } from "@developerportalsg/session-mng";
// or
const { validateAuthSession } = require("@developerportalsg/session-mng")


// example usage
app.use(async function (req, res, next) {
  const cookieName = "dev.con.sid.local";
  const parsedCookie = req.cookies[cookieName];
  res.locals.sessionId = parsedCookie;
  let payload = {
    appId: '...', // tenant's appId
    sessionId: res.locals.sessionId, 
    xAPIKey: process.env.X_API_KEY,
  }
  if(req.method === 'POST' || req.method === 'PUT' || req.method === 'DELETE'){
    const xCsrfToken = req.header('X-CSRF-Token');
    payload = {...payload, csrfToken: xCsrfToken}// package checks for valid CSRF if csrfToken is provided
  }
  const response = await validateAuthSession(
    payload
  )
  res.locals.isAuthenticated = response.isAuthenticated;
  res.locals.isValidCsrf = response.isValidCsrf;
  next();
});
```

## Input Payload Params

| Params      | Type | Description | Required |
| ----------- | ----------- | ---------- | -------------
| appId      | string       |  Tenant's appId created in techpass portal.         | Yes
| sessionId   | string        |  Session Id extracted from cookie.          | Yes
| xAPIKey   | string        | XAPIKey needed to make api call to techpass's session management API endpoint   | Yes
| csrfToken   | string        | CSRF token relayed from frontend          | Optional <br/> If provided, will validate csrf 
| sessMngApiEnv   | string        |  Techpass's session management API endpoint environment being called.         | Optional <br/> 'local' [Default] <br/> 'dev' <br/> 'stg' <br/> 'prod'

## Response Object

```js
// Response if Session Does Not Exist
{
  isAuthenticated: false,
  isValidCsrf: false,
  failureMessage: '...'
}

// Response Object if Session Exists
{
  isAuthenticated: true,
  sessionObject: {
    csrfValidated: true, // If csrfToken is not provided in payload, this will be false
    email: 'yan_nyein_aung@hive.gov.sg',
    exp: 1670830974,
    iat: 1670829440,
    name: 'Yan Nyein AUNG',
    oid: 'xxx',
    roles: [ 'Default Access' ],
    userPrincipalName: 'yan_nyein_aung_hive.gov.sg#EXT#@gdpptdev.onmicrosoft.com'
  },
  isValidCsrf: true // If csrfToken is not provided in payload, this will be false
}
```

### Caveat

If csrfToken is not provided, response object will have `isValidCsrf` and `sessionObject.csrfValidated` as `false` but `isAuthenticated` as `true` and `sessionObject` will be in the response object.

Refer to this [Central Session Management](https://confluence.ship.gov.sg/display/TSBUS/Central+Session+Management) documentation for more information on the underlying API being used in this `session-mng` package.