| 45 | ); |
| 46 | |
| 47 | export function UseSessions(options: UseSessionOptions = {}): HookDecorator { |
| 48 | |
| 49 | function badRequestOrRedirect(description: string): HttpResponse { |
| 50 | if (options.redirectTo) { |
| 51 | return new HttpResponseRedirect(options.redirectTo); |
| 52 | } |
| 53 | return new HttpResponseBadRequest({ code: 'invalid_request', description }); |
| 54 | } |
| 55 | |
| 56 | function unauthorizedOrRedirect(description: string): HttpResponse { |
| 57 | if (options.redirectTo) { |
| 58 | return new HttpResponseRedirect(options.redirectTo); |
| 59 | } |
| 60 | return new HttpResponseUnauthorized({ code: 'invalid_token', description }) |
| 61 | .setHeader( |
| 62 | 'WWW-Authenticate', |
| 63 | `error="invalid_token", error_description="${description}"` |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | async function hook(ctx: Context, services: ServiceManager) { |
| 68 | const ConcreteSessionStore: ClassOrAbstractClass<SessionStore> = options.store || SessionStore; |
| 69 | const store = services.get(ConcreteSessionStore); |
| 70 | |
| 71 | async function postFunction(response: HttpResponse) { |
| 72 | if (!(ctx.session) || isHttpResponseInternalServerError(response)) { |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | if (ctx.session.isDestroyed) { |
| 77 | if (options.cookie) { |
| 78 | removeSessionCookie(response, !!options.userCookie); |
| 79 | } |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | await ctx.session.commit(); |
| 84 | |
| 85 | if (options.cookie) { |
| 86 | const userCookie = options.userCookie ? await options.userCookie(ctx, services) : undefined; |
| 87 | setSessionCookie(response, ctx.session, userCookie); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /* Validate the request */ |
| 92 | |
| 93 | let sessionID: string|undefined; |
| 94 | |
| 95 | try { |
| 96 | sessionID = getSessionIDFromRequest(ctx.request, options.cookie ? 'token-in-cookie' : 'token-in-header', !!options.required); |
| 97 | } catch (error) { |
| 98 | if (error instanceof RequestValidationError) { |
| 99 | return badRequestOrRedirect(error.message); |
| 100 | } |
| 101 | // TODO: test this. |
| 102 | throw error; |
| 103 | } |
| 104 | |