import { AuthenticationClient } from "../../clients" ; import { AuthenticateRequestWithCredentials , AuthenticateRequestWithToken , Session } from "../../common" ; import { issueTokenCookie , parseTokenCookie , resetTokenCookie } from "../../utilities" ; import { handler } from "../_" ; import schema = require ( "../../common/events/authenticate/index.json" ) ; /**
 * Authentication request (intersection type to omit complex type guards)
 */ type Request = AuthenticateRequestWithCredentials & AuthenticateRequestWithToken ; param event return export const post = handler < { } , Request , Session > ( schema , async ( { headers , body : { username , password , remember , token } } ) => { const auth = new AuthenticationClient ( ) ; if ( username && password ) { const { refresh , ... body } = await auth . authenticateWithCredentials ( username , password ) ; return { body : remember ? { ... body , refresh } : body , ... ( remember && refresh ? { headers : { "Set-Cookie" : issueTokenCookie ( refresh ) } } : { } ) } ; } else { token = token || parseTokenCookie ( headers . Cookie ) ; try { const session = await auth . authenticateWithToken ( token ) ; return { body : session } ; } catch ( err ) { err . code = err . code || err . name ; return { statusCode : err . statusCode || 400 , body : { type : err . code , message : err . message . replace ( /\.$/ , "" ) } , headers : { "Set-Cookie" : resetTokenCookie ( ) } } ; } } } ) ;