mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
feat(journey): read and unlock protected share links in the client hooks
The data side of the protected journey link (#2553), without markup yet: - journeyApi.unlockPublicJourney posts a reader's password; the answer sets the link's unlock cookie. - useJourneyPublic tells a locked link (access 'locked') and an expired one ('expired') apart from a broken one, and unlock() reports 'ok', 'wrong', 'rate_limited', 'expired' or 'failed', reloading the journey on success. - useJourneyShareLink carries has_password, expires_at, view_count and last_viewed_at, and setProtection() sets or clears the password and the expiry, shown only once the server took it.
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
* No React, no side effects — safe to import from both the data hook and the
|
||||
* presentational page.
|
||||
*/
|
||||
import { JOURNEY_PUBLIC_ERROR_CODES } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* An entry as the share link sends it (`journeyPublicEntrySchema` in
|
||||
@@ -53,6 +54,41 @@ export interface PublicGalleryPhoto extends PublicPhoto {
|
||||
lng?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the link lets this browser in (#2553): open, waiting for its
|
||||
* password, or past the date its owner set.
|
||||
*/
|
||||
export type PublicLinkAccess = 'open' | 'locked' | 'expired';
|
||||
|
||||
/** What typing a password came to. */
|
||||
export type PublicUnlockOutcome = 'ok' | 'wrong' | 'rate_limited' | 'expired' | 'failed';
|
||||
|
||||
interface ApiErrorLike {
|
||||
response?: { status?: number; data?: { code?: unknown } };
|
||||
}
|
||||
|
||||
function failureOf(err: unknown): { status?: number; code?: unknown } {
|
||||
const response = (err as ApiErrorLike | null)?.response;
|
||||
return { status: response?.status, code: response?.data?.code };
|
||||
}
|
||||
|
||||
/** The access a failed read of the link means, or null for any other failure. */
|
||||
export function publicLinkAccessOf(err: unknown): Exclude<PublicLinkAccess, 'open'> | null {
|
||||
const { status, code } = failureOf(err);
|
||||
if (status === 401 && code === JOURNEY_PUBLIC_ERROR_CODES.locked) return 'locked';
|
||||
if (status === 410 && code === JOURNEY_PUBLIC_ERROR_CODES.expired) return 'expired';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What a failed unlock means to the reader. */
|
||||
export function unlockOutcomeOf(err: unknown): Exclude<PublicUnlockOutcome, 'ok'> {
|
||||
const { status, code } = failureOf(err);
|
||||
if (status === 401 && code === JOURNEY_PUBLIC_ERROR_CODES.denied) return 'wrong';
|
||||
if (status === 429) return 'rate_limited';
|
||||
if (status === 410) return 'expired';
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>();
|
||||
for (const e of entries) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// FE-JRN-PUBHOOK-001 to FE-JRN-PUBHOOK-003
|
||||
// FE-JRN-PUBHOOK-001 to FE-JRN-PUBHOOK-007
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import type { PublicEntry } from './journeyPublicModel';
|
||||
import { useJourneyPublic } from './useJourneyPublic';
|
||||
|
||||
@@ -108,4 +108,88 @@ describe('useJourneyPublic', () => {
|
||||
// A journey that ended long ago, read oldest-first, starts at the beginning.
|
||||
await waitFor(() => expect(result.current.openAtEntryId).toBeNull());
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-004: a link with a password reads as locked, not as broken (#2553)', async () => {
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.access).toBe('locked');
|
||||
expect(result.current.error).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-005: a link past its date reads as expired', async () => {
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' }, { status: 410 })
|
||||
)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.access).toBe('expired');
|
||||
expect(result.current.error).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-006: the right password loads the journey', async () => {
|
||||
let unlocked = false;
|
||||
const sent: unknown[] = [];
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
unlocked
|
||||
? HttpResponse.json({
|
||||
journey: { title: 'Japan' },
|
||||
entries: [buildEntry({ id: 1 })],
|
||||
gallery: [],
|
||||
permissions: { share_timeline: true, share_gallery: true, share_map: false },
|
||||
stats: {},
|
||||
})
|
||||
: HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
),
|
||||
http.post('/api/public/journey/tok-1/unlock', async ({ request }) => {
|
||||
sent.push(await request.json());
|
||||
unlocked = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
})
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
await waitFor(() => expect(result.current.access).toBe('locked'));
|
||||
|
||||
let outcome: string | undefined;
|
||||
await act(async () => {
|
||||
outcome = await result.current.unlock('secret');
|
||||
});
|
||||
|
||||
expect(outcome).toBe('ok');
|
||||
expect(sent).toEqual([{ password: 'secret' }]);
|
||||
await waitFor(() => expect(result.current.access).toBe('open'));
|
||||
expect(result.current.timelineEntries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-007: a wrong password, too many tries and a dead link each say so', async () => {
|
||||
let answer = HttpResponse.json({ error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' }, { status: 401 });
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
),
|
||||
http.post('/api/public/journey/tok-1/unlock', () => answer)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
await waitFor(() => expect(result.current.access).toBe('locked'));
|
||||
|
||||
expect(await result.current.unlock('nope')).toBe('wrong');
|
||||
answer = HttpResponse.json({ error: 'Too many attempts. Please try again later.' }, { status: 429 });
|
||||
expect(await result.current.unlock('nope')).toBe('rate_limited');
|
||||
answer = HttpResponse.json({ error: 'boom' }, { status: 500 });
|
||||
expect(await result.current.unlock('nope')).toBe('failed');
|
||||
answer = HttpResponse.json({ error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' }, { status: 410 });
|
||||
await act(async () => {
|
||||
expect(await result.current.unlock('nope')).toBe('expired');
|
||||
});
|
||||
expect(result.current.access).toBe('expired');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,10 @@ import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { DAY_COLORS } from '../../components/Journey/dayColors'
|
||||
import { journeyMapStops } from '../../components/Journey/journeyMapStops'
|
||||
import { posterlessVideo } from '../journeyDetail/JourneyDetailPage.helpers'
|
||||
import { groupByDate, type PublicEntry, type PublicGalleryPhoto } from './journeyPublicModel'
|
||||
import {
|
||||
groupByDate, publicLinkAccessOf, unlockOutcomeOf,
|
||||
type PublicEntry, type PublicGalleryPhoto, type PublicLinkAccess, type PublicUnlockOutcome,
|
||||
} from './journeyPublicModel'
|
||||
import { useJourneyMapLayers } from '../../components/Journey/useJourneyMapLayers'
|
||||
import { journeyOpenAtEntryId } from '../../components/Journey/journeyOpenAt'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
@@ -26,6 +29,11 @@ export function useJourneyPublic() {
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
// #2553: a link with a password answers 401 until this browser unlocked it,
|
||||
// one past its date 410; the page shows a password card or a "gone" note.
|
||||
const [access, setAccess] = useState<PublicLinkAccess>('open')
|
||||
// Bumped by a successful unlock, so the read runs again with the new cookie.
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; thumbSrc?: string; caption?: string | null; mediaType?: string | null }[]; index: number } | null>(null)
|
||||
@@ -46,10 +54,44 @@ export function useJourneyPublic() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
let cancelled = false
|
||||
journeyApi.getPublicJourney(token)
|
||||
.then(d => setData(d))
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false))
|
||||
.then(d => {
|
||||
if (cancelled) return
|
||||
setData(d)
|
||||
setAccess('open')
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return
|
||||
const refused = publicLinkAccessOf(err)
|
||||
if (refused) setAccess(refused)
|
||||
else setError(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [token, reloadKey])
|
||||
|
||||
/**
|
||||
* Send the password a reader typed. On 'ok' the server has set the link's
|
||||
* cookie and the journey loads; every other outcome is for the password card
|
||||
* to word ('wrong', 'rate_limited', 'expired', 'failed').
|
||||
*/
|
||||
const unlock = useCallback(async (password: string): Promise<PublicUnlockOutcome> => {
|
||||
if (!token) return 'failed'
|
||||
try {
|
||||
await journeyApi.unlockPublicJourney(token, password)
|
||||
} catch (err) {
|
||||
const outcome = unlockOutcomeOf(err)
|
||||
if (outcome === 'expired') setAccess('expired')
|
||||
return outcome
|
||||
}
|
||||
setLoading(true)
|
||||
setReloadKey(n => n + 1)
|
||||
return 'ok'
|
||||
}, [token])
|
||||
|
||||
const entries = (data?.entries || []) as PublicEntry[]
|
||||
@@ -170,7 +212,7 @@ export function useJourneyPublic() {
|
||||
}, [desktopTwoColumn, view])
|
||||
|
||||
return {
|
||||
token, data, loading, error, isMobile, locale,
|
||||
token, data, loading, error, access, unlock, isMobile, locale,
|
||||
view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker,
|
||||
mapRef, feedRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick,
|
||||
perms, journey, stats,
|
||||
|
||||
Reference in New Issue
Block a user