MichalLytek / MichalLytek/type-graphql

Inverted authorization mode - @Public() decorator

Open
#230 24 comments 6 reactions 0 assignees View on GitHub
Community :family_man_girl: Discussion :speech_balloon: Enhancement :new:
Dominant language
TypeScript
Stars
8.1k
Forks
672
PR merge metrics
No merged PRs in 30d

Description

> **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:
```javascript
export function Public() {
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:
```javascript
export class CookieAuthMiddleware implements MiddlewareInterface {
async use({ context, info }: ResolverData, 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()`?

Contributor guide

Open the contributing guide

Research direction

Start by reading the middleware and guard behavior described in the issue, then inspect index.ts where the default context value is set. Trace the execution order for @Public(), @Authorized(), and CookieAuthMiddleware. Done would be a documented, supported way to bypass authentication for selected resolvers, with the execution order or alternative approach made clear.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.