trails/apps/journal/app/routes/oauth.authorize.tsx
Ullrich Schäfer b9aac2859a
Drop auth.server.ts re-exports + rename to .server.ts convention (task 5.2)
Two cleanups in one pass:

1. Update import paths app-wide from `~/lib/auth.server` to
   `~/lib/auth/session.server` for the four session helpers
   (sessionStorage, createSession, getSessionUser, destroySession).
   ~40 files: 33 simple path swaps where the file imported only session
   symbols, 5 splits where it also imported per-method auth functions
   (auth.verify.tsx, api.settings.email.ts, activities.\$id.tsx,
   routes.\$id.tsx, auth.accept-terms.tsx) — those keep one import
   from auth.server (for verifyMagicToken, canView, recordTermsAcceptance,
   etc.) and gain a second import from auth/session.server.
   Two more files used relative paths and were missed by the first
   grep pass (lib/oauth.server.ts and routes/oauth.authorize.tsx) —
   migrated too.
   The @deprecated re-exports block in auth.server.ts is gone.

2. Rename the new auth files to follow the project's `.server.ts`
   convention so Vite/React Router treat them as server-only (they
   read process.env.SESSION_SECRET, hit the DB, etc. — must NOT enter
   the client bundle):
   - auth/session.ts → auth/session.server.ts
   - auth/completion.ts → auth/completion.server.ts
   - auth/completion.test.ts → auth/completion.server.test.ts
   Done with `git mv` so blame is preserved.

Verified: typecheck + lint green; 126 unit tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 03:01:30 +02:00

80 lines
2.8 KiB
TypeScript

import type { Route } from "./+types/oauth.authorize";
import { redirect } from "react-router";
import { getSessionUser } from "../lib/auth/session.server.ts";
import {
getOAuthClient,
validateRedirectUri,
createAuthorizationCode,
} from "../lib/oauth.server.ts";
/**
* GET /oauth/authorize
*
* OAuth2 authorization endpoint. If the user is already logged in,
* generates an authorization code and redirects. Otherwise redirects
* to the login page with a return URL.
*
* Query params:
* - client_id
* - redirect_uri
* - code_challenge
* - code_challenge_method (default: S256)
* - response_type (must be "code")
* - state (opaque, passed back to client)
*/
export async function loader({ request }: Route.LoaderArgs) {
const url = new URL(request.url);
const clientId = url.searchParams.get("client_id");
const redirectUri = url.searchParams.get("redirect_uri");
const codeChallenge = url.searchParams.get("code_challenge");
const codeChallengeMethod = url.searchParams.get("code_challenge_method") ?? "S256";
const responseType = url.searchParams.get("response_type");
const state = url.searchParams.get("state") ?? "";
// Validate required params
if (!clientId || !redirectUri || !codeChallenge || responseType !== "code") {
return new Response(
JSON.stringify({ error: "invalid_request", error_description: "Missing required parameters" }),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
if (codeChallengeMethod !== "S256" && codeChallengeMethod !== "plain") {
return new Response(
JSON.stringify({ error: "invalid_request", error_description: "Unsupported code_challenge_method" }),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
// Validate client
const client = await getOAuthClient(clientId);
if (!client || !validateRedirectUri(client, redirectUri)) {
return new Response(
JSON.stringify({ error: "invalid_client", error_description: "Unknown client or redirect URI" }),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
// Check if user is already authenticated
const user = await getSessionUser(request);
if (!user) {
// Redirect to login with return URL so we come back here after auth
const returnUrl = url.pathname + url.search;
return redirect(`/auth/login?returnTo=${encodeURIComponent(returnUrl)}`);
}
// User is authenticated — issue code and redirect to client
const code = await createAuthorizationCode({
userId: user.id,
clientId,
codeChallenge,
codeChallengeMethod,
redirectUri,
});
const callbackUrl = new URL(redirectUri);
callbackUrl.searchParams.set("code", code);
if (state) callbackUrl.searchParams.set("state", state);
return redirect(callbackUrl.toString());
}