Files
Musify/frontend/src/routes/login/+server.ts
T
Admin e7e854959f feat(frontend): server-side Zitadel OIDC auth (part 2)
Add Authorization Code + PKCE login/logout against Zitadel, handled entirely
server-side with an httpOnly signed session cookie:
- $lib/server/auth: openid-client discovery (config cached), jose-signed
  session encode/decode, cookie/name constants
- routes: /login (builds the authorize URL with PKCE/state/nonce, ?mode=register
  -> prompt=create), /auth/callback (code exchange + session cookie),
  /logout (clears session + Zitadel end_session)
- hooks.server populates locals.user/accessToken from the session
- +layout.server exposes the user; Navbar shows the signed-in user + Salir,
  or Iniciar sesión / Registrarse
- switch to adapter-node; env-driven config (.env gitignored, .env.example
  committed) with issuer http://host.docker.internal:8080

Verified: svelte-check + build clean; dev smoke test shows the landing in the
logged-out state and /login issuing a 302 to Zitadel's authorize endpoint with
PKCE/state/nonce (discovery reachable). Real client id/secret still needed to
complete the token exchange.
2026-07-05 22:58:47 +02:00

51 lines
1.4 KiB
TypeScript

import { redirect } from '@sveltejs/kit';
import * as client from 'openid-client';
import type { RequestHandler } from './$types';
import {
getOidcConfig,
authConfig,
OIDC_SCOPE,
STATE_COOKIE,
VERIFIER_COOKIE,
NONCE_COOKIE,
RETURN_COOKIE
} from '$lib/server/auth';
export const GET: RequestHandler = async ({ url, cookies }) => {
const config = await getOidcConfig();
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
const state = client.randomState();
const nonce = client.randomNonce();
const register = url.searchParams.get('mode') === 'register';
const returnTo = url.searchParams.get('returnTo') ?? '/explore';
const parameters: Record<string, string> = {
redirect_uri: authConfig.redirectUri,
scope: OIDC_SCOPE,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
state,
nonce
};
if (register) parameters.prompt = 'create';
const authorizationUrl = client.buildAuthorizationUrl(config, parameters);
const cookieOptions = {
httpOnly: true,
sameSite: 'lax' as const,
secure: url.protocol === 'https:',
path: '/',
maxAge: 600
};
cookies.set(VERIFIER_COOKIE, codeVerifier, cookieOptions);
cookies.set(STATE_COOKIE, state, cookieOptions);
cookies.set(NONCE_COOKIE, nonce, cookieOptions);
cookies.set(RETURN_COOKIE, returnTo, cookieOptions);
redirect(302, authorizationUrl.href);
};