Skip to content

Inverted authorization mode - @Public() decorator #230

@breytex

Description

@breytex

Original title: Running a guard before the middlewares

Hello :)
Usually, ppl in the GraphQL world use an @Authorized() guard to shield resolvers from unauthorized access. I want to build the opposite: a @Public() guard to flag a few resolvers as "available without login". Reason is, that my SaaS app has like 3 (login-related) mutations which are public, and all other resolvers are guarded with @Authorized() so far. I would like to turn this upside-down.

So I have a Public guard:

export function Public<T extends object>() {
    return UseMiddleware(async ({ args, context }, next: NextFn) => {
        console.log("public field")
        context.public = true   // default set in index.ts is false
        return next()
    })
}

and an auth middleware:

export class CookieAuthMiddleware implements MiddlewareInterface<MyContext> {
    async use({ context, info }: ResolverData<MyContext>, next: NextFn) {
        if (context.public) {
            console.log("public request, authorized")
            await next()

        } else {
              // do some cookie / session magic to check access rights
        }
     }
}

My main problem here is, that a middleware is executed before before the guards in type-graphql, which breaks the entire idea of my approach.
I want to detect if a request targets a public resolver using the guard and then "skip" the auth middleware. This requires the public guard to be executed before the middlewares.

Is it possible to make a guard execute before the middlewares in general?
Or do you see a different approach for implementing @Public() as a counterpart to @Authorized()?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions