| 1 | import { Context, Schema } from "effect" |
| 2 | import { HttpApiMiddleware, HttpApiSecurity } from "effect/http-api" |
| 3 | import type { User } from "../domain/User.ts" |
| 4 | |
| 5 | export class CurrentUser extends Context.Service<CurrentUser, User>()("acme/HttpApi/Authorization/CurrentUser") {} |
| 6 | |
| 7 | export class Unauthorized extends Schema.TaggedError<Unauthorized>()( |
| 8 | "Unauthorized", |
| 9 | { |
| 10 | message: Schema.String |
| 11 | }, |
| 12 | // You can define error status codes directly on the error class |
| 13 | { httpApiStatus: 401 } |
| 14 | ) {} |
| 15 | |
| 16 | export class Authorization extends HttpApiMiddleware.Service<Authorization, { |
| 17 | // Middleware can provide services to other middleware and endpoints, which is |
| 18 | // useful for things like authentication, where you want to inject the current |
| 19 | // user into the context for other endpoints to consume. |
| 20 | provides: CurrentUser |
| 21 | // If your middleware requires dependencies from other middleware, you can |
| 22 | // specify those as well. |
| 23 | requires: never |
| 24 | }>()("acme/HttpApi/Authorization", { |
| 25 | // This middleware requires clients to also provide an implementation, to |
| 26 | // inject a api key |
| 27 | requiredForClient: true, |
| 28 | // Middleware can optionally define security schemes, which are used to |
| 29 | // generate OpenAPI docs and decode credientials from incoming requests for |
| 30 | // you. |
| 31 | security: { |
| 32 | bearer: HttpApiSecurity.bearer |
| 33 | }, |
| 34 | // Middlware can specify errors that it may raise |
| 35 | error: Unauthorized |
| 36 | }) {} |