Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -14,9 +14,6 @@ import (
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// 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
|
||||
|
||||
@@ -19,12 +19,7 @@ import (
|
||||
|
||||
// Login is the resolver for the login field.
|
||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
||||
// The Gin context is needed for two things GraphQL cannot express: the
|
||||
// client IP for rate limiting, and setting response cookies. It is
|
||||
// smuggled in by AuthContextMiddleware.
|
||||
//
|
||||
// This mutation mirrors handlers.Store.Login; the two share the limiter
|
||||
// and services.Auth, so the same 5/min budget covers both entry points.
|
||||
// Gin context for the client IP and cookies. Shares the REST login's limiter.
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
@@ -34,8 +29,6 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("too many login attempts, please try again later")
|
||||
}
|
||||
|
||||
// Identical message for unknown user and wrong password, so the API
|
||||
// cannot be used to enumerate usernames.
|
||||
var user models.User
|
||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
@@ -52,8 +45,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
|
||||
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
// The payload carries no token: the tokens only ever travel as HttpOnly
|
||||
// cookies, so client JavaScript never sees them.
|
||||
// Tokens travel only as HttpOnly cookies.
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
@@ -64,12 +56,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
// Bumping the token version is what actually revokes the tokens; clearing
|
||||
// the cookies only stops the browser presenting them. Both are best
|
||||
// effort and logout always reports success, matching the REST endpoint.
|
||||
// Best effort, always succeeds, like the REST endpoint.
|
||||
if userID, ok := UserIDFromCtx(ctx); ok {
|
||||
// The context only carries claims from a token that already
|
||||
// verified, so this cannot be used to revoke someone else's sessions.
|
||||
// Claims in ctx are already verified, so this can't target others.
|
||||
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
|
||||
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
|
||||
}
|
||||
@@ -92,11 +81,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Shared with the REST refresh endpoint, but the messages below are the
|
||||
// ones this resolver already returned, so the GraphQL error strings are
|
||||
// unchanged. Admin status and the token version are both re-read from the
|
||||
// database here, which is what lets a revoked admin flag or a logout take
|
||||
// effect on refresh.
|
||||
// Re-reads admin and token version from the DB.
|
||||
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
|
||||
if err != nil {
|
||||
switch {
|
||||
@@ -121,16 +106,12 @@ 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".
|
||||
// Not @signedIn: this query's error has always been "unauthorized".
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Read fresh from the database rather than returned from the token
|
||||
// claims, so `me` reflects the current username and admin flag.
|
||||
var user models.User
|
||||
user.ID = userID
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
|
||||
@@ -12,10 +12,8 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// The SPA puts these values straight into a style binding, as
|
||||
// `background-color` and `url("<image>")`. Vue sets them through the CSSOM,
|
||||
// so nothing can escape into other properties, but a quote or bracket in the
|
||||
// image could still end the url() early — hence the narrow shapes.
|
||||
// These go into a style binding; a quote or bracket in the image could still
|
||||
// end url() early, hence the narrow shapes.
|
||||
var (
|
||||
// A hex colour, a colour name, or one of the colour functions — named,
|
||||
// so that url() and friends don't pass as a "function".
|
||||
|
||||
@@ -23,9 +23,7 @@ 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) {
|
||||
// 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.
|
||||
// Loaded first so the deleted record can be returned and a bad id is "not found".
|
||||
var bookmark models.Bookmark
|
||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -15,9 +15,7 @@ import (
|
||||
|
||||
// CreateBox is the resolver for the createBox field.
|
||||
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
|
||||
// Framed defaults to true here rather than in the gorm tag — see the
|
||||
// comment on models.Box.Framed. Sizes not supplied fall back to the
|
||||
// same 300x200 the column defaults use.
|
||||
// Framed defaults here, not in the gorm tag; see models.Box.Framed.
|
||||
box := models.Box{
|
||||
Page: input.Page,
|
||||
Kind: input.Kind,
|
||||
@@ -45,8 +43,7 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
|
||||
if input.AdminOnly != nil {
|
||||
box.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
// A linked box takes its html from the component, so its own is
|
||||
// dropped rather than stored as a copy that would quietly go stale.
|
||||
// A linked box's own html would only go stale.
|
||||
if input.ComponentID != nil {
|
||||
id := uint(*input.ComponentID)
|
||||
exists, err := componentExists(r.Store.DB, id)
|
||||
@@ -75,10 +72,8 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
|
||||
|
||||
// UpdateBox is the resolver for the updateBox field.
|
||||
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
|
||||
// Partial update: nil fields are left alone. The canvas sends only the
|
||||
// geometry after a drag and only the html after an edit, so this is
|
||||
// what keeps the two from overwriting each other. Kind is not
|
||||
// updatable — switching a widget box to html is a delete and create.
|
||||
// Partial: the canvas sends only geometry after a drag and only html after
|
||||
// an edit, so neither overwrites the other.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -87,8 +82,7 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
|
||||
box.Widget = input.Widget
|
||||
}
|
||||
if input.HTML != nil {
|
||||
// A linked box's html is the component's; changing it here would
|
||||
// only fork a copy. The editor sends it to updateComponent instead.
|
||||
// Edit linked html via updateComponent, or it forks a copy.
|
||||
if box.ComponentID != nil {
|
||||
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
|
||||
}
|
||||
@@ -140,12 +134,8 @@ func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box,
|
||||
|
||||
// Boxes is the resolver for the boxes field.
|
||||
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
|
||||
// Public: this is the page layout every visitor loads. Ordered by z so
|
||||
// DOM order matches stacking order, which keeps tab order sensible.
|
||||
//
|
||||
// What is admin-only is filtered here rather than hidden in the browser,
|
||||
// so a private note never reaches anyone else: an adminOnly page answers
|
||||
// with no boxes at all, and adminOnly boxes are left out of the rest.
|
||||
// Ordered by z so DOM and tab order match stacking. Admin-only content is
|
||||
// filtered server-side so it never reaches anyone else.
|
||||
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for box.resolvers.go. Kept out of that file because
|
||||
// gqlgen moves unknown code in a resolvers file to the end, under a warning
|
||||
// comment, on every regenerate.
|
||||
// Helpers live outside *.resolvers.go because gqlgen moves unknown code there.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -26,9 +24,7 @@ func setInt(dst *int, src *int) {
|
||||
}
|
||||
}
|
||||
|
||||
// validateBox checks the fields a box needs to render and clamps geometry
|
||||
// rather than rejecting it, because a drag that overshoots the canvas edge
|
||||
// should land at the edge, not fail.
|
||||
// validateBox clamps geometry, so an overshooting drag lands at the edge.
|
||||
func validateBox(box *models.Box) error {
|
||||
if !validPageKey(box.Page) {
|
||||
return errors.New("a box needs a valid page")
|
||||
@@ -59,9 +55,7 @@ func validateBox(box *models.Box) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateShadow trims a box-shadow value and bounds its length. The value is
|
||||
// not parsed: the front end sets it through a style binding, so it can only
|
||||
// ever be the one property, and an invalid value just draws no shadow.
|
||||
// validateShadow doesn't parse: a style binding confines it to one property.
|
||||
func validateShadow(shadow *string) error {
|
||||
*shadow = strings.TrimSpace(*shadow)
|
||||
if len(*shadow) > maxShadowLen {
|
||||
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
|
||||
// Uses is the resolver for the uses field.
|
||||
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
|
||||
// One count per component, which is fine for an admin-only list of a
|
||||
// handful; soft-deleted boxes are excluded by GORM's default scope.
|
||||
var count int64
|
||||
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
@@ -27,7 +25,6 @@ func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (in
|
||||
|
||||
// CreateComponent is the resolver for the createComponent field.
|
||||
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
|
||||
// Framed defaults to true and the size to 300x200, as for a new box.
|
||||
name, err := usableComponentName(r.Store.DB, input.Name, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -57,8 +54,7 @@ func (r *mutationResolver) CreateComponent(ctx context.Context, input model.Crea
|
||||
|
||||
// UpdateComponent is the resolver for the updateComponent field.
|
||||
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
|
||||
// Partial, like updateBox. Nothing to do for the linked boxes: they
|
||||
// read the html from here every time they are fetched.
|
||||
// Linked boxes read the html from here, so nothing else to update.
|
||||
var c models.Component
|
||||
if err := r.Store.DB.First(&c, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -100,9 +96,7 @@ func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input mo
|
||||
|
||||
// DeleteComponent is the resolver for the deleteComponent field.
|
||||
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
|
||||
// The linked boxes keep showing what they showed, as copies, so
|
||||
// deleting a component never changes a page. One transaction, so a
|
||||
// failure can't leave boxes linked to a deleted component.
|
||||
// Linked boxes become copies, so deleting never changes a page.
|
||||
var c models.Component
|
||||
if err := r.Store.DB.First(&c, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -121,9 +115,8 @@ func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models
|
||||
|
||||
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
|
||||
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
|
||||
// The box becomes the component's first linked instance, so carrying
|
||||
// on editing it edits the component. A box that is already linked
|
||||
// would make a component of a component's html; detach it first.
|
||||
// The box becomes the first linked instance. A linked box must be
|
||||
// detached first.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -161,8 +154,6 @@ func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name
|
||||
|
||||
// DetachBox is the resolver for the detachBox field.
|
||||
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
|
||||
// The html is filled in from the component and then saved, which is
|
||||
// exactly the copy fillLinked otherwise never lets reach the row.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -27,9 +27,6 @@ func cleanComponentName(name string) (string, error) {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// componentNameTaken reports whether a live component other than exceptID
|
||||
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
|
||||
// sentence rather than a constraint violation.
|
||||
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||
@@ -53,12 +50,8 @@ func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// fillLinked sets each linked box's in-memory HTML to its component's, with
|
||||
// one query for all of them. Only for boxes about to be returned or
|
||||
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
|
||||
// freeze a copy of the component into it. A box whose component has gone
|
||||
// (deleted outside deleteComponent, which detaches first) is left with
|
||||
// empty HTML rather than failing the whole page.
|
||||
// fillLinked sets linked boxes' HTML in memory only: saving a filled box would
|
||||
// freeze a copy into it. A missing component leaves the HTML empty.
|
||||
func fillLinked(db *gorm.DB, boxes []models.Box) error {
|
||||
var ids []uint
|
||||
for _, b := range boxes {
|
||||
|
||||
@@ -7,17 +7,10 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// This file is the bridge between Gin's request handling and gqlgen's
|
||||
// resolvers. gqlgen resolvers receive only a context.Context, so
|
||||
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
|
||||
// the *gin.Context itself into that context, and these accessors read them
|
||||
// back out.
|
||||
// Resolvers get only a context.Context; AuthContextMiddleware puts the
|
||||
// verified claims and the *gin.Context into it.
|
||||
|
||||
// contextKey is a private named type so that these keys can never collide
|
||||
// with a key set by another package — the reason the standard library warns
|
||||
// against using bare strings as context keys. Note the string value
|
||||
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
|
||||
// *Gin* context, but the two are unrelated and do not see each other.
|
||||
// Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context.
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
@@ -25,10 +18,8 @@ const (
|
||||
ginContextKey contextKey = "ginContext"
|
||||
)
|
||||
|
||||
// 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. Turning "anonymous"
|
||||
// into a refusal is the job of the schema directives, per field.
|
||||
// UserClaimsFromCtx returns nil for anonymous requests; refusing is the
|
||||
// directives' job.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -37,12 +28,6 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
return claims
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -55,12 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// 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.
|
||||
// IsAdminFromCtx reads the token, so a revoked flag applies on expiry.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -70,10 +50,7 @@ func IsAdminFromCtx(ctx context.Context) bool {
|
||||
return ok && admin
|
||||
}
|
||||
|
||||
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
|
||||
// for things that live outside GraphQL's model: setting auth cookies and
|
||||
// reading the client IP. Returns nil if the middleware was not installed,
|
||||
// which the auth resolvers surface as an error rather than panicking.
|
||||
// GinContextFromCtx is nil if the middleware wasn't installed.
|
||||
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
||||
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
||||
if !ok {
|
||||
|
||||
@@ -36,18 +36,14 @@ func cleanCoverLetterName(name string) (string, error) {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// coverLetterNameTaken reports whether a live letter other than exceptID has
|
||||
// this name. Checked up front, like layoutNameTaken, so the admin gets a
|
||||
// sentence rather than a constraint violation.
|
||||
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// checkCoverLetterBody reports why body can't be stored. The server never
|
||||
// reads inside it, so it only has to be a JSON object of a sane size — an
|
||||
// array or a bare string would be a frontend bug worth refusing early.
|
||||
// checkCoverLetterBody: the server never reads inside it, so it need only be a
|
||||
// JSON object of sane size.
|
||||
func checkCoverLetterBody(body string) error {
|
||||
if len(body) > maxCoverLetterBodyLen {
|
||||
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
|
||||
@@ -60,9 +56,7 @@ func checkCoverLetterBody(body string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanSnippetText trims text and reports why it can't be a bank paragraph.
|
||||
// Counted in characters, not bytes, since the limit is about how much prose
|
||||
// fits rather than storage.
|
||||
// cleanSnippetText counts characters, not bytes.
|
||||
func cleanSnippetText(text string) (string, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
|
||||
@@ -7,34 +7,16 @@ import (
|
||||
"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.
|
||||
// The @admin and @signedIn directives. The front end shows these error
|
||||
// strings verbatim (the tracker reads "admin access required" as a lapsed
|
||||
// session), so don't reword them.
|
||||
|
||||
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.
|
||||
// Directives is shared by main and the tests. A nil directive fails closed.
|
||||
func Directives() DirectiveRoot {
|
||||
return DirectiveRoot{
|
||||
Admin: requireAdmin,
|
||||
@@ -42,9 +24,6 @@ func Directives() DirectiveRoot {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -52,9 +31,6 @@ func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error
|
||||
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)
|
||||
|
||||
@@ -20,15 +20,8 @@ import (
|
||||
"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.
|
||||
// Covers both the directive functions and which fields carry them. No
|
||||
// database: refused fields never reach their resolvers.
|
||||
|
||||
// withClaims builds the context AuthContextMiddleware would for a verified
|
||||
// token. Claims are decoded from JSON in production, hence float64 for the id.
|
||||
@@ -100,9 +93,7 @@ func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// guardOf fails on both directives at once: @signedIn adds nothing to @admin.
|
||||
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
|
||||
t.Helper()
|
||||
admin := field.Directives.ForName("admin") != nil
|
||||
@@ -123,14 +114,8 @@ 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.
|
||||
// publicMutations is the allow-list; any other unguarded mutation fails
|
||||
// TestEveryMutationIsGuarded.
|
||||
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||
|
||||
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
@@ -159,9 +144,7 @@ func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Pinned so loosening @admin to @signedIn needs a change here.
|
||||
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||
var got []string
|
||||
@@ -176,15 +159,8 @@ func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Queries are public by default, so the guarded set is pinned exactly.
|
||||
// me, messages and spotifyNeedsReauth vary by caller without a directive.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
@@ -217,9 +193,7 @@ func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Keep directives on root fields: the tests above only look there.
|
||||
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
for name, def := range schema.Types {
|
||||
@@ -234,10 +208,7 @@ func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// execute runs an operation as main wires it, with an empty Store.
|
||||
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
|
||||
t.Helper()
|
||||
srv := handler.New(NewExecutableSchema(Config{
|
||||
@@ -298,9 +269,7 @@ func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// IDs stay quoted decimal strings on the wire, accepting strings or numbers.
|
||||
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
|
||||
for _, id := range []uint{0, 1, 12, 4294967295} {
|
||||
var asUint, asInt bytes.Buffer
|
||||
|
||||
+11
-47
@@ -1,51 +1,15 @@
|
||||
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
|
||||
// serves most of the site's data.
|
||||
// Package graph is the GraphQL layer behind POST /graphql.
|
||||
//
|
||||
// How the pieces fit:
|
||||
// graph/schema/*.graphql is the source of truth; gqlgen regenerates
|
||||
// generated.go and model/models_gen.go (never edit them). gqlgen.yml maps
|
||||
// object types onto the GORM structs in backend/models.
|
||||
//
|
||||
// - graph/schema/*.graphql is the source of truth. Running
|
||||
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
|
||||
// and model/models_gen.go, and adds stubs for any new field to the
|
||||
// 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. 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).
|
||||
// - 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
|
||||
// the plain context.Context a resolver receives.
|
||||
// Nothing guards the endpoint itself. A field is protected only by an
|
||||
// @admin or @signedIn directive (directives.go); a field with neither is
|
||||
// public. directives_test.go fails if a mutation has neither and isn't on its
|
||||
// public allow-list. Finer rules (post ownership, hiding private messages)
|
||||
// live in resolvers via IsAdminFromCtx / UserIDFromCtx.
|
||||
//
|
||||
// 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. 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
|
||||
// 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
|
||||
// them by hand may be moved to the end of the file on the next generate.
|
||||
// gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are
|
||||
// untouched.
|
||||
package graph
|
||||
|
||||
@@ -24,10 +24,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
|
||||
// would dereference it, so return null to the client instead. The cache
|
||||
// is deliberately not written in that case, so an empty feed is retried
|
||||
// on the next request.
|
||||
// Not cached, so an empty feed is retried next time.
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -5,10 +5,7 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
|
||||
// commit message out of the doubly-encoded Content field as it goes. It
|
||||
// dereferences feed, so callers must rule out the (nil, nil) that
|
||||
// FetchLatestFeed returns for an empty feed.
|
||||
// mapGiteaFeed requires a non-nil feed.
|
||||
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
||||
return &model.GiteaFeedItem{
|
||||
AvatarURL: feed.ActUser.AvatarURL,
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
|
||||
// for the same reason as box_helpers.go.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -17,9 +14,7 @@ import (
|
||||
|
||||
const maxLayoutNameLen = 100
|
||||
|
||||
// layoutBox is one box as a layout stores it: what makes it look the way it
|
||||
// does, without the id and page that tie a row to one canvas. Changing these
|
||||
// field names would make older layouts load with the renamed fields empty.
|
||||
// layoutBox is a box minus id and page. Renaming fields breaks saved layouts.
|
||||
type layoutBox struct {
|
||||
Kind string `json:"kind"`
|
||||
Widget *string `json:"widget,omitempty"`
|
||||
@@ -34,9 +29,7 @@ type layoutBox struct {
|
||||
Shadow string `json:"shadow,omitempty"`
|
||||
HideOnMobile bool `json:"hideOnMobile"`
|
||||
AdminOnly bool `json:"adminOnly"`
|
||||
// ComponentID is the component a linked box was linked to. HTML is
|
||||
// stored too, so that a layout outlives the component: loading links the
|
||||
// box again if the component is still there and uses HTML if not.
|
||||
// HTML is kept too, so a layout outlives a deleted component.
|
||||
ComponentID *uint `json:"componentId,omitempty"`
|
||||
}
|
||||
|
||||
@@ -46,7 +39,6 @@ type layoutBackground struct {
|
||||
Fit string `json:"fit"`
|
||||
}
|
||||
|
||||
// cleanLayoutName trims name and reports why it can't be a layout's name.
|
||||
func cleanLayoutName(name string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
@@ -58,18 +50,14 @@ func cleanLayoutName(name string) (string, error) {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// layoutNameTaken reports whether a live layout other than exceptID has this
|
||||
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
|
||||
// than a constraint violation.
|
||||
// Checked up front so the admin gets a sentence, not a constraint violation.
|
||||
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// canvasExists reports whether page is a canvas boxes can be put on: the
|
||||
// landing page, or a live Page. Loading a layout onto any other key would
|
||||
// leave its boxes where nothing shows them.
|
||||
// canvasExists: boxes on any other key would never be shown.
|
||||
func canvasExists(db *gorm.DB, page string) (bool, error) {
|
||||
if page == "index" {
|
||||
return true, nil
|
||||
@@ -82,16 +70,13 @@ func canvasExists(db *gorm.DB, page string) (bool, error) {
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// pageBoxes is every box on page, adminOnly ones included, in the order the
|
||||
// boxes query returns them. Only for admin-only callers.
|
||||
// pageBoxes includes adminOnly boxes; admin callers only.
|
||||
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
|
||||
var boxes []models.Box
|
||||
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
|
||||
return boxes, err
|
||||
}
|
||||
|
||||
// snapshotPage is an unsaved Layout holding page's boxes and background as
|
||||
// they are now. empty is true when there was nothing to keep.
|
||||
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
|
||||
boxes, err := pageBoxes(db, page)
|
||||
if err != nil {
|
||||
@@ -139,7 +124,6 @@ func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
|
||||
return boxes, nil
|
||||
}
|
||||
|
||||
// pageLabel is how a page key reads in a generated layout name.
|
||||
func pageLabel(page string) string {
|
||||
if page == "index" {
|
||||
return "/"
|
||||
@@ -147,7 +131,6 @@ func pageLabel(page string) string {
|
||||
return "/" + page
|
||||
}
|
||||
|
||||
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
|
||||
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
|
||||
name := base
|
||||
for n := 2; ; n++ {
|
||||
@@ -159,22 +142,17 @@ func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// applyLayoutTo copies layout onto page inside tx; see applyLayout in
|
||||
// layout.graphql for what replace does. The copies are new rows, so the page
|
||||
// owns them outright.
|
||||
// applyLayoutTo creates new rows, so nothing stays linked to the layout.
|
||||
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
|
||||
stored, err := decodeLayoutBoxes(layout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Added on top, the copies keep their own stacking order but all sit
|
||||
// above what the page already has.
|
||||
// Added copies stack above the page's existing boxes.
|
||||
zShift := 0
|
||||
if replace {
|
||||
// What is being replaced is kept first, so a replace can be undone by
|
||||
// loading that layout back. A page with nothing on it has nothing to
|
||||
// keep.
|
||||
// Save what's being replaced first, so a replace can be undone.
|
||||
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
|
||||
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
|
||||
if err != nil {
|
||||
@@ -234,7 +212,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
|
||||
}
|
||||
}
|
||||
|
||||
// Adding on top leaves the page's own background alone.
|
||||
if replace && layout.Background != nil {
|
||||
var saved layoutBackground
|
||||
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
|
||||
@@ -251,8 +228,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
|
||||
return nil
|
||||
}
|
||||
|
||||
// liveComponents is the set of components the stored boxes were linked to
|
||||
// that still exist, so applyLayoutTo knows which boxes to link again.
|
||||
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
|
||||
var ids []uint
|
||||
for _, b := range stored {
|
||||
|
||||
@@ -12,21 +12,15 @@ import (
|
||||
)
|
||||
|
||||
// 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.
|
||||
// The chat hub's connection number, not a User id.
|
||||
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.AuthorID), nil
|
||||
}
|
||||
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
// Non-admins get the public subset rather than an error, so the chat
|
||||
// history loads for everyone. The same filter is applied to the history
|
||||
// replayed over the WebSocket (services.HandleWebSocket) — change one and
|
||||
// the other must change too.
|
||||
//
|
||||
// Note the ordering differs between the two: newest first here, oldest
|
||||
// first over the socket.
|
||||
// Non-admins get the public subset. Keep in step with the WebSocket
|
||||
// history filter (services.HandleWebSocket), which is oldest first.
|
||||
var messages []models.Message
|
||||
query := r.Store.DB.Order("created_at DESC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
|
||||
@@ -8,39 +8,20 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AuthContextMiddleware prepares the request context for the GraphQL handler.
|
||||
//
|
||||
// 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 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.
|
||||
//
|
||||
// Unlike the REST path there is no refresh-token fallback here, so once the
|
||||
// access token expires GraphQL treats the caller as anonymous until the front
|
||||
// end refreshes.
|
||||
// AuthContextMiddleware never rejects: a bad or missing token leaves the
|
||||
// context anonymous and the directives decide. No refresh fallback.
|
||||
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||
|
||||
accessToken, err := c.Cookie("access_token")
|
||||
if err == nil {
|
||||
// The database is needed to check the token version, so a
|
||||
// revoked token (logout, password change) leaves the request
|
||||
// anonymous instead of continuing to authorise mutations.
|
||||
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
|
||||
if err == nil {
|
||||
ctx = context.WithValue(ctx, userClaimsKey, claims)
|
||||
}
|
||||
}
|
||||
|
||||
// The context is immutable, so the enriched one has to be written
|
||||
// back onto the request for the gqlgen handler to see it.
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -45,9 +45,7 @@ func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePag
|
||||
|
||||
// UpdatePage is the resolver for the updatePage field.
|
||||
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
|
||||
// Partial update, like updateBox. A new slug moves the page's boxes and
|
||||
// background with it in the same transaction, since both find their page
|
||||
// by slug.
|
||||
// Partial. A new slug moves the boxes and background in the same transaction.
|
||||
var page models.Page
|
||||
if err := r.Store.DB.First(&page, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -134,9 +132,7 @@ func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
|
||||
|
||||
// Page is the resolver for the page field.
|
||||
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
|
||||
// Null, not an error, for a missing page: the SPA's catch-all route asks
|
||||
// this for every unknown path and shows its 404 on null. An adminOnly
|
||||
// page reads as missing to everyone else, so its existence isn't leaked.
|
||||
// Null for missing or hidden pages: the SPA shows its 404 on null.
|
||||
var page models.Page
|
||||
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
|
||||
@@ -13,20 +13,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// pageKeyPattern is the shape of a box's page key and of a page slug: lower
|
||||
// case words joined by hyphens, in one or more /-separated segments. It is
|
||||
// URL-safe as it stands, so the front end can use a slug as a path without
|
||||
// escaping it.
|
||||
// Slugs are URL-safe as they stand.
|
||||
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
|
||||
|
||||
const maxSlugLen = 100
|
||||
|
||||
// reservedFirstSegments are paths a page could never be reached at, because
|
||||
// Caddy or one of the SPA's own routes answers them first (see
|
||||
// caddy/routes.caddy and vue/src/router/index.js), plus the
|
||||
// landing page's key "index", whose boxes a page of the same slug would
|
||||
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
|
||||
// pages under it and the home page /stp are all canvas pages.
|
||||
// Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and
|
||||
// "stp" are canvas pages, so not reserved.
|
||||
var reservedFirstSegments = map[string]bool{
|
||||
"stp2": true, "index": true, "admin": true, "cv": true,
|
||||
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
|
||||
@@ -51,9 +44,7 @@ func validateSlug(slug string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageHiddenFrom reports whether the page with this key is an adminOnly page
|
||||
// and the caller is not an admin. A key with no Page row (the landing page,
|
||||
// or a page that doesn't exist) is not hidden.
|
||||
// A key with no Page row is never hidden.
|
||||
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
|
||||
if IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
@@ -63,9 +54,7 @@ func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// slugTaken reports whether a live page other than exceptID has this slug.
|
||||
// Checked up front so the admin gets a sentence rather than a constraint
|
||||
// violation; the partial unique index still backs it up.
|
||||
// Checked up front for a readable error; the partial unique index backs it.
|
||||
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
|
||||
|
||||
@@ -14,10 +14,7 @@ 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, 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.
|
||||
// @signedIn: places are the site's one shared list, with no ownership.
|
||||
place := models.Place{
|
||||
Title: input.Title,
|
||||
Location: input.Location,
|
||||
|
||||
@@ -16,16 +16,12 @@ import (
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
// @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")
|
||||
}
|
||||
|
||||
// The admin form submits whatever is in its fields, so an accidental click
|
||||
// on an empty form would otherwise publish a blank post to the feed.
|
||||
// Stops a stray click publishing a blank post.
|
||||
if strings.TrimSpace(input.Title) == "" {
|
||||
return nil, fmt.Errorf("a post needs a title")
|
||||
}
|
||||
@@ -50,15 +46,12 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Only the author may edit, even among admins.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
|
||||
// Both fields are non-pointer in the input, so this is a full replace —
|
||||
// omitting one in the mutation blanks it rather than leaving it alone.
|
||||
// Full replace: an omitted field is blanked.
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
@@ -84,9 +77,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
// Soft delete. The error is propagated: reporting success for a delete
|
||||
// that did not happen would leave the client showing the post as gone
|
||||
// until the next reload.
|
||||
if err := r.Store.DB.Delete(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -96,9 +86,7 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
|
||||
// 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.
|
||||
// Without it the field is nil and the schema's author field resolves to
|
||||
// null — there is no lazy loading and no error to tell you why.
|
||||
// Without Preload, author resolves to null silently.
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -7,17 +7,7 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// It serves as dependency injection for your app, add any dependencies you require
|
||||
// here.
|
||||
|
||||
// Resolver is the root of the GraphQL schema and the only dependency every
|
||||
// resolver has. Rather than listing dependencies individually it holds the
|
||||
// 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, 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.
|
||||
// Resolver holds the same handlers.Store the REST handlers use.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -21,8 +21,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.Time), nil
|
||||
}
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
# The background behind a canvas page, keyed by the same page key as its
|
||||
# boxes ("index" for the landing page, or a Page's slug), so the landing
|
||||
# page and every other canvas page are set the same way. Edited from the
|
||||
# canvas's "Background" button; see models.Background.
|
||||
#
|
||||
# Anyone may read it, as part of the page, except that an adminOnly page's
|
||||
# background is null to everyone but an admin.
|
||||
# A page key's background; null for an adminOnly page unless admin.
|
||||
|
||||
type Background {
|
||||
id: ID!
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# Boxes on a canvas page: the landing page (page "index") or an
|
||||
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
|
||||
# Anyone may read a page's layout — it is the page — but only an admin may
|
||||
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
|
||||
# are px on a fixed 1400px-wide design canvas; see models.Box.
|
||||
#
|
||||
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
|
||||
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
|
||||
# componentId is linked to that Component: its html is the component's, and
|
||||
# updateBox refuses to change it (component.graphql).
|
||||
# Boxes on a page key. Public reads, admin writes; adminOnly boxes go to
|
||||
# admins only. kind is "widget" or "html" (sandboxed iframe).
|
||||
|
||||
type Box {
|
||||
id: ID!
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# Components: named HTML boxes that can be placed on any canvas page, either
|
||||
# as a copy (an ordinary box) or linked (a Box whose componentId is set).
|
||||
# Linked boxes share only the html — editing a component changes every box
|
||||
# linked to it — while title, geometry, frame and visibility stay each box's
|
||||
# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box
|
||||
# starts with. See models.Component and graph/component_helpers.go.
|
||||
#
|
||||
# Admin only throughout, reads included, because a component may have been
|
||||
# saved from an adminOnly note. A linked box's html still reaches visitors
|
||||
# through the boxes query, which is the point.
|
||||
# Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes
|
||||
# share only the html. Admin only, reads included.
|
||||
|
||||
type Component {
|
||||
id: ID!
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
# Saved layouts: a named copy of one canvas page's boxes and background,
|
||||
# which can be loaded onto any canvas page — the landing page ("index") or a
|
||||
# Page's slug. Loading copies: the new boxes belong to the target page, so
|
||||
# editing a page afterwards never changes the layout or another page. Moving
|
||||
# a layout is saving it on one page and loading it on another with
|
||||
# replace: true. See models.Layout and graph/layout_helpers.go.
|
||||
#
|
||||
# Admin only throughout, reads included, because a layout keeps a page's
|
||||
# adminOnly boxes along with the rest.
|
||||
# Saved snapshots of a page's boxes and background; loading copies them.
|
||||
# Admin only, reads included, since layouts keep adminOnly boxes.
|
||||
|
||||
type Layout {
|
||||
id: ID!
|
||||
@@ -39,10 +32,6 @@ extend type Mutation {
|
||||
# Renames it; what a layout holds never changes after it is saved.
|
||||
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
|
||||
deleteLayout(id: ID!): Layout! @admin
|
||||
# Copies the layout onto `page` and answers with that page's boxes.
|
||||
# replace: false adds the copies on top of what is there, leaving the
|
||||
# background alone. replace: true first saves the page as a layout named
|
||||
# "<page> before <layout>, <time>", then swaps its boxes and background
|
||||
# for the layout's.
|
||||
# replace: true first saves the page as a layout, then swaps in this one.
|
||||
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
|
||||
}
|
||||
|
||||
@@ -1,35 +1,10 @@
|
||||
# Root of the GraphQL schema.
|
||||
#
|
||||
# Query and Mutation are declared here with no fields; every other file in this
|
||||
# directory adds to them with `extend type Query` / `extend type Mutation`.
|
||||
# That is what lets the schema be split one file per domain, matching the
|
||||
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
|
||||
#
|
||||
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
|
||||
# serialised as RFC 3339.
|
||||
#
|
||||
# These files are the source of truth: after editing one, run
|
||||
# go run github.com/99designs/gqlgen generate
|
||||
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
|
||||
# Note that `#` comments like this one are invisible to clients; a `"""` block
|
||||
# would become a schema description and show up in introspection.
|
||||
# Root types; each file extends Query and Mutation. Use # comments, not """
|
||||
# (descriptions show up in introspection).
|
||||
|
||||
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.
|
||||
# A field is public unless it has @admin or @signedIn (graph/directives.go).
|
||||
# directives_test.go enforces this for mutations.
|
||||
directive @admin on FIELD_DEFINITION
|
||||
directive @signedIn on FIELD_DEFINITION
|
||||
|
||||
|
||||
@@ -3,15 +3,8 @@ package graph
|
||||
// This file is hand-written and is never regenerated by gqlgen — it is not
|
||||
// named after a schema file, so `gqlgen generate` leaves it alone.
|
||||
|
||||
// ptrs copies a slice of values into a slice of pointers to those values.
|
||||
//
|
||||
// Every list query loads rows with Find(&xs) into a []T and then has to hand
|
||||
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
|
||||
// &xs[i] is safe: the slice is never appended to after this point, so the
|
||||
// backing array cannot move and the pointers stay valid.
|
||||
//
|
||||
// Loading straight into a []*T would avoid the copy but changes the query
|
||||
// GORM emits, so the copy is kept deliberately.
|
||||
// ptrs turns []T into []*T for gqlgen. Loading into []*T directly would
|
||||
// change the SQL GORM emits.
|
||||
func ptrs[T any](xs []T) []*T {
|
||||
result := make([]*T, len(xs))
|
||||
for i := range xs {
|
||||
|
||||
@@ -51,11 +51,7 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
||||
}
|
||||
|
||||
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
|
||||
//
|
||||
// Admin-gated: false for everyone else, so this query leaks nothing. Admin is
|
||||
// read from the access-token claims the AuthContextMiddleware resolved, not
|
||||
// the database — the same trade-off AdminMiddleware makes (revocation waits
|
||||
// for token expiry).
|
||||
// False for non-admins.
|
||||
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||
if r.Store.SpotifyClient != nil {
|
||||
return false, nil
|
||||
|
||||
@@ -5,10 +5,6 @@ import (
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// Converters from the Spotify library's rich types to the deliberately narrow
|
||||
// GraphQL types — the schema exposes only the handful of fields the home page
|
||||
// renders.
|
||||
|
||||
// mapSpotifyImages keeps just the URLs of a set of album images.
|
||||
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
result := make([]*model.SpotifyImage, len(images))
|
||||
@@ -35,10 +31,7 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
}
|
||||
|
||||
// mapRecentItems converts recently played history entries.
|
||||
//
|
||||
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
|
||||
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
|
||||
// takes — the duplication is forced by the library's types.
|
||||
// A RecentlyPlayedItem holds a SimpleTrack, so mapSpotifyTrack can't be reused.
|
||||
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
||||
result := make([]*model.SpotifyRecentItem, len(items))
|
||||
for i, item := range items {
|
||||
|
||||
@@ -8,10 +8,7 @@ import (
|
||||
)
|
||||
|
||||
// mapSteamGames converts Steam API games into the GraphQL shape.
|
||||
//
|
||||
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
|
||||
// serves every game's cover art at a predictable path keyed by app id, so
|
||||
// building the URL here saves an extra API call per game.
|
||||
// Header images follow a predictable CDN path, saving an API call per game.
|
||||
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
||||
result := make([]*model.SteamGame, len(games))
|
||||
for i, g := range games {
|
||||
|
||||
@@ -18,9 +18,6 @@ import (
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
// 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
|
||||
@@ -55,8 +52,7 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Guards against the last admin demoting themselves and locking everyone
|
||||
// out of the admin UI.
|
||||
// Stops the last admin locking everyone out.
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
@@ -76,10 +72,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
|
||||
// SetUserPermissions is the resolver for the setUserPermissions field.
|
||||
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
|
||||
// The whole list is replaced, so the admin panel sends every ticked box
|
||||
// each time. An unknown key is refused rather than dropped, so a stale
|
||||
// front end cannot silently save less than it showed. The stored list is
|
||||
// rebuilt in registry order, which also drops duplicates.
|
||||
// Full replace. Unknown keys are refused so a stale UI can't silently
|
||||
// save less than it showed.
|
||||
want := map[string]bool{}
|
||||
for _, key := range permissions {
|
||||
if !services.ValidPermission(key) {
|
||||
@@ -99,8 +93,7 @@ func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permi
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
// No token bump needed: the permission gate reads this column on every
|
||||
// request, so the change applies to the user's next one.
|
||||
// No token bump: the gate reads this column on every request.
|
||||
user.Permissions = granted
|
||||
if err := r.Store.DB.Save(&user).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -129,6 +122,5 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
|
||||
|
||||
// PermissionTypes is the resolver for the permissionTypes field.
|
||||
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
|
||||
// A copy, so nothing downstream can write through to the registry.
|
||||
return ptrs(slices.Clone(services.PermissionTypes)), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user