# Authenticator

Implements [`middy v1.x` AWS Lambda Middleware](https://github.com/middyjs/middy/tree/1.0.0-beta) to provide token authentication to serverless endpoints.

## Implementation

Run `npm install @middy/core` to add middy to your project.

Run `npm install @mosure/lambda-auth-middleware` to install to your project.

Run `npm install @middy/http-error-handler` to install the error handler.

To implement this middleware into your AWS Lambda follow the code sample below:

```typescript
import { Context, APIGatewayProxyResult, APIGatwayProxyCallback } from 'aws-lambda';
import middy from '@middy/core';
import httpErrorHandler from '@middy/http-error-handler';

import { authorize, AuthMiddlewareConfig } from '@mosure/lambda-auth-middleware';


// Optional token payload and validator
interface TokenPayload {
    somePayloadValue: string;
}

const isPayload = (payload: any): payload is TokenPayload => {
    return payload && payload['somePayloadValue'];
}

// Your AWS Lambda function
const myLambdaFunction = (event: AuthEvent<TokenPayload>, context: Context, callback: APIGatewayProxyCallback) => {
    // Optionally access JWT payload
    if (event.auth.payload.somePayloadValue !== 'TEST') {
        // TODO: handle bad payload
    }

    // TODO: Business Logic (post-authentication)
};

const authConfig: AuthMiddlewareConfig = {
    credentialsRequired: !process.env.NODE_DEBUG, // Force authorization header to exist
    secret: process.env.JWT_SECRET,
    algorithm: 'HS256',
    audience: process.env.JWT_AUDIENCE,
    isPayload
};

const handler = middy(myLambdaFunction)
    .use(httpErrorHandler())
    .use(authorize(authConfig));
```
