Document codebase: comments, per-area READMEs, deployment guide
Readability pass across all four areas of the stack. Comments explain why rather than what, concentrated at the points where behaviour is non-obvious: concurrency, caching, auth, scraping and nginx templating. Backend: doc comments on every exported declaration across handlers, services, models and resolvers. Resolver commentary lives inside function bodies so gqlgen does not strip it on regeneration; schema files use # comments rather than description blocks so introspection output is unchanged. Extracted the duplicated auth-cookie blocks into helpers. Frontend: header comments on every component, store and view, including STATUS: notes marking which of the parallel/legacy views are still live. Documented the non-reactive animation-state pattern, the homeData hub and the WebSocket stale-socket guard. Removed a few dead imports and named the reconnect-backoff and poll-interval constants. Python: module and function docstrings covering the Travelodge scraping contract, the deadline threading, the two-executor concurrency and the NDJSON streaming protocol. Infra: header blocks on every compose file, nginx template, Dockerfile and entrypoint, covering the config selection, envsubst allow-lists, rate-limit semantics and volume persistence. Hoisted the duplicated envsubst variable list in nginx/entrypoint.sh. New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example, backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which stated a 24h access token where main.go sets 7 days. No behaviour change. go build/vet, vite build, py_compile and docker compose config all pass. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -20,6 +20,7 @@ func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, e
|
||||
|
||||
// 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")
|
||||
}
|
||||
@@ -38,6 +39,9 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &activities[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
|
||||
@@ -17,6 +17,12 @@ 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.
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
@@ -26,6 +32,8 @@ 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")
|
||||
@@ -40,24 +48,10 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
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.
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
@@ -68,6 +62,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
// Max-age -1 tells the browser to drop the cookies. Nothing is
|
||||
// invalidated server-side, so a token captured beforehand still works
|
||||
// until it expires.
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
@@ -97,6 +94,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
// Setting the primary key and calling First with no condition makes GORM
|
||||
// look the row up by that key. Admin status is re-read from the database
|
||||
// here, which is what lets a revoked admin flag take effect on refresh.
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
@@ -108,23 +108,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
@@ -136,6 +120,8 @@ func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair on a GraphQL response.
|
||||
//
|
||||
// This mirrors handlers.Store.setAuthCookies — the two cannot be shared
|
||||
// because importing graph from handlers would be a cycle, so any change to
|
||||
// cookie attributes has to be made in both places or login via REST and login
|
||||
// via GraphQL will disagree.
|
||||
//
|
||||
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
|
||||
// true here: the cookies never travel over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
|
||||
// provider while still blocking cross-site POSTs. Each max-age mirrors the
|
||||
// lifetime baked into the token itself.
|
||||
//
|
||||
// It lives in its own file rather than in auth.resolvers.go because gqlgen may
|
||||
// relocate hand-written code in the files it regenerates.
|
||||
func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
}
|
||||
@@ -35,6 +35,9 @@ func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.
|
||||
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.
|
||||
var bookmark models.Bookmark
|
||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -51,6 +54,9 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &bookmarks[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Bookmark, len(bookmarks))
|
||||
for i := range bookmarks {
|
||||
result[i] = &bookmarks[i]
|
||||
|
||||
@@ -7,6 +7,17 @@ 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.
|
||||
|
||||
// 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.
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
@@ -14,6 +25,9 @@ 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.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -22,6 +36,8 @@ 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.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -34,6 +50,11 @@ 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.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -43,6 +64,10 @@ 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.
|
||||
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
||||
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
|
||||
// serves most of the site's data.
|
||||
//
|
||||
// How the pieces fit:
|
||||
//
|
||||
// - 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. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// - 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.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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.
|
||||
package graph
|
||||
@@ -38,6 +38,9 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &favorites[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// GiteaFeed is the resolver for the giteaFeed field.
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
// One-minute cache on the Store, shared by every visitor, so a busy home
|
||||
// page does not hammer the Gitea container.
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
}
|
||||
@@ -23,6 +25,10 @@ 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.
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ 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.
|
||||
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
||||
return &model.GiteaFeedItem{
|
||||
AvatarURL: feed.ActUser.AvatarURL,
|
||||
|
||||
@@ -81,6 +81,8 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
|
||||
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.
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
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;
|
||||
// note this also means a nullable column can never be cleared back to
|
||||
// null through this mutation.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -79,6 +83,8 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
// 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 {
|
||||
return false, err
|
||||
}
|
||||
@@ -87,9 +93,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")
|
||||
}
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -17,12 +17,21 @@ func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, err
|
||||
}
|
||||
|
||||
// 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.
|
||||
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.
|
||||
var messages []models.Message
|
||||
query := r.Store.DB.Order("created_at DESC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
@@ -31,6 +40,9 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error)
|
||||
if err := query.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &messages[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
|
||||
@@ -7,6 +7,18 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 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 pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
//
|
||||
// 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.
|
||||
func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||
@@ -19,6 +31,8 @@ func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
|
||||
@@ -15,6 +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")
|
||||
}
|
||||
@@ -43,6 +46,8 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
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
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -48,10 +48,14 @@ 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.
|
||||
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.
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
@@ -81,6 +85,8 @@ 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 dropped, so a failed delete still reports
|
||||
// success to the client.
|
||||
r.Store.DB.Delete(&post)
|
||||
return &post, nil
|
||||
}
|
||||
@@ -92,10 +98,16 @@ func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
|
||||
// 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.
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &posts[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
|
||||
@@ -7,6 +7,15 @@ 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
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &rows[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
@@ -30,6 +33,8 @@ func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error
|
||||
}
|
||||
|
||||
// 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,3 +1,6 @@
|
||||
# Latest activity from the self-hosted Gitea instance, proxied and cached for
|
||||
# one minute by the backend. Resolves to null when the feed is empty.
|
||||
|
||||
type GiteaFeedItem {
|
||||
avatarUrl: String!
|
||||
repoUrl: String!
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
# Job application tracker. Rows come from these mutations or automatically
|
||||
# from the email sync pipeline (backend/services/email_sync.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:
|
||||
# applied, screening, assessment, interviewing, offer, rejected, withdrawn.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# Chat history. The live chat runs over the WebSocket at /ws, not GraphQL;
|
||||
# this query is the initial page load.
|
||||
#
|
||||
# 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.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
content: String!
|
||||
|
||||
@@ -1,3 +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.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
# 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.
|
||||
|
||||
scalar Time
|
||||
|
||||
type Query
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Spotify "now playing" / "recently played" for the home page. Both resolve to
|
||||
# null / an empty list when the backend has never completed the Spotify OAuth
|
||||
# flow, so the page degrades rather than erroring.
|
||||
|
||||
type SpotifyArtist {
|
||||
name: String!
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Steam presence and recent games for the home page, cached for five minutes.
|
||||
# headerImage is built from the app id rather than returned by Steam's API.
|
||||
|
||||
type SteamGame {
|
||||
appId: Int!
|
||||
name: String!
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
|
||||
// A nil client means the OAuth flow has never been completed. Report that
|
||||
// as null rather than an error so the home page renders without it.
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -38,6 +40,8 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
// One-minute cache. This resolver is the only writer of that cache; the
|
||||
// REST /spotify/recent endpoint reads it but never fills it.
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ 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))
|
||||
for i, img := range images {
|
||||
@@ -13,6 +18,7 @@ func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
return result
|
||||
}
|
||||
|
||||
// mapSpotifyTrack converts a currently-playing track.
|
||||
func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
artists := make([]*model.SpotifyArtist, len(track.Artists))
|
||||
for i, a := range track.Artists {
|
||||
@@ -28,6 +34,11 @@ 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.
|
||||
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
||||
result := make([]*model.SpotifyRecentItem, len(items))
|
||||
for i, item := range items {
|
||||
|
||||
@@ -19,6 +19,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Five-minute cache across both Steam calls, which are made together and
|
||||
// expire together.
|
||||
if r.Store.SteamFresh() {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
@@ -36,6 +38,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PersonaState 0 is offline; every higher value is some flavour of
|
||||
// online. A nil summary (private profile) reads as offline.
|
||||
online := false
|
||||
if summary != nil {
|
||||
online = summary.PersonaState > 0
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// 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.
|
||||
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
||||
result := make([]*model.SteamGame, len(games))
|
||||
for i, g := range games {
|
||||
|
||||
@@ -20,6 +20,8 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
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.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -62,6 +64,8 @@ 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.
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
@@ -88,6 +92,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &users[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
|
||||
Reference in New Issue
Block a user