Effect CommunityEC
Effect Community14mo ago
5 replies
Pivel

Issue with JWTService Dependency in Auth Middleware for HttpApi

I'm trying to create an auth middleare for my HttpApi but I'm running into issues because my jwtService which is used for checking the token validity is added into dependencies of the layer and Effect doesn't like that because it only expects HttpRouter.HttpRouter.Provided there. Any ideas?

class User extends Schema.Class<User>("User")({ code: Schema.String, token: Schema.String }) {}

class Unauthorized extends Schema.TaggedError<Unauthorized>()(
    "Unauthorized",
    {},
    HttpApiSchema.annotations({ status: 401 })
) {}

class CurrentUser extends Context.Tag("CurrentUser")<CurrentUser, User>() {}

class AuthMiddleware extends HttpApiMiddleware.Tag<AuthMiddleware>()("AuthMiddleware", {
    provides: CurrentUser,
    failure: Unauthorized,
    security: {
        bearer: HttpApiSecurity.bearer
    }
}) {}

const AuthMiddlewareLive = Layer.effect(
    AuthMiddleware,
    JWTService.pipe(Effect.map((jwtService) => AuthMiddleware.of({
        bearer: (_token) =>
            Effect.gen(function*() {
                const {token, code} = yield* jwtService.verify(Redacted.value(_token)).pipe(
                    Effect.catchTag("JWTVerifyError", () => Effect.failSync(() => new Unauthorized()))
                );
                return new User({token, code})
            })
    })))
)


FYI: my JWTService has ConfigService as its depdencency as it takes in some values defined from ENV. Therefore it throws:
TS2375: Type Effect<User, Unauthorized, ConfigService> is not assignable to type Effect<User, Unauthorized, Provided> with 'exactOptionalPropertyTypes: true'. Consider adding undefined to the types of the target's properties.
Type ConfigService is not assignable to type Provided
Was this page helpful?