diff --git a/admin/public/config.js b/admin/public/config.js index 3a5255d..bb2cd76 100644 --- a/admin/public/config.js +++ b/admin/public/config.js @@ -4,4 +4,8 @@ // Wystawienie osobnego API tylko dla awaryjnych scenariuszy — wpisz pelny URL. window.__FITOS_CONFIG__ = { apiUrl: '', + // Link „Aplikacja" w menu panelu. Puste = odgadnij port aplikacji z portu + // panelu (dev 9000->9001, vite 5174->5173, staging 13000->13001). + // Inne mapowanie portow (prod) = wpisz pelny adres, np. 'https://app.example.com'. + appUrl: '', }; diff --git a/admin/src/components/Layout.tsx b/admin/src/components/Layout.tsx index febc123..781ec9f 100644 --- a/admin/src/components/Layout.tsx +++ b/admin/src/components/Layout.tsx @@ -1,6 +1,7 @@ import { useState } from 'react'; import { NavLink, Outlet, useNavigate } from 'react-router-dom'; import { + AppWindow, Building2, Dumbbell, LogOut, @@ -15,6 +16,7 @@ import { type LucideIcon, } from 'lucide-react'; import { useAuth } from '../store/auth'; +import { APP_URL } from '../config'; import { Button, ThemeToggle } from './ui'; import { Topbar } from '../topbar'; import { Brandmark } from './Brandmark'; @@ -26,6 +28,8 @@ interface NavItem { label: string; icon: LucideIcon; end: boolean; + /** Link na inny origin (np. aplikacja) — , nie . */ + external?: boolean; } interface NavSection { @@ -53,7 +57,12 @@ const SECTIONS: NavSection[] = [ }, { label: 'System', - items: [{ to: '/logs', label: 'Logi', icon: ScrollText, end: true }], + items: [ + { to: '/logs', label: 'Logi', icon: ScrollText, end: true }, + // Powrót do aplikacji użytkownika — zawsze na końcu, inny origin (aplikacja + // wznowi sesję z własnego ciastka fitos_refresh, panelu nie dotyka). + { to: APP_URL, label: 'Aplikacja', icon: AppWindow, end: false, external: true }, + ], }, ]; @@ -82,41 +91,60 @@ function NavLinks({ className={cn('flex flex-col gap-0.5', collapsed ? 'px-2' : 'px-3')} aria-label="Nawigacja główna" > - {items.map((item) => ( - - cn( - 'relative flex h-[38px] items-center gap-2.5 rounded-[10px] text-[13.5px] font-semibold transition-colors duration-150', - collapsed ? 'justify-center px-0' : 'px-3', - isActive - ? 'bg-accent/11 text-accent-text' - : 'text-dim hover:bg-line/30 hover:text-ink', - ) - } - > - {({ isActive }) => ( - <> - {isActive && ( - - ))} + {items.map((item) => { + const rowClass = (isActive: boolean) => + cn( + 'relative flex h-[38px] items-center gap-2.5 rounded-[10px] text-[13.5px] font-semibold transition-colors duration-150', + collapsed ? 'justify-center px-0' : 'px-3', + isActive ? 'bg-accent/11 text-accent-text' : 'text-dim hover:bg-line/30 hover:text-ink', + ); + const icon = ; + const label = !collapsed && {item.label}; + + if (item.external) { + return ( + + {icon} + {label} + + ); + } + + return ( + rowClass(isActive)} + > + {({ isActive }) => ( + <> + {isActive && ( + + ); + })} ); } @@ -185,13 +213,13 @@ export default function Layout() { const footerRail = (
- + diff --git a/admin/src/components/ui/theme-toggle.tsx b/admin/src/components/ui/theme-toggle.tsx index ff9f7e7..25852a6 100644 --- a/admin/src/components/ui/theme-toggle.tsx +++ b/admin/src/components/ui/theme-toggle.tsx @@ -8,7 +8,7 @@ export function ThemeToggle({ className = '' }: { className?: string }) { onClick={toggle} aria-label="Przełącz motyw" title="Przełącz motyw" - className={`inline-flex shrink-0 items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()} + className={`inline-flex items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()} > {theme === 'dark' ? : } diff --git a/admin/src/config.ts b/admin/src/config.ts index b37eafb..b682d5f 100644 --- a/admin/src/config.ts +++ b/admin/src/config.ts @@ -2,7 +2,7 @@ declare global { interface Window { - __FITOS_CONFIG__?: { apiUrl?: string }; + __FITOS_CONFIG__?: { apiUrl?: string; appUrl?: string }; } } @@ -12,3 +12,18 @@ export const API_URL: string = window.location.origin; export const API_BASE = `${API_URL}/api/v1`; + +/** + * Origin aplikacji użytkownika (link „Aplikacja" w menu panelu). + * config.js: `appUrl` (pełny adres) ma pierwszeństwo. Fallback: ten sam host, + * port aplikacji wg znanego mapowania stosów (dev 9000→9001, vite 5174→5173, + * staging 13000→13001). Własne mapowanie portów (prod) = wpis w config.js. + */ +export const APP_URL: string = + window.__FITOS_CONFIG__?.appUrl || + (() => { + const { protocol, hostname, port } = window.location; + const appPort = + port === '9000' ? '9001' : port === '5174' ? '5173' : port === '13000' ? '13001' : port; + return `${protocol}//${hostname}${appPort ? `:${appPort}` : ''}`; + })(); diff --git a/admin/src/store/auth.ts b/admin/src/store/auth.ts index 47f5677..51b5f46 100644 --- a/admin/src/store/auth.ts +++ b/admin/src/store/auth.ts @@ -40,6 +40,8 @@ export const useAuth = create((set) => ({ init: async () => { try { + // Ciastka nie znają portów — zalogowany w aplikacji admin (której API + // wystawiło przy loginie też fitos_admin_refresh) wchodzi tu bez hasła. const refreshRes = await fetch(`${API_BASE}/auth/refresh`, { method: 'POST', credentials: 'include', diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts index bc18912..a2c0a11 100644 --- a/admin/test/e2e/admin.spec.ts +++ b/admin/test/e2e/admin.spec.ts @@ -10,6 +10,15 @@ async function loginAsAdmin(page: Page) { await expect(page).toHaveURL(/\/gyms$/); } +test('sidebar zawiera link „Aplikacja” prowadzący do aplikacji użytkownika', async ({ page }) => { + mockApi(page, { gyms: { gyms: [TEST_GYM] } }); + await loginAsAdmin(page); + const link = page.getByRole('link', { name: 'Aplikacja' }); + await expect(link).toBeVisible(); + // dev (vite 5174) → port aplikacji 5173 wg mapowania z src/config.ts + await expect(link).toHaveAttribute('href', /:5173\/?$/); +}); + test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page }) => { mockApi(page, { gyms: { gyms: [TEST_GYM] } }); await loginAsAdmin(page); diff --git a/api/src/routes/auth.ts b/api/src/routes/auth.ts index 9c6f4ec..009f036 100644 --- a/api/src/routes/auth.ts +++ b/api/src/routes/auth.ts @@ -104,7 +104,7 @@ export function createAuthRoutes({ prisma }: AppDeps) { * summary: Login with email + password * tags: [Auth] * responses: - * 200: { description: OK, returns user + access token } + * 200: { description: 'OK, returns user + access token; dla konta z isAdmin=true (login z aplikacji) wystawiamy tez ciastko fitos_admin_refresh — SSO panelu' } * 401: { description: Invalid credentials } */ router.post( @@ -115,6 +115,12 @@ export function createAuthRoutes({ prisma }: AppDeps) { const data = req.body as z.infer; const result = await login(prisma, data); setRefreshCookie(res, result.refreshToken, isAdminClient(req)); + // Administrator logujacy sie przez aplikacje dostaje dodatkowo ciastko + // panelu — link „Panel admina" otwiera admina juz zalogowanego (te same + // ciastka po tej samej domenie; rotacja nie uniewaznia starych wartosci). + if (!isAdminClient(req) && result.user.isAdmin) { + setRefreshCookie(res, result.refreshToken, true); + } res.json({ user: result.user, accessToken: result.accessToken }); }), ); diff --git a/api/test/integration/auth.test.ts b/api/test/integration/auth.test.ts index 58192b6..c370ea9 100644 --- a/api/test/integration/auth.test.ts +++ b/api/test/integration/auth.test.ts @@ -152,9 +152,7 @@ describe('auth routes', () => { await agent.post('/api/v1/auth/login').send({ email: user.email, password }); const res = await agent.post('/api/v1/auth/logout'); expect(res.status).toBe(204); - const setCookie = (res.headers['set-cookie'] ?? []).find((c) => - c.startsWith('fitos_refresh='), - ); + const setCookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('fitos_refresh=')); expect(setCookie).toBeDefined(); expect(setCookie).toMatch(/Expires=Thu, 01 Jan 1970|Max-Age=0/); }); @@ -204,6 +202,36 @@ describe('auth routes', () => { expect(asApp.status).toBe(401); }); + it('login z aplikacji: admin dostaje tez ciastko panelu (SSO), cwiczacy nie', async () => { + const app = buildApp(); + const { user, password } = await createUser({ isAdmin: true }); + const login = await app.post('/api/v1/auth/login').send({ email: user.email, password }); + expect(login.status).toBe(200); + const cookies = (login.headers['set-cookie'] ?? []).join('\n'); + expect(cookies).toContain('fitos_refresh='); + expect(cookies).toContain('fitos_admin_refresh='); + + // ciastko panelu odswieza sie jak normalna sesja admina + const adminToken = (login.headers['set-cookie'] ?? []) + .find((c) => c.startsWith('fitos_admin_refresh='))! + .split('=')[1] + .split(';')[0]; + const asAdmin = await app + .post('/api/v1/auth/refresh') + .set('X-Client', 'admin') + .set('Cookie', [`fitos_admin_refresh=${adminToken}`]); + expect(asAdmin.status).toBe(200); + + // zwykly user — tylko ciastko aplikacji + const { user: member, password: memberPassword } = await createUser(); + const memberLogin = await app + .post('/api/v1/auth/login') + .send({ email: member.email, password: memberPassword }); + expect((memberLogin.headers['set-cookie'] ?? []).join('\n')).not.toContain( + 'fitos_admin_refresh=', + ); + }); + it('logout (admin client): clears both cookie names and revokes tokens', async () => { const app = buildApp(); const { user, password } = await createUser(); diff --git a/app/public/config.js b/app/public/config.js index 3a5255d..1c675c6 100644 --- a/app/public/config.js +++ b/app/public/config.js @@ -4,4 +4,8 @@ // Wystawienie osobnego API tylko dla awaryjnych scenariuszy — wpisz pelny URL. window.__FITOS_CONFIG__ = { apiUrl: '', + // Link „Panel admina" w aplikacji. Puste = odgadnij port admina z portu + // aplikacji (dev 9001->9000, vite 5173->5174, staging 13001->13000). + // Inne mapowanie portow (prod) = wpisz pelny adres, np. 'https://admin.example.com'. + adminUrl: '', }; diff --git a/app/src/components/Layout.tsx b/app/src/components/Layout.tsx index 35e8229..81dfa30 100644 --- a/app/src/components/Layout.tsx +++ b/app/src/components/Layout.tsx @@ -11,12 +11,14 @@ import { Menu, MessageSquare, Play, + ShieldCheck, User, Users, X, type LucideIcon, } from 'lucide-react'; import { useAuth } from '../store/auth'; +import { ADMIN_URL } from '../config'; import { useActiveSession, useConversations, @@ -38,6 +40,8 @@ interface NavItem { icon: LucideIcon; end: boolean; badge?: number; + /** Link na inny origin (np. panel admina) — , nie . */ + external?: boolean; } const NAV: NavItem[] = [ @@ -67,6 +71,14 @@ const ANNOUNCEMENTS_NAV: NavItem = { icon: Megaphone, end: false, }; +// Panel admina — zawsze na końcu listy, tylko dla kont z isAdmin=true. +const ADMIN_NAV: NavItem = { + to: ADMIN_URL, + label: 'Panel admina', + icon: ShieldCheck, + end: false, + external: true, +}; const SIDEBAR_KEY = 'fitos-sidebar-collapsed'; @@ -93,53 +105,73 @@ function NavLinks({ className={cn('flex flex-col gap-0.5', collapsed ? 'px-2' : 'px-3')} aria-label="Nawigacja główna" > - {items.map((item) => ( - - cn( - 'relative flex h-[38px] items-center gap-2.5 rounded-[10px] text-[13.5px] font-semibold transition-colors duration-150', - collapsed ? 'justify-center px-0' : 'px-3', - isActive - ? 'bg-accent/11 text-accent-text' - : 'text-dim hover:bg-line/30 hover:text-ink', - ) - } - > - {({ isActive }) => ( - <> - {isActive && ( - - ))} + {items.map((item) => { + const rowClass = (isActive: boolean) => + cn( + 'relative flex h-[38px] items-center gap-2.5 rounded-[10px] text-[13.5px] font-semibold transition-colors duration-150', + collapsed ? 'justify-center px-0' : 'px-3', + isActive ? 'bg-accent/11 text-accent-text' : 'text-dim hover:bg-line/30 hover:text-ink', + ); + const icon = ; + const label = !collapsed && {item.label}; + const navBar = ( + + {icon} + {label} + + ); + } + + return ( + rowClass(isActive)} + > + {({ isActive }) => ( + <> + {isActive && navBar} + {icon} + {label} + {typeof item.badge === 'number' && + item.badge > 0 && + (collapsed ? ( + + ); + })} ); } @@ -198,6 +230,8 @@ export default function Layout() { if (isTrainer) navItems = [...navItems.slice(0, -1), TRAINEES_NAV, navItems[navItems.length - 1]]; if (pendingInvitations > 0) navItems = [...navItems.slice(0, -1), INVITATIONS_NAV, navItems[navItems.length - 1]]; + // „Panel admina” — zawsze na samym końcu, tylko dla administratorów. + if (user?.isAdmin) navItems = [...navItems, ADMIN_NAV]; const fullName = [user?.firstName, user?.lastName].filter(Boolean).join(' ') || user?.email || '?'; @@ -234,13 +268,13 @@ export default function Layout() { const footerRail = (
- + diff --git a/app/src/components/ui/theme-toggle.tsx b/app/src/components/ui/theme-toggle.tsx index ff9f7e7..25852a6 100644 --- a/app/src/components/ui/theme-toggle.tsx +++ b/app/src/components/ui/theme-toggle.tsx @@ -8,7 +8,7 @@ export function ThemeToggle({ className = '' }: { className?: string }) { onClick={toggle} aria-label="Przełącz motyw" title="Przełącz motyw" - className={`inline-flex shrink-0 items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()} + className={`inline-flex items-center justify-center p-2.5 rounded-[10px] bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()} > {theme === 'dark' ? : } diff --git a/app/src/config.ts b/app/src/config.ts index 929bffe..08822b7 100644 --- a/app/src/config.ts +++ b/app/src/config.ts @@ -2,7 +2,7 @@ declare global { interface Window { - __FITOS_CONFIG__?: { apiUrl?: string }; + __FITOS_CONFIG__?: { apiUrl?: string; adminUrl?: string }; } } @@ -13,3 +13,18 @@ export const API_URL: string = window.location.origin; export const API_BASE = `${API_URL}/api/v1`; + +/** + * Origin panelu admina (link „Panel admina" dla administratorów). + * config.js: `adminUrl` (pełny adres) ma pierwszeństwo. Fallback: ten sam host, + * port admina wg znanego mapowania stosów (dev 9001→9000, vite 5173→5174, + * staging 13001→13000). Własne mapowanie portów (prod) = wpis w config.js. + */ +export const ADMIN_URL: string = + window.__FITOS_CONFIG__?.adminUrl || + (() => { + const { protocol, hostname, port } = window.location; + const adminPort = + port === '9001' ? '9000' : port === '5173' ? '5174' : port === '13001' ? '13000' : port; + return `${protocol}//${hostname}${adminPort ? `:${adminPort}` : ''}`; + })(); diff --git a/app/test/AdminPanelLink.test.tsx b/app/test/AdminPanelLink.test.tsx new file mode 100644 index 0000000..a165cfb --- /dev/null +++ b/app/test/AdminPanelLink.test.tsx @@ -0,0 +1,132 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import App from '../src/App'; +import { ADMIN_URL } from '../src/config'; +import { useAuth } from '../src/store/auth'; +import { setAccessToken } from '../src/api/client'; +import type { User } from '../src/api/types'; + +function user(overrides: Partial = {}): User { + return { + id: 'u1', + email: 'jan@test.local', + firstName: 'Jan', + lastName: 'Kowalski', + age: 30, + heightCm: 180, + phone: null, + isAdmin: false, + availability: null, + priorities: 'chest', + exclusions: 'knee', + developMuscles: [], + canDoMuscles: [], + difficultMuscles: [], + avoidMuscles: [], + createdAt: '2026-08-22T10:00:00.000Z', + ...overrides, + }; +} + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function mockApi(current: User) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes('/auth/refresh')) + return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } }); + if (url.includes('/auth/login')) + return jsonResponse(200, { user: current, accessToken: 'tok-1' }); + if (url.includes('/me/active-session')) return jsonResponse(200, { session: null }); + if (url.includes('/me/feed/unread-count')) return jsonResponse(200, { count: 0 }); + if (url.includes('/me')) return jsonResponse(200, { user: current, memberships: [] }); + if (url.includes('/messages/conversations')) return jsonResponse(200, { conversations: [] }); + if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] }); + if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] }); + if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] }); + if (url.includes('/dashboard')) + return jsonResponse(200, { + killstreak: 0, + activePlan: null, + nextTraining: null, + progress: null, + }); + return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); + }), + ); +} + +async function login(current: User) { + mockApi(current); + const tester = userEvent.setup(); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, + }); + render( + + + + + , + ); + + expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument(); + const email = document.querySelector('input[type="email"]') as HTMLInputElement; + const password = document.querySelector('input[type="password"]') as HTMLInputElement; + await tester.type(email, 'jan@test.local'); + await tester.type(password, 'Password123!'); + await tester.click(screen.getByRole('button', { name: 'Zaloguj' })); + expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument(); +} + +beforeEach(() => { + setAccessToken(null); + localStorage.clear(); + useAuth.setState({ user: null, ready: false }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Panel admina w aplikacji', () => { + it('administrator widzi link „Panel admina” w stopce sidebaru', async () => { + await login(user({ isAdmin: true })); + + const link = screen.getByRole('link', { name: 'Panel admina' }); + expect(link).toBeInTheDocument(); + expect(link.getAttribute('href')).toBe(ADMIN_URL); + }); + + it('ikony w railu (przyciemniony sidebar) są tej samej wielkości', async () => { + await login(user({ isAdmin: true })); + + // rail = zwinięty sidebar; jedyna instancja ThemeToggle to ta w stopce raila + const toggle = screen.getByRole('button', { name: 'Przełącz motyw' }); + const logout = screen.getByRole('button', { name: 'Wyloguj' }); + const ts = toggle.getBoundingClientRect(); + const ls = logout.getBoundingClientRect(); + expect(Math.round(ts.width)).toBe(Math.round(ls.width)); + expect(Math.round(ts.height)).toBe(Math.round(ls.height)); + const tsvg = toggle.querySelector('svg')!.getBoundingClientRect(); + const lsvg = logout.querySelector('svg')!.getBoundingClientRect(); + expect(Math.round(tsvg.width)).toBe(Math.round(lsvg.width)); + expect(Math.round(tsvg.height)).toBe(Math.round(lsvg.height)); + }); + + it('zwykły użytkownik nie widzi linku „Panel admina”', async () => { + await login(user({ isAdmin: false })); + + expect(screen.queryByRole('link', { name: 'Panel admina' })).not.toBeInTheDocument(); + }); +});