feat(app): personal workspace in the account store, reset on account change
The store reads the personal workspace with the account (ready, loading, inactive, unconfirmed, missing, error; never created in the browser). A change of account drops profile, roles, avatar and workspace at once, and a late answer for the previous account is ignored. generateUuid gives v4 ids on the plain-HTTP LAN origin, where crypto.randomUUID is missing.
This commit is contained in:
1 parent
a0e069959b
commit
ff028ec071
4 files changed
+289
-19
No files matched your search
@@ -11,3 +11,18 @@ export function generateId(): string {
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* A random version 4 uuid, also on an origin that is not a secure context
|
||||
* (the DEV origin is plain HTTP on the LAN, where crypto.randomUUID is
|
||||
* missing but crypto.getRandomValues is not). Used for request ids the
|
||||
* database stores as uuid.
|
||||
*/
|
||||
export function generateUuid(): string {
|
||||
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16))
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
type AvatarState,
|
||||
downloadAvatar,
|
||||
fetchOwnAvatarState,
|
||||
fetchPersonalWorkspaceId,
|
||||
classifyRecordError,
|
||||
type FaunosteoClient,
|
||||
type RecordFailureKind,
|
||||
type OwnProfilePatch,
|
||||
type PlatformRole,
|
||||
type Profile,
|
||||
@@ -26,6 +29,21 @@ import { getSupabaseClient } from '@/lib/supabase'
|
||||
*/
|
||||
export type AuthStatus = 'loading' | 'unavailable' | 'signed_out' | 'signed_in'
|
||||
|
||||
/**
|
||||
* The account's personal workspace (contract §4): created by the server at
|
||||
* sign-up, read once with the account, never created here. RLS hides it from
|
||||
* a deactivated profile and an unconfirmed email, told apart before reading;
|
||||
* `missing` is an active, confirmed account whose workspace does not answer.
|
||||
*/
|
||||
export type WorkspaceState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; id: string }
|
||||
| { status: 'inactive' }
|
||||
| { status: 'unconfirmed' }
|
||||
| { status: 'missing' }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
export interface AuthState {
|
||||
status: AuthStatus
|
||||
session: Session | null
|
||||
@@ -41,9 +59,12 @@ export interface AuthState {
|
||||
avatar: AvatarState | null
|
||||
/** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */
|
||||
avatarUrl: string | null
|
||||
workspace: WorkspaceState
|
||||
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
|
||||
start: () => () => void
|
||||
refreshAccount: () => Promise<void>
|
||||
/** Reads the personal workspace again (after a failure). */
|
||||
refreshWorkspace: () => Promise<void>
|
||||
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
|
||||
/** Re-reads the own rows; downloads the clean photo when it changed. */
|
||||
refreshAvatar: () => Promise<AvatarState>
|
||||
@@ -83,13 +104,53 @@ async function syncAvatar(client: FaunosteoClient, user: User, set: Set, get: Ge
|
||||
return avatar
|
||||
}
|
||||
|
||||
/** A setter that drops the patch once another account has signed in: no late response leaks across accounts. */
|
||||
function setForUser(user: User, set: Set, get: Get): Set {
|
||||
return (patch) => {
|
||||
if (get().user?.id === user.id) set(patch)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadWorkspace(
|
||||
client: FaunosteoClient,
|
||||
user: User,
|
||||
profile: Profile | null,
|
||||
set: Set,
|
||||
) {
|
||||
if (!user.email_confirmed_at) return set({ workspace: { status: 'unconfirmed' } })
|
||||
if (profile && !profile.active) return set({ workspace: { status: 'inactive' } })
|
||||
set({ workspace: { status: 'loading' } })
|
||||
try {
|
||||
const id = await fetchPersonalWorkspaceId(client, user.id)
|
||||
set({ workspace: id ? { status: 'ready', id } : { status: 'missing' } })
|
||||
} catch (error) {
|
||||
set({ workspace: { status: 'error', failure: classifyRecordError(error) } })
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: Get) {
|
||||
const setOwn = setForUser(user, set, get)
|
||||
const [profile, roles] = await Promise.all([
|
||||
fetchOwnProfile(client, user.id),
|
||||
fetchOwnPlatformRoles(client, user.id),
|
||||
])
|
||||
set({ profile, roles })
|
||||
await syncAvatar(client, user, set, get).catch(() => set({ avatar: null }))
|
||||
setOwn({ profile, roles })
|
||||
await Promise.all([
|
||||
loadWorkspace(client, user, profile, setOwn),
|
||||
syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })),
|
||||
])
|
||||
}
|
||||
|
||||
/** Everything the store holds about one account: dropped together on sign-out and on a change of account. */
|
||||
function accountReset(get: Get): Partial<AuthState> {
|
||||
revokeUrl(get().avatarUrl)
|
||||
return {
|
||||
profile: null,
|
||||
roles: [],
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
workspace: { status: 'idle' },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,30 +166,33 @@ function applyAuthEvent(
|
||||
) {
|
||||
const previousUserId = get().user?.id
|
||||
if (event === 'SIGNED_OUT' || session === null) {
|
||||
revokeUrl(get().avatarUrl)
|
||||
set({
|
||||
...accountReset(get),
|
||||
status: 'signed_out',
|
||||
session: null,
|
||||
user: null,
|
||||
profile: null,
|
||||
roles: [],
|
||||
recovery: false,
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
const changedAccount = session.user.id !== previousUserId
|
||||
const patch: Partial<AuthState> = {
|
||||
// Another account: nothing of the previous one stays on screen while the new one loads.
|
||||
...(changedAccount ? { ...accountReset(get), workspace: { status: 'loading' } } : {}),
|
||||
status: 'signed_in',
|
||||
session,
|
||||
user: session.user,
|
||||
}
|
||||
if (event === 'PASSWORD_RECOVERY') patch.recovery = true
|
||||
set(patch)
|
||||
if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
|
||||
if (changedAccount || event === 'USER_UPDATED') {
|
||||
setTimeout(() => {
|
||||
void loadAccount(client, session.user, set, get).catch(() => {
|
||||
set({ profile: null, roles: [] })
|
||||
void loadAccount(client, session.user, set, get).catch((error: unknown) => {
|
||||
setForUser(session.user, set, get)({
|
||||
profile: null,
|
||||
roles: [],
|
||||
workspace: { status: 'error', failure: classifyRecordError(error) },
|
||||
})
|
||||
})
|
||||
}, 0)
|
||||
}
|
||||
@@ -155,6 +219,7 @@ export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
urlFailure: null,
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
workspace: { status: 'idle' },
|
||||
|
||||
start: () => {
|
||||
const client = getSupabaseClient()
|
||||
@@ -175,6 +240,11 @@ export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
await loadAccount(requireClient(), requireUser(get().user), set, get)
|
||||
},
|
||||
|
||||
refreshWorkspace: async () => {
|
||||
const user = requireUser(get().user)
|
||||
await loadWorkspace(requireClient(), user, get().profile, setForUser(user, set, get))
|
||||
},
|
||||
|
||||
refreshAvatar: async () => {
|
||||
return syncAvatar(requireClient(), requireUser(get().user), set, get)
|
||||
},
|
||||
@@ -197,16 +267,12 @@ export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
|
||||
signOut: async () => {
|
||||
const clear = () => {
|
||||
revokeUrl(get().avatarUrl)
|
||||
set({
|
||||
...accountReset(get),
|
||||
status: 'signed_out',
|
||||
session: null,
|
||||
user: null,
|
||||
profile: null,
|
||||
roles: [],
|
||||
recovery: false,
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
})
|
||||
}
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user