Spotify unauthenticated: throttled log + admin reconnect on Listening widget
Deploy with Docker Compose / deploy (push) Successful in 40s

- Backend logs a rate-limited (1/h) "not authenticated" line when a resolver
  finds the Spotify client nil instead of silently degrading to null.
- New public-but-gated spotifyNeedsReauth query: false for everyone except
  an admin session whose backend has no client.
- The /stp Listening widget offers admins a "Reconnect Spotify" button that
  hits /api/spotify/auth and navigates to the returned authorisation URL;
  non-admins still see the widget degrade as before.

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
2026-09-22 22:54:48 +01:00
co-authored by Claude Code
parent 241acb82d9
commit ff186f04a7
6 changed files with 163 additions and 19 deletions
+71 -18
View File
@@ -170,24 +170,25 @@ type ComplexityRoot struct {
}
Query struct {
Activities func(childComplexity int) int
Bookmarks func(childComplexity int) int
Favorites func(childComplexity int) int
GiteaFeed func(childComplexity int) int
JobAppReferences func(childComplexity int) int
JobApplication func(childComplexity int, id int) int
JobApplications func(childComplexity int) int
Me func(childComplexity int) int
Messages func(childComplexity int) int
Places func(childComplexity int) int
Post func(childComplexity int, id int) int
Posts func(childComplexity int) int
RowingSessions func(childComplexity int) int
SpotifyListening func(childComplexity int) int
SpotifyRecent func(childComplexity int) int
SteamStatus func(childComplexity int) int
User func(childComplexity int, id int) int
Users func(childComplexity int) int
Activities func(childComplexity int) int
Bookmarks func(childComplexity int) int
Favorites func(childComplexity int) int
GiteaFeed func(childComplexity int) int
JobAppReferences func(childComplexity int) int
JobApplication func(childComplexity int, id int) int
JobApplications func(childComplexity int) int
Me func(childComplexity int) int
Messages func(childComplexity int) int
Places func(childComplexity int) int
Post func(childComplexity int, id int) int
Posts func(childComplexity int) int
RowingSessions func(childComplexity int) int
SpotifyListening func(childComplexity int) int
SpotifyNeedsReauth func(childComplexity int) int
SpotifyRecent func(childComplexity int) int
SteamStatus func(childComplexity int) int
User func(childComplexity int, id int) int
Users func(childComplexity int) int
}
Rowing struct {
@@ -321,6 +322,7 @@ type QueryResolver interface {
RowingSessions(ctx context.Context) ([]*models.Rowing, error)
SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error)
SpotifyRecent(ctx context.Context) ([]*model.SpotifyRecentItem, error)
SpotifyNeedsReauth(ctx context.Context) (bool, error)
SteamStatus(ctx context.Context) (*model.SteamStatus, error)
Users(ctx context.Context) ([]*models.User, error)
User(ctx context.Context, id int) (*models.User, error)
@@ -1081,6 +1083,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
}
return e.ComplexityRoot.Query.SpotifyListening(childComplexity), true
case "Query.spotifyNeedsReauth":
if e.ComplexityRoot.Query.SpotifyNeedsReauth == nil {
break
}
return e.ComplexityRoot.Query.SpotifyNeedsReauth(childComplexity), true
case "Query.spotifyRecent":
if e.ComplexityRoot.Query.SpotifyRecent == nil {
break
@@ -5244,6 +5252,29 @@ func (ec *executionContext) fieldContext_Query_spotifyRecent(_ context.Context,
return fc, nil
}
func (ec *executionContext) _Query_spotifyNeedsReauth(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_Query_spotifyNeedsReauth(ctx, field)
},
func(ctx context.Context) (any, error) {
return ec.Resolvers.Query().SpotifyNeedsReauth(ctx)
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler {
return ec.marshalNBoolean2bool(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_Query_spotifyNeedsReauth(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("Query", field, true, true, errors.New("field of type Boolean does not have child fields"))
}
func (ec *executionContext) _Query_steamStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
@@ -9419,6 +9450,28 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
}
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
case "spotifyNeedsReauth":
field := field
innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
}
}()
res = ec._Query_spotifyNeedsReauth(ctx, field)
if res == graphql.Null {
atomic.AddUint32(&fs.Invalids, 1)
}
return res
}
rrm := func(ctx context.Context) graphql.Marshaler {
return ec.OperationContext.RootResolverMiddleware(ctx,
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
}
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
case "steamStatus":
field := field
+4
View File
@@ -34,4 +34,8 @@ type SpotifyRecentItem {
extend type Query {
spotifyListening: SpotifyPlaying
spotifyRecent: [SpotifyRecentItem!]
# True only for an admin session while the backend lacks a Spotify client
# (OAuth never completed or the token was revoked), used by the Listening
# widget to offer a reconnect link. Everyone else gets false.
spotifyNeedsReauth: Boolean!
}
+21
View File
@@ -16,6 +16,7 @@ func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPla
// 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 {
r.Store.LogSpotifyUnauthenticated("spotifyListening")
return nil, nil
}
@@ -35,6 +36,7 @@ func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPla
// SpotifyRecent is the resolver for the spotifyRecent field.
func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRecentItem, error) {
if r.Store.SpotifyClient == nil {
r.Store.LogSpotifyUnauthenticated("spotifyRecent")
return []*model.SpotifyRecentItem{}, nil
}
@@ -47,3 +49,22 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
return mapRecentItems(played), nil
}
// 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).
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
if r.Store.SpotifyClient != nil {
return false, nil
}
if !IsAdminFromCtx(ctx) {
return false, nil
}
r.Store.LogSpotifyUnauthenticated("spotifyNeedsReauth")
return true, nil
}
+21
View File
@@ -3,6 +3,7 @@ package handlers
import (
"crypto/rand"
"encoding/hex"
"log"
"sync"
"time"
@@ -66,6 +67,12 @@ type Store struct {
// restarting an OAuth flow that takes seconds.
spotifyStatesMu sync.Mutex
spotifyStates map[string]time.Time
// spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line:
// every page visit hits spotifyRecent, so an unauthenticated backend would
// otherwise write a flood of identical lines. nil means "recently logged".
spotifyNilLoggedMu sync.Mutex
spotifyNilLoggedAt time.Time
}
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
@@ -123,6 +130,20 @@ func (s *Store) ConsumeSpotifyState(state string) bool {
// only when the entry is present and inside its TTL; each "Set..." method
// stores a value and stamps it.
// LogSpotifyUnauthenticated logs that the Spotify OAuth flow has never been
// completed (or a stored token stopped working), with a where hint. It is
// rate-limited to one line per hour — see spotifyNilLoggedAt — because
// spotifyRecent is hit by every home-page visit.
func (s *Store) LogSpotifyUnauthenticated(where string) {
s.spotifyNilLoggedMu.Lock()
defer s.spotifyNilLoggedMu.Unlock()
if time.Since(s.spotifyNilLoggedAt) < time.Hour {
return
}
s.spotifyNilLoggedAt = time.Now()
log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where)
}
// CachedRecentSongs returns the cached Spotify recently-played list if it is
// within its one-minute TTL. An empty list counts as stale, so an empty
// listening history is re-fetched every time (unchanged behaviour).
+10
View File
@@ -22,6 +22,12 @@ const song_template = {
export const useSongsStore = defineStore("songs", () => {
const songs = ref([song_template]);
// signalEnglish (see below) plus an admin-only "needs Spotify re-auth"
// flag, fetched alongside the songs. The widget uses it to offer the
// reconnect link; non-admins also get the field (false) because the query
// is public and the resolver simply gates it.
const needsReauth = ref(false);
const songsCount = computed(() => songs.value.length);
const homeData = useHomeDataStore();
@@ -52,8 +58,10 @@ export const useSongsStore = defineStore("songs", () => {
}
playedAt
}
spotifyNeedsReauth
}
`);
needsReauth.value = !!data.spotifyNeedsReauth;
if (Array.isArray(data.spotifyRecent) && data.spotifyRecent.length > 0) {
songs.value = data.spotifyRecent;
}
@@ -67,6 +75,8 @@ export const useSongsStore = defineStore("songs", () => {
songsCount,
needsReauth,
fetchSongs,
};
});
+36 -1
View File
@@ -8,6 +8,7 @@
import Header from "@/components/text/Header.vue";
import { computed, onMounted } from "vue";
import { useSongsStore } from "@/stores/songs";
import { useAuthStore } from "@/stores/auth";
import { useRotation } from "@/js/useRotation";
const ROTATE_MS = 5000;
@@ -22,6 +23,30 @@ const { idx, next: nextSong } = useRotation(() => songsStore.songs, ROTATE_MS, {
const song = computed(() => songsStore.songs[idx.value]);
// Admin-only reconnect: when spotifyNeedsReauth comes back true the backend
// has no Spotify client (OAuth never completed or the token was revoked), so
// the widget offers the OAuth start endpoint instead of the template song.
// Non-admins get none of this.
const auth = useAuthStore();
const showReconnect = computed(
() => auth.loggedIn && auth.user.admin && songsStore.needsReauth,
);
// GET /api/spotify/auth returns { url } — the Spotify authorisation URL with
// a one-shot state nonce. Navigating to it runs the OAuth dance; the callback
// installs the client server-side. Errors are swallowed: the widget simply
// stays as it was.
async function reconnect() {
try {
const res = await fetch("/api/spotify/auth");
if (!res.ok) return;
const { url } = await res.json();
window.location.href = url;
} catch (err) {
console.error("Cannot start Spotify re-authentication", err);
}
}
onMounted(() => {
songsStore.fetchSongs();
});
@@ -33,7 +58,17 @@ onMounted(() => {
<Header>Listening To</Header>
</div>
<div class="content-scroll">
<Transition name="fade">
<div v-if="showReconnect" class="flex flex-col items-center">
<p class="text-center">Spotify needs reconnecting.</p>
<button
type="button"
class="underline text-mid cursor-pointer bg-transparent border-0"
@click="reconnect"
>
Reconnect Spotify
</button>
</div>
<Transition name="fade" v-else>
<div
@click="nextSong"
:key="song.track.name"