Declare GraphQL auth in the schema and drop the Go Claude client
Authorisation: @admin and @signedIn schema directives replace the 25 hand-copied resolver checks. A test fails if a mutation has neither and is not on the public allow-list, so a new mutation cannot ship unguarded. IDs: uint model IDs bind through graphql.UintID, removing the ten int(obj.ID) resolvers. Job status is a GraphQL enum, tied to services.statusOrder by a test. Input is strict, so the mutations no longer coerce an unknown status to "applied"; output is lenient so one legacy row cannot fail the list. deleteJobApplication and deleteJobAppReference now error on a missing id like the other deletes. The rowing reader, the job extractor and now the email classifier reach the Python service through one services.CallPython helper. The email pipeline's prompt and fence stripping moved to Python, and anthropic-sdk-go is gone from go.mod. Fix the auth test fixture, whose 11-byte secret had been panicking the services test package since InitAuth began requiring 32 bytes. Add a test that keeps the python service's compose environment list in step with the env registry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -7,24 +7,16 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Admin-only, but there is no check to see here: the field is marked
|
||||
// @admin in the schema and the directive (directives.go) has already
|
||||
// refused anyone else by the time this runs.
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
}
|
||||
return ptrs(activities), nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
||||
|
||||
type activityResolver struct{ *Resolver }
|
||||
|
||||
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
// Checked here rather than with @signedIn because the message differs:
|
||||
// this query has always answered "unauthorized", and the directive's is
|
||||
// "authentication required".
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
|
||||
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateBookmark is the resolver for the createBookmark field.
|
||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
|
||||
|
||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Loaded first so the deleted record can be returned to the client, and
|
||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
||||
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
}
|
||||
return ptrs(bookmarks), nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
||||
|
||||
type bookmarkResolver struct{ *Resolver }
|
||||
|
||||
@@ -27,7 +27,8 @@ const (
|
||||
|
||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
||||
// not an error here, because many queries are public.
|
||||
// not an error here, because many queries are public. Turning "anonymous"
|
||||
// into a refusal is the job of the schema directives, per field.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
//
|
||||
// ok is also the test behind the @signedIn directive. A resolver calls this
|
||||
// itself when it needs the id for more than a gate: to record a post's
|
||||
// author, or to compare the caller with a row's owner.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -50,11 +55,12 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
||||
// the authorisation check for nearly every mutation — there is no middleware
|
||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
||||
// flag only bites once the access token expires.
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. It is
|
||||
// what the @admin directive tests (directives.go), which is how nearly every
|
||||
// mutation is authorised; resolvers call it directly only for the softer
|
||||
// cases a directive cannot express, such as the messages query filtering
|
||||
// rather than refusing. Admin comes from the token, not the database, so a
|
||||
// revoked admin flag only bites once the access token expires.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
// The schema's two authorisation directives. A field marked @admin or
|
||||
// @signedIn in graph/schema/*.graphql has the matching function here 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.
|
||||
//
|
||||
// This replaces a check that used to be copied into the top of every guarded
|
||||
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
|
||||
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
|
||||
// it is now declared next to the field, where a missing one can be seen and
|
||||
// tested for (directives_test.go), instead of being a line someone has to
|
||||
// remember to paste.
|
||||
//
|
||||
// The two error strings are part of the contract with the front end, which
|
||||
// shows them as they are; the tracker page, for one, explains "admin access
|
||||
// required" as a lapsed session. Do not reword them.
|
||||
//
|
||||
// This file is hand-written and never touched by gqlgen.
|
||||
|
||||
const (
|
||||
errAdminRequired = "admin access required"
|
||||
errSignedInRequired = "authentication 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,
|
||||
SignedIn: requireSignedIn,
|
||||
}
|
||||
}
|
||||
|
||||
// requireAdmin implements @admin: the request must carry an access token
|
||||
// whose admin claim is true. Admin comes from the token, not the database, so
|
||||
// demoting a user only bites once their access token is replaced.
|
||||
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf(errAdminRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// requireSignedIn implements @signedIn: any verified access token will do,
|
||||
// admin or not. An admin is signed in, so this never needs pairing with
|
||||
// @admin.
|
||||
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf(errSignedInRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/vektah/gqlparser/v2/ast"
|
||||
|
||||
"adam-french.co.uk/backend/handlers"
|
||||
)
|
||||
|
||||
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
|
||||
// by directives.go. These tests cover both halves: that the two functions
|
||||
// decide correctly, and that the schema marks the fields it should — the
|
||||
// second being the one that matters day to day, since the way this goes
|
||||
// wrong is a new field added without a directive.
|
||||
//
|
||||
// Nothing here needs a database: a refused field never reaches its resolver,
|
||||
// and the tests only ever drive fields that are refused or that return before
|
||||
// touching the Store.
|
||||
|
||||
// withClaims builds the context AuthContextMiddleware would for a verified
|
||||
// token. Claims are decoded from JSON in production, hence float64 for the id.
|
||||
func withClaims(id float64, admin bool) context.Context {
|
||||
claims := jwt.MapClaims{"id": id, "admin": admin}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}
|
||||
|
||||
func TestDirectives(t *testing.T) {
|
||||
anonymous := context.Background()
|
||||
user := withClaims(2, false)
|
||||
admin := withClaims(1, true)
|
||||
// A token that verified but carries no id: not something GenerateJWT
|
||||
// mints, but it must not count as signed in.
|
||||
noID := func() context.Context {
|
||||
claims := jwt.MapClaims{"admin": false}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
directive func(context.Context, any, graphql.Resolver) (any, error)
|
||||
ctx context.Context
|
||||
wantErr string // "" means the resolver must run
|
||||
}{
|
||||
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
|
||||
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
|
||||
{"@admin admits an admin", requireAdmin, admin, ""},
|
||||
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
|
||||
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
|
||||
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
|
||||
{"@signedIn admits an admin", requireSignedIn, admin, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
called := false
|
||||
next := func(ctx context.Context) (any, error) {
|
||||
called = true
|
||||
return "resolved", nil
|
||||
}
|
||||
res, err := c.directive(c.ctx, nil, next)
|
||||
|
||||
if c.wantErr == "" {
|
||||
if err != nil || !called || res != "resolved" {
|
||||
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The exact strings are what the front end displays.
|
||||
if err == nil || err.Error() != c.wantErr {
|
||||
t.Fatalf("err = %v, want %q", err, c.wantErr)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("the resolver ran for a refused request")
|
||||
}
|
||||
if res != nil {
|
||||
t.Fatalf("res = %v, want nil alongside the error", res)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Directives() must supply every directive the schema declares; a nil one
|
||||
// makes gqlgen fail each field that uses it.
|
||||
func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||
d := Directives()
|
||||
if d.Admin == nil || d.SignedIn == nil {
|
||||
t.Fatal("Directives() left a directive unimplemented")
|
||||
}
|
||||
}
|
||||
|
||||
// guardOf reports which authorisation directive a field carries: "admin",
|
||||
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
|
||||
// nothing to @admin) and fails the test rather than being quietly accepted.
|
||||
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
|
||||
t.Helper()
|
||||
admin := field.Directives.ForName("admin") != nil
|
||||
signedIn := field.Directives.ForName("signedIn") != nil
|
||||
switch {
|
||||
case admin && signedIn:
|
||||
t.Errorf("%s carries both @admin and @signedIn", field.Name)
|
||||
return "admin"
|
||||
case admin:
|
||||
return "admin"
|
||||
case signedIn:
|
||||
return "signedIn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func schemaUnderTest() *ast.Schema {
|
||||
return NewExecutableSchema(Config{}).Schema()
|
||||
}
|
||||
|
||||
// publicMutations is the complete list of mutations that anyone may call.
|
||||
// A mutation is public only by being named here, so adding one to the schema
|
||||
// without a directive fails TestEveryMutationIsGuarded until it is either
|
||||
// guarded or deliberately listed.
|
||||
//
|
||||
// All three are how a session is obtained or given up, so they cannot require
|
||||
// one: login checks a password, refreshToken checks the refresh cookie, and
|
||||
// logout is a no-op for a visitor who is not signed in.
|
||||
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||
|
||||
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
var seen []string
|
||||
for _, field := range schema.Mutation.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
seen = append(seen, field.Name)
|
||||
guard := guardOf(t, field)
|
||||
public := slices.Contains(publicMutations, field.Name)
|
||||
switch {
|
||||
case guard == "" && !public:
|
||||
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
|
||||
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
|
||||
case guard != "" && public:
|
||||
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
|
||||
}
|
||||
}
|
||||
// A renamed or removed mutation must not leave a stale exemption behind.
|
||||
for _, name := range publicMutations {
|
||||
if !slices.Contains(seen, name) {
|
||||
t.Errorf("publicMutations lists %s, which is not in the schema", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mutations that need only a session rather than an admin. Pinned so that
|
||||
// loosening a mutation from @admin to @signedIn — which the test above would
|
||||
// accept — has to be done here too.
|
||||
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||
var got []string
|
||||
for _, field := range schemaUnderTest().Mutation.Fields {
|
||||
if guardOf(t, field) == "signedIn" {
|
||||
got = append(got, field.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(got)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Queries are public by default — the home page is built from them — so the
|
||||
// rule cannot be "every field is guarded". Instead the guarded set is pinned
|
||||
// exactly: removing a directive from one of these, or adding a query that
|
||||
// exposes private data without one, has to be a visible change to this map.
|
||||
//
|
||||
// Three queries are sensitive to who is asking without being in it, because
|
||||
// they answer rather than refuse: `me` returns "unauthorized" itself,
|
||||
// `messages` filters out private rows for non-admins, and
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"jobApplications": "admin",
|
||||
"jobApplication": "admin",
|
||||
"jobAppReferences": "admin",
|
||||
"places": "signedIn",
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, field := range schemaUnderTest().Query.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
if guard := guardOf(t, field); guard != "" {
|
||||
got[field.Name] = guard
|
||||
}
|
||||
}
|
||||
for name, guard := range want {
|
||||
if got[name] != guard {
|
||||
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
|
||||
}
|
||||
}
|
||||
for name, guard := range got {
|
||||
if _, ok := want[name]; !ok {
|
||||
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The directives are FIELD_DEFINITION only and are meant for the two root
|
||||
// types. One on an object's field would be enforced, but nothing above would
|
||||
// notice it being removed, so keep them where the tests look.
|
||||
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
for name, def := range schema.Types {
|
||||
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
|
||||
continue
|
||||
}
|
||||
for _, field := range def.Fields {
|
||||
if guardOf(t, field) != "" {
|
||||
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// execute runs one operation through the real executable schema, wired the
|
||||
// way main wires it, and returns the response's error messages. The Store is
|
||||
// empty: every operation below is refused, or returns, before its resolver
|
||||
// would touch the database.
|
||||
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
|
||||
t.Helper()
|
||||
srv := handler.New(NewExecutableSchema(Config{
|
||||
Resolvers: &Resolver{Store: &handlers.Store{}},
|
||||
Directives: Directives(),
|
||||
}))
|
||||
srv.AddTransport(transport.POST{})
|
||||
|
||||
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
|
||||
var resp struct {
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decoding response %s: %v", rec.Body, err)
|
||||
}
|
||||
var messages []string
|
||||
for _, e := range resp.Errors {
|
||||
messages = append(messages, e.Message)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// End to end: the message a client receives for a refused field is the bare
|
||||
// string the resolvers used to return, with nothing wrapped around it.
|
||||
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
|
||||
{"non-admin admin query", withClaims(2, false), `{ jobApplications { id } }`, "admin access required"},
|
||||
{"anonymous admin mutation", context.Background(), `mutation { deleteJobApplication(id: 1) }`, "admin access required"},
|
||||
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
|
||||
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
|
||||
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
|
||||
// Not a directive, and a different message on purpose.
|
||||
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := execute(t, c.ctx, c.query, nil)
|
||||
if !slices.Equal(got, []string{c.want}) {
|
||||
t.Fatalf("errors = %q, want exactly %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The JobStatus enum over the wire, from the side the tracker page uses it:
|
||||
// status sent as a JSON string variable. A value in the vocabulary reaches the
|
||||
// resolver (shown by the resolver's own validation error, which comes before
|
||||
// any database access); one outside it is refused before the resolver runs.
|
||||
func TestJobStatusInputOverTheWire(t *testing.T) {
|
||||
const mutation = `mutation ($input: CreateJobApplicationInput!) { createJobApplication(input: $input) { id status } }`
|
||||
admin := withClaims(1, true)
|
||||
input := func(status any) map[string]any {
|
||||
// A blank title makes the resolver return early, so no test here
|
||||
// needs a database.
|
||||
return map[string]any{"input": map[string]any{"jobTitle": " ", "company": "Acme", "status": status}}
|
||||
}
|
||||
|
||||
for _, status := range []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"} {
|
||||
got := execute(t, admin, mutation, input(status))
|
||||
if !slices.Equal(got, []string{"jobTitle and company are required"}) {
|
||||
t.Errorf("status %q: errors = %q, want it accepted and the resolver reached", status, got)
|
||||
}
|
||||
}
|
||||
|
||||
for _, status := range []any{"hired", "Applied", "", " applied", 3} {
|
||||
got := execute(t, admin, mutation, input(status))
|
||||
if len(got) != 1 || got[0] == "jobTitle and company are required" {
|
||||
t.Errorf("status %#v: errors = %q, want it refused before the resolver", status, got)
|
||||
}
|
||||
}
|
||||
|
||||
// The guard still comes first: an anonymous caller learns nothing about
|
||||
// the vocabulary from a valid input.
|
||||
if got := execute(t, context.Background(), mutation, input("applied")); !slices.Equal(got, []string{"admin access required"}) {
|
||||
t.Errorf("anonymous: errors = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs: the wire form must be what it was when every type had a hand-written
|
||||
// resolver returning int. Both marshallers write a quoted decimal string and
|
||||
// both read a string or a number.
|
||||
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
|
||||
for _, id := range []uint{0, 1, 12, 4294967295} {
|
||||
var asUint, asInt bytes.Buffer
|
||||
graphql.MarshalUintID(id).MarshalGQL(&asUint)
|
||||
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
|
||||
if asUint.String() != asInt.String() {
|
||||
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
|
||||
}
|
||||
}
|
||||
if got := func() string {
|
||||
var b bytes.Buffer
|
||||
graphql.MarshalUintID(12).MarshalGQL(&b)
|
||||
return b.String()
|
||||
}(); got != `"12"` {
|
||||
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
|
||||
}
|
||||
}
|
||||
+30
-9
@@ -9,8 +9,13 @@
|
||||
// matching *.resolvers.go. Never edit those two generated files.
|
||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
||||
// structs in backend/models, so model/ holds only input and payload
|
||||
// types. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// types. A model's `ID uint` binds to `id: ID!` directly, because
|
||||
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
|
||||
// needed for it. A field resolver is only written where the Go type has
|
||||
// no binding (Message.authorId and Rowing's time/distance are unsigned in
|
||||
// Go and Int in the schema).
|
||||
// - The JobStatus enum is bound to a custom marshaller in
|
||||
// services/job_status.go rather than a generated type; see that file.
|
||||
// - Resolvers reach the database and the third-party caches through
|
||||
// Resolver.Store, the same handlers.Store the REST endpoints use.
|
||||
// - context.go and middleware.go carry the caller's identity from Gin into
|
||||
@@ -18,13 +23,29 @@
|
||||
//
|
||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
||||
// annotates the context and lets everything through, so each resolver checks
|
||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
||||
// check is fully public. The rule of thumb in this schema is that queries are
|
||||
// public and mutations are admin-only, with these exceptions: the job
|
||||
// application and job reference queries are admin-only (they are private
|
||||
// data), the places mutations need only a signed-in user, and the messages
|
||||
// query hides private messages from non-admins rather than refusing.
|
||||
// annotates the context and lets everything through. What guards a field is a
|
||||
// directive on it in the schema:
|
||||
//
|
||||
// createUser(input: CreateUserInput!): User! @admin
|
||||
// places: [Place!]! @signedIn
|
||||
//
|
||||
// @admin requires an admin's access token, @signedIn any valid one. Both are
|
||||
// implemented once, in directives.go, and run before the resolver, so a
|
||||
// guarded resolver contains no check of its own. A field with NEITHER
|
||||
// directive is fully public.
|
||||
//
|
||||
// The rule of thumb in this schema is that queries are public and mutations
|
||||
// are @admin, with these exceptions: login, logout and refreshToken are
|
||||
// public; the places mutations and query are @signedIn; and the users, job
|
||||
// application and job reference queries are @admin (they are private data).
|
||||
// directives_test.go holds that list and fails when the schema departs from
|
||||
// it — in particular when a mutation is added with no directive.
|
||||
//
|
||||
// A directive is only a gate. Anything finer stays in the resolver and uses
|
||||
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
|
||||
// author, `me` answers for the caller (with its own "unauthorized" error),
|
||||
// the messages query hides private messages from non-admins rather than
|
||||
// refusing, and spotifyNeedsReauth is simply false for non-admins.
|
||||
//
|
||||
// The files ending in _helpers.go are hand-written and are not touched by
|
||||
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
|
||||
|
||||
@@ -7,23 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
}
|
||||
return ptrs(favorites), nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
||||
|
||||
type favoriteResolver struct{ *Resolver }
|
||||
|
||||
+527
-515
File diff suppressed because it is too large
Load Diff
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
ref := models.JobAppReference{
|
||||
Category: input.Category,
|
||||
Label: input.Label,
|
||||
@@ -39,9 +30,6 @@ func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input mode
|
||||
|
||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -66,10 +54,13 @@ func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, in
|
||||
|
||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
// Loaded first so a missing id is an error rather than a `true` that
|
||||
// deleted nothing; see DeleteJobApplication.
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
||||
if err := r.Store.DB.Delete(&ref).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
@@ -77,9 +68,6 @@ func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (b
|
||||
|
||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
||||
// default 0) keep a stable, insertion-ordered sequence.
|
||||
@@ -88,8 +76,3 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
||||
|
||||
type jobAppReferenceResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,19 +12,10 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// String! is non-null but not non-empty, and the columns are only
|
||||
// `not null`, so "" stores happily and then never matches the email
|
||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
||||
@@ -33,12 +24,15 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
if jobTitle == "" || company == "" {
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
// input.Status is already one of the JobStatus values: the enum's
|
||||
// unmarshaller (services.UnmarshalJobStatus) refused anything else before
|
||||
// this resolver was reached, so it is stored as it came.
|
||||
app := models.JobApplication{
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Status: input.Status,
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
Description: input.Description,
|
||||
@@ -51,9 +45,6 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
|
||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched.
|
||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
||||
@@ -82,7 +73,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = services.NormalizeStatus(*input.Status)
|
||||
app.Status = *input.Status
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
@@ -101,12 +92,19 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
|
||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
// Loaded first so a missing id is an error, as it is for the deletes that
|
||||
// return the row (deletePost, deletePlace, deleteBookmark). Deleting by
|
||||
// id alone reports success whether or not anything matched, which told
|
||||
// the tracker a row was gone when it had never existed. The return type
|
||||
// stays Boolean! for the front end's sake, so the only value is true.
|
||||
//
|
||||
// Soft delete: the row is kept, which is what lets the email pipeline see
|
||||
// that an application was deleted and not re-create it.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Soft delete straight by id, without loading first — so deleting an id
|
||||
// that does not exist still returns true.
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
if err := r.Store.DB.Delete(&app).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
@@ -114,10 +112,12 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
// Admin-only even though it is a query: job applications are private.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Admin-only even though it is a query (@admin in the schema): job
|
||||
// applications are private.
|
||||
//
|
||||
// A row whose stored status is outside the JobStatus enum does not fail
|
||||
// this list: services.MarshalJobStatus passes it through.
|
||||
//
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
@@ -132,17 +132,9 @@ func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobAppli
|
||||
|
||||
// JobApplication is the resolver for the jobApplication field.
|
||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// JobApplication returns JobApplicationResolver implementation.
|
||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
||||
|
||||
type jobApplicationResolver struct{ *Resolver }
|
||||
|
||||
@@ -11,11 +11,6 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// AuthorID is the resolver for the authorId field.
|
||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
||||
// hub's per-connection counter, not a User id — see models.Message.
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
||||
// valid access token is present. Crucially it never rejects a request: a
|
||||
// missing, expired or forged token simply leaves the context anonymous, which
|
||||
// is what lets public queries work and pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
// is what lets public queries work and leaves every authorisation decision
|
||||
// to the field being resolved — the @admin / @signedIn directives on it (see
|
||||
// directives.go), or the resolver itself for anything finer. Both cookie and
|
||||
// verify errors are swallowed for exactly that reason.
|
||||
//
|
||||
// It takes the database because validating a token means loading the user to
|
||||
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
|
||||
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -16,11 +15,9 @@ import (
|
||||
// CreatePlace is the resolver for the createPlace field.
|
||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
||||
// Any signed-in user, not just an admin — places are the one shared,
|
||||
// collaboratively edited list on the site. There is no per-user
|
||||
// ownership, so any signed-in user can edit or delete any place.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// collaboratively edited list on the site, so the schema marks these
|
||||
// fields @signedIn rather than @admin. There is no per-user ownership, so
|
||||
// any signed-in user can edit or delete any place.
|
||||
place := models.Place{
|
||||
Title: input.Title,
|
||||
Location: input.Location,
|
||||
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
|
||||
|
||||
// UpdatePlace is the resolver for the updatePlace field.
|
||||
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// Partial update, same pointer-means-supplied convention as job
|
||||
// applications: nil fields are left as they are.
|
||||
var place models.Place
|
||||
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
|
||||
// DeletePlace is the resolver for the deletePlace field.
|
||||
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
|
||||
return &place, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Places is the resolver for the places field.
|
||||
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var places []models.Place
|
||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(places), nil
|
||||
}
|
||||
|
||||
// Place returns PlaceResolver implementation.
|
||||
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
|
||||
|
||||
type placeResolver struct{ *Resolver }
|
||||
|
||||
@@ -15,10 +15,9 @@ import (
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// @admin has already established that there is a session; the id is read
|
||||
// here because the post needs an author, not as a second gate. The !ok
|
||||
// branch is only reachable with a token that has admin but no usable id.
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -34,10 +33,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -48,8 +43,9 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// Admin alone is not enough: a post may only be edited by its author, so
|
||||
// one admin cannot rewrite another's posts.
|
||||
// Admin alone (the @admin on the field) is not enough: a post may only be
|
||||
// edited by its author, so one admin cannot rewrite another's posts. This
|
||||
// is the kind of rule a directive cannot express, so it stays here.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
@@ -67,10 +63,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -95,11 +87,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
// Preload issues a second query for the authors and fills in Post.Author.
|
||||
@@ -120,8 +107,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Post returns PostResolver implementation.
|
||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||
|
||||
type postResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||
// database handle and one set of third-party caches.
|
||||
//
|
||||
// The generated code embeds *Resolver in per-type resolver structs
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
// The generated code embeds *Resolver in per-type resolver structs, which is
|
||||
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
||||
// resolvers files. A type only gets one when a field of it needs a resolver:
|
||||
// queryResolver and mutationResolver always, messageResolver and
|
||||
// rowingResolver for their unsigned-to-Int fields. Most object types bind
|
||||
// every field straight to the model and have none.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
return ptrs(rows), nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Time is the resolver for the time field.
|
||||
// Time is the resolver for the time field: total session seconds, narrowed
|
||||
// from uint64 to GraphQL's Int.
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
createActivity(input: CreateActivityInput!): Activity! @admin
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@ type AuthPayload {
|
||||
user: User!
|
||||
}
|
||||
|
||||
# `me` carries no directive although it needs a session: it answers
|
||||
# "unauthorized", not @signedIn's "authentication required", and the front end
|
||||
# relies on that query failing quietly for an anonymous visitor.
|
||||
extend type Query {
|
||||
me: User
|
||||
}
|
||||
|
||||
# Deliberately public: these are how a session is obtained and given up.
|
||||
extend type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
|
||||
@@ -18,6 +18,6 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
||||
deleteBookmark(id: ID!): Bookmark!
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
|
||||
deleteBookmark(id: ID!): Bookmark! @admin
|
||||
}
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Reusable snippets for filling in application forms. Private, like the
|
||||
# applications themselves, so the query is @admin as well as the mutations.
|
||||
|
||||
type JobAppReference {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
@@ -23,11 +26,13 @@ input UpdateJobAppReferenceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobAppReferences: [JobAppReference!]!
|
||||
jobAppReferences: [JobAppReference!]! @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
||||
deleteJobAppReference(id: ID!): Boolean!
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference! @admin
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference! @admin
|
||||
# Errors on an id that does not exist, like the other deletes; the Boolean
|
||||
# is only ever true.
|
||||
deleteJobAppReference(id: ID!): Boolean! @admin
|
||||
}
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
# Job application tracker. Rows come from these mutations, automatically from
|
||||
# the email sync pipeline (backend/services/email_sync.go), or from the browser
|
||||
# capture userscript (backend/handlers/handle_job_capture.go). These are
|
||||
# private data, so the queries here are admin-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# saved, applied, screening, assessment, interviewing, offer, rejected,
|
||||
# withdrawn.
|
||||
# private data, so the queries here are @admin as well as the mutations.
|
||||
#
|
||||
# description is the captured posting text. It can run to tens of kilobytes,
|
||||
# so the tracker's list query leaves it out and asks for it per row.
|
||||
|
||||
# The lifecycle of an application, in the order the email pipeline and the
|
||||
# capture endpoint are allowed to advance it. The values are lowercase on
|
||||
# purpose: they are exactly the strings stored in the status column and ranked
|
||||
# in services.statusOrder (backend/services/email_sync.go), and a test there
|
||||
# fails if this list and that map ever differ. Adding a status means adding
|
||||
# it in both places, and to the tracker page and the capture userscript.
|
||||
#
|
||||
# It is bound to a custom marshaller (services/job_status.go, via gqlgen.yml)
|
||||
# rather than a generated Go type: input is strict, so a mutation carrying a
|
||||
# status outside this list is refused, while output passes a legacy stored
|
||||
# value through so one old row cannot fail the whole jobApplications query.
|
||||
#
|
||||
# On the wire it is still a JSON string ("applied"), as it was when the field
|
||||
# was a String, both in variables and in responses.
|
||||
enum JobStatus {
|
||||
saved
|
||||
applied
|
||||
screening
|
||||
assessment
|
||||
interviewing
|
||||
offer
|
||||
rejected
|
||||
withdrawn
|
||||
}
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
@@ -19,7 +39,7 @@ type JobApplication {
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
status: JobStatus!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
@@ -30,7 +50,7 @@ input CreateJobApplicationInput {
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
status: JobStatus!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
@@ -41,19 +61,21 @@ input UpdateJobApplicationInput {
|
||||
company: String
|
||||
location: String
|
||||
url: String
|
||||
status: String
|
||||
status: JobStatus
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobApplications: [JobApplication!]!
|
||||
jobApplication(id: ID!): JobApplication
|
||||
jobApplications: [JobApplication!]! @admin
|
||||
jobApplication(id: ID!): JobApplication @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
||||
deleteJobApplication(id: ID!): Boolean!
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication! @admin
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication! @admin
|
||||
# Errors on an id that does not exist, like the other deletes; the Boolean
|
||||
# is only ever true.
|
||||
deleteJobApplication(id: ID!): Boolean! @admin
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
#
|
||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||
# User id, and private messages are silently filtered out for non-admins
|
||||
# rather than causing an error.
|
||||
# rather than causing an error — which is why the query has no @admin: the
|
||||
# resolver makes that decision per row.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
||||
# not an admin, and there is no per-user ownership: the list is shared.
|
||||
# Places to go. Unlike most mutations these require only a signed-in user
|
||||
# (@signedIn), not an admin, and there is no per-user ownership: the list is
|
||||
# shared. The query is guarded too — the list is not public.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
places: [Place!]!
|
||||
places: [Place!]! @signedIn
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPlace(input: CreatePlaceInput!): Place!
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
|
||||
deletePlace(id: ID!): Place!
|
||||
createPlace(input: CreatePlaceInput!): Place! @signedIn
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
|
||||
deletePlace(id: ID!): Place! @signedIn
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ extend type Query {
|
||||
post(id: ID!): Post
|
||||
}
|
||||
|
||||
# @admin is only the first half of the rule for updatePost and deletePost:
|
||||
# the resolver also requires the caller to be the post's author.
|
||||
extend type Mutation {
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
createPost(input: CreatePostInput!): Post! @admin
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
|
||||
deletePost(id: ID!): Post! @admin
|
||||
}
|
||||
|
||||
@@ -16,5 +16,22 @@
|
||||
|
||||
scalar Time
|
||||
|
||||
# Authorisation. There is no middleware in front of /graphql, so a field is
|
||||
# PUBLIC unless it carries one of these. Each is implemented once, in
|
||||
# graph/directives.go, and runs before the field's resolver:
|
||||
#
|
||||
# @admin the request must carry an admin's access token
|
||||
# (error: "admin access required")
|
||||
# @signedIn any valid access token will do
|
||||
# (error: "authentication required")
|
||||
#
|
||||
# Every mutation needs one of them unless it is deliberately public (login,
|
||||
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
|
||||
# which queries are guarded. Rules that are not a plain gate stay in the
|
||||
# resolver: a post is only editable by its author, `me` answers for whoever is
|
||||
# signed in, and `messages` filters private rows rather than refusing.
|
||||
directive @admin on FIELD_DEFINITION
|
||||
directive @signedIn on FIELD_DEFINITION
|
||||
|
||||
type Query
|
||||
type Mutation
|
||||
|
||||
@@ -36,6 +36,7 @@ extend type Query {
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
# True only for an admin session while the backend lacks a Spotify client
|
||||
# (OAuth never completed or the token was revoked), used by the Listening
|
||||
# widget to offer a reconnect link. Everyone else gets false.
|
||||
# widget to offer a reconnect link. Everyone else gets false — a soft
|
||||
# check in the resolver, not @admin, so the home page query never errors.
|
||||
spotifyNeedsReauth: Boolean!
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@ input CreateUserInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
users: [User!]! @admin
|
||||
user(id: ID!): User @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createUser(input: CreateUserInput!): User!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
createUser(input: CreateUserInput!): User! @admin
|
||||
deleteUser(id: ID!): User! @admin
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
|
||||
}
|
||||
|
||||
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// A soft check, deliberately not @admin: the directive would turn this
|
||||
// into an error on the public home page query.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -16,12 +16,9 @@ import (
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Only an existing admin can create accounts — there is no public
|
||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
||||
// Only an existing admin can create accounts (@admin in the schema) —
|
||||
// there is no public sign-up. New users are created non-admin;
|
||||
// setUserAdmin promotes them.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -37,10 +34,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
@@ -55,10 +48,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -85,9 +74,6 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,22 +83,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// User returns UserResolver implementation.
|
||||
func (r *Resolver) User() UserResolver { return &userResolver{r} }
|
||||
|
||||
type userResolver struct{ *Resolver }
|
||||
|
||||
Reference in New Issue
Block a user