fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, PATCH } from '../route'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
function unauthed() {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: null,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
}
|
||||
|
||||
function authedForGet(
|
||||
row: { hide_assistant_fab?: boolean; auto_logout?: boolean } | null,
|
||||
) {
|
||||
const maybeSingle = vi.fn().mockResolvedValue({ data: row, error: null })
|
||||
const supabase = {
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
eq: vi.fn(() => ({ maybeSingle })),
|
||||
})),
|
||||
})),
|
||||
}
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
return { supabase }
|
||||
}
|
||||
|
||||
function authedForPatch(upsertError: { message: string } | null = null) {
|
||||
const upsert = vi.fn().mockResolvedValue({ error: upsertError })
|
||||
const supabase = { from: vi.fn(() => ({ upsert })) }
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
return { upsert }
|
||||
}
|
||||
|
||||
function patchRequest(body: unknown) {
|
||||
return new Request('http://localhost/api/user/preferences', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('GET /api/user/preferences', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
unauthed()
|
||||
const res = await GET()
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns the stored preferences', async () => {
|
||||
authedForGet({ hide_assistant_fab: true, auto_logout: true })
|
||||
const res = await GET()
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ hide_assistant_fab: true, auto_logout: true })
|
||||
})
|
||||
|
||||
it('defaults to false when no preferences row exists', async () => {
|
||||
authedForGet(null)
|
||||
const res = await GET()
|
||||
const { body } = await parseJsonResponse<{ data: unknown }>(res)
|
||||
expect(body.data).toEqual({ hide_assistant_fab: false, auto_logout: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/user/preferences', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
unauthed()
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an invalid body with 400', async () => {
|
||||
authedForPatch()
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: 'yes' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects unknown keys with 400', async () => {
|
||||
authedForPatch()
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: true, locale: 'en' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('upserts the preference for the authenticated user', async () => {
|
||||
const { upsert } = authedForPatch()
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ hide_assistant_fab: true })
|
||||
expect(upsert).toHaveBeenCalledWith(
|
||||
{ user_id: 'user-1', hide_assistant_fab: true },
|
||||
{ onConflict: 'user_id' }
|
||||
)
|
||||
})
|
||||
|
||||
it('writes a multi-field request as one atomic upsert', async () => {
|
||||
const { upsert } = authedForPatch()
|
||||
const res = await PATCH(
|
||||
patchRequest({ hide_assistant_fab: true, auto_logout: false })
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(upsert).toHaveBeenCalledTimes(1)
|
||||
expect(upsert).toHaveBeenCalledWith(
|
||||
{ user_id: 'user-1', hide_assistant_fab: true, auto_logout: false },
|
||||
{ onConflict: 'user_id' }
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
authedForPatch()
|
||||
const res = await PATCH(patchRequest({}))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('upserts auto_logout and resets the session timeout cookie', async () => {
|
||||
const { upsert } = authedForPatch()
|
||||
const res = await PATCH(patchRequest({ auto_logout: true }))
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ auto_logout: true })
|
||||
expect(upsert).toHaveBeenCalledWith(
|
||||
{ user_id: 'user-1', auto_logout: true },
|
||||
{ onConflict: 'user_id' }
|
||||
)
|
||||
// The signed timeout cookie caches the opt-in; a change must clear it so
|
||||
// the middleware re-mints with the new preference on the next request.
|
||||
const setCookie = res.headers.get('set-cookie') ?? ''
|
||||
expect(setCookie).toContain('gnubok-session-timeout=;')
|
||||
})
|
||||
|
||||
it('does not touch the session timeout cookie for unrelated preferences', async () => {
|
||||
authedForPatch()
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('set-cookie')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 500 when the upsert fails', async () => {
|
||||
authedForPatch({ message: 'boom' })
|
||||
const res = await PATCH(patchRequest({ hide_assistant_fab: false }))
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { sessionTimeoutClearCookieOptions } from '@/lib/auth/session-timeout'
|
||||
import { SESSION_TIMEOUT_COOKIE } from '@/lib/auth/session-timeout-shared'
|
||||
|
||||
// User-level UI preferences (not company-scoped), stored on user_preferences.
|
||||
// Mirrors the /api/user/locale pattern: requireAuth directly because these
|
||||
// must work even when the user has no active company.
|
||||
|
||||
const BodySchema = z
|
||||
.object({
|
||||
hide_assistant_fab: z.boolean().optional(),
|
||||
auto_logout: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine((value) => Object.keys(value).length > 0, {
|
||||
message: 'At least one preference is required',
|
||||
})
|
||||
|
||||
export async function GET() {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
const { data } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('hide_assistant_fab, auto_logout')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
hide_assistant_fab: data?.hide_assistant_fab ?? false,
|
||||
auto_logout: data?.auto_logout ?? false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
|
||||
}
|
||||
|
||||
const parsed = BodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Invalid preferences' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { hide_assistant_fab, auto_logout } = parsed.data
|
||||
|
||||
// One literal upsert per accepted field combination: the phantom-column
|
||||
// schema guard cannot resolve spread payloads, and a single write keeps a
|
||||
// multi-field request atomic.
|
||||
let upsertError: unknown = null
|
||||
if (hide_assistant_fab !== undefined && auto_logout !== undefined) {
|
||||
const { error } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert(
|
||||
{ user_id: user.id, hide_assistant_fab, auto_logout },
|
||||
{ onConflict: 'user_id' },
|
||||
)
|
||||
upsertError = error
|
||||
} else if (hide_assistant_fab !== undefined) {
|
||||
const { error } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert({ user_id: user.id, hide_assistant_fab }, { onConflict: 'user_id' })
|
||||
upsertError = error
|
||||
} else if (auto_logout !== undefined) {
|
||||
const { error } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert({ user_id: user.id, auto_logout }, { onConflict: 'user_id' })
|
||||
upsertError = error
|
||||
}
|
||||
|
||||
if (upsertError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: getErrorMessage(upsertError, {
|
||||
context: 'settings',
|
||||
statusCode: 500,
|
||||
}),
|
||||
},
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
const response = NextResponse.json({ data: parsed.data })
|
||||
|
||||
if (parsed.data.auto_logout !== undefined) {
|
||||
// The middleware caches the opt-in inside the signed timeout cookie.
|
||||
// Clearing it forces a re-mint on the next request, so the change takes
|
||||
// effect immediately instead of at the next login.
|
||||
response.cookies.set(
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
'',
|
||||
sessionTimeoutClearCookieOptions(),
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
Reference in New Issue
Block a user