# @theorchard/jwt-service-handler

Common utilities for treating JWT in our service layers.

## Usage

### JwtHandler

In order to use the JwtHandler it needs to be first initialized with a cache and a service name.

```ts
import { JwtHandler } from '@theorchard/jwt-service-handler';

const handler = JwtHandler.create(cache, 'graphql-test-service');
// Sync remote Jwt Enabled Services to the local cache
handler.cacheJwtServicesList();

// Scheduler to re-sync Jwt Enabled Services in cache every 12hrs
handler.cacheRefreshScheduler(logInfo);
```

Then later anywhere in your code, you can get the `instance` using the static property.

```ts
import { JwtHandler } from '@theorchard/jwt-service-handler';

const someFunction = async () => {
    const enabledServices = await JwtHandler.instance.retrieve();

    // static helper using the singleton instance
    const isEnabled = await JwtHandler.isEnabledService('ows-users');
};
```

### Service Token

If you are writing a service that needs to make an inter-service request but has no user context to forward you can use the Service Token feature.

In order to do this you will need to give your service permission to access the `${env}/lambda-jwt-request/jwt_token` and `${env}/lambda-jwt-request/jwt_token_expiration` secrets.
This can be done by using the [terraform-owsrequest](https://github.com/theorchard/terraform-owsrequest) module.

You can then use the `getServiceToken` function every time you need to make a service-to-service request. You should not store the returned token. The token will be null in environments other than `qa` and `prod`.

```ts
import { HEADER_AUTHORIZATION } from '@theorchard/constants';
import { getServiceToken } from '@theorchard/jwt-service-handler';

const someFunction = async () => {
    const response = await fetch('url', {
        headers: {
            [HEADER_AUTHORIZATION]: await getServiceToken(),
        },
    });
};
```

### JWT Service List

Although this package will automatically update the list of jwt enabled services, we have migrated the management of it to be through terraform. Thus, please be sure to make PRs against [`terraform-infra`](https://github.com/theorchard/terraform-infra) to add your service to `qa/lambda-jwt-refresh/jwt_enabled_services.tf` and `prod/lambda-jwt-refresh/jwt_enabled_services.tf`. While we continue to make sure all parts of our application support JWT Bearer tokens, we need to maintain this list.
