package graph import ( "context" "errors" "github.com/99designs/gqlgen/graphql" "adam-french.co.uk/job-tracker/internal/auth" ) // The schema's authorisation directive. A field marked @admin in // schema/*.graphql has requireAdmin run before its resolver; if it returns an // error the resolver is never called and the error is what the client // receives for that field. // // The verdict itself comes from internal/auth, which asked the site backend // before GraphQL ran (auth.Annotate in main). // // The error string is part of the contract with the front end, which explains // "admin access required" as a lapsed session and sends the browser to the // site's login. Do not reword it. // // This file is hand-written and never touched by gqlgen. const errAdminRequired = "admin access required" // Directives is the set gqlgen needs in graph.Config. It is a function so // that main and the tests wire exactly the same implementations. // // Leaving a directive nil in the Config does not open the fields that use it: // the generated code answers "directive admin is not implemented" for each. func Directives() DirectiveRoot { return DirectiveRoot{Admin: requireAdmin} } // requireAdmin implements @admin. func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) { if !auth.IsAdminFromCtx(ctx) { return nil, errors.New(errAdminRequired) } return next(ctx) }