Completed
Pull Request — master (#4)
by Aaron
02:20
created

main/src/authenticator.ts   A

Complexity

Total Complexity 2
Complexity/F 0

Size

Lines of Code 28
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 2
eloc 22
mnd 2
bc 2
fnc 0
dl 0
loc 28
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
// tslint:disable-next-line: no-implicit-dependencies
2
import { APIGatewayProxyEvent } from 'aws-lambda' // @types
3
import getToken from './getToken'
4
import UnauthorisedResponse from './UnauthorisedResponse'
5
import verify, { Jwt, SecretOrPublicKey, VerifyOptions } from './verify'
6
7
export { SecretOrPublicKey, VerifyOptions }
8
export type APIGatewayProxyEventJwt = APIGatewayProxyEvent & { jwt: Jwt }
9
10
export const authenticator =
11
  (secretOrPublicKey: SecretOrPublicKey, options?: VerifyOptions) =>
12
  (event: APIGatewayProxyEvent): APIGatewayProxyEventJwt | UnauthorisedResponse => {
13
    const token = getToken(event)
14
    if (typeof token !== 'string') {
15
      return token // return UnauthorisedResponse
16
    }
17
    return new Promise((resolve) => {
18
      verify(token, secretOrPublicKey, { ...options }, (error, jwt?: Jwt) => {
19
        if (error) {
20
          resolve(new UnauthorisedResponse(`${error.name} ${error.message}`))
21
        }
22
        resolve({ ...event, jwt })
23
      })
24
    })
25
  }
26
27
export default authenticator
28