mirror of
https://github.com/appwrite/console.git
synced 2026-11-18 20:47:21 +00:00
(refactor): flatten the consent-page flow and extract oauth2 error constants
- Hoist the flow out of the 220-line effect into one named function per entry branch (grant_id / request_uri / raw client_id), cancelled via a run counter instead of a closed-over flag. - Dedupe the authorize-request param extraction shared by createPAR and authorize into readAuthorizeParams(), plus getAccount()/fail() helpers. - Move error messages and the oauth2_invalid_request exception type into a colocated errors.ts. - Build navigation targets with resolve() to satisfy svelte/no-navigation-without-resolve.
This commit is contained in:
2 files changed
+237
-213
No files matched your search
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { base } from '$app/paths';
|
||||
import { resolve } from '$app/paths';
|
||||
import { page } from '$app/state';
|
||||
import { AppwriteException, type Models } from '@appwrite.io/console';
|
||||
import { Card, Layout, Typography, Icon, Spinner } from '@appwrite.io/pink-svelte';
|
||||
@@ -10,13 +10,15 @@
|
||||
import { isWebRedirect } from '$lib/helpers/oauth2-redirect';
|
||||
import OAuth2ConsentCard, { type OAuth2Outcome } from '../consent-card.svelte';
|
||||
import OAuth2OutcomeCard from '../outcome-card.svelte';
|
||||
import { OAuth2ErrorMessage, OAuth2ErrorType } from '../errors';
|
||||
|
||||
type Phase = 'loading' | 'ready' | 'approved' | 'denied' | 'error';
|
||||
type Account = Models.User<Models.Preferences>;
|
||||
|
||||
let phase = $state<Phase>('loading');
|
||||
let grant = $state<Models.Oauth2Grant | null>(null);
|
||||
let app = $state<Models.App | null>(null);
|
||||
let account = $state<Models.User<Models.Preferences> | null>(null);
|
||||
let account = $state<Account | null>(null);
|
||||
let error = $state<string | null>(null);
|
||||
let completedRedirectUrl = $state<string | undefined>(undefined);
|
||||
|
||||
@@ -28,6 +30,214 @@
|
||||
return Number.isInteger(value) && value >= 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function getAccount(): Promise<Account | null> {
|
||||
return sdk.forConsole.account.get().catch(() => null) as Promise<Account | null>;
|
||||
}
|
||||
|
||||
// The authorize-request fields shared verbatim between createPAR (pre-login
|
||||
// push) and authorize (authenticated direct path).
|
||||
function readAuthorizeParams(params: URLSearchParams) {
|
||||
const resources = params.getAll('resource');
|
||||
return {
|
||||
redirectUri: params.get('redirect_uri') ?? '',
|
||||
responseType: params.get('response_type') ?? 'code',
|
||||
scope: params.get('scope') ?? '',
|
||||
state: params.get('state') ?? undefined,
|
||||
nonce: params.get('nonce') ?? undefined,
|
||||
codeChallenge: params.get('code_challenge') ?? undefined,
|
||||
codeChallengeMethod: params.get('code_challenge_method') ?? undefined,
|
||||
prompt: params.get('prompt') ?? undefined,
|
||||
maxAge: parseMaxAge(params.get('max_age')),
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined,
|
||||
resource: resources.length > 0 ? (resources as unknown as string) : undefined
|
||||
};
|
||||
}
|
||||
|
||||
function goSignIn(resumeUrl?: string) {
|
||||
const target = resumeUrl ?? window.location.pathname + window.location.search;
|
||||
void goto(resolve(`/login?redirect=${encodeURIComponent(target)}`), {
|
||||
replaceState: true
|
||||
});
|
||||
}
|
||||
|
||||
function fail(e: unknown, fallback: string) {
|
||||
error = (e as Error)?.message ?? fallback;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
// Load a grant + its app branding and render the consent card.
|
||||
async function loadConsent(
|
||||
grantId: string,
|
||||
cancelled: () => boolean,
|
||||
knownAccount?: Account | null
|
||||
): Promise<void> {
|
||||
const loadedGrant = await sdk.forConsole.oauth2.getGrant({ grantId });
|
||||
const [loadedApp, loadedAccount] = await Promise.all([
|
||||
sdk.forConsole.apps.get({ appId: loadedGrant.appId }),
|
||||
knownAccount !== undefined ? Promise.resolve(knownAccount) : getAccount()
|
||||
]);
|
||||
if (cancelled()) return;
|
||||
grant = loadedGrant;
|
||||
app = loadedApp;
|
||||
account = loadedAccount;
|
||||
phase = 'ready';
|
||||
}
|
||||
|
||||
async function resumeFromGrant(grantId: string, cancelled: () => boolean): Promise<void> {
|
||||
try {
|
||||
await loadConsent(grantId, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
if (e instanceof AppwriteException && e.code === 401) {
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
fail(e, OAuth2ErrorMessage.GRANT_INVALID);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAuthorizeResult(
|
||||
result: Models.Oauth2Authorize,
|
||||
loggedInAccount: Account,
|
||||
clientId: string | null,
|
||||
fromRequestUri: boolean,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
if (result.redirectUrl) {
|
||||
// Already consented — go straight back to the client.
|
||||
window.location.href = result.redirectUrl;
|
||||
if (!isWebRedirect(result.redirectUrl)) {
|
||||
completedRedirectUrl = result.redirectUrl;
|
||||
account = loggedInAccount;
|
||||
app = clientId
|
||||
? await sdk.forConsole.apps.get({ appId: clientId }).catch(() => null)
|
||||
: null;
|
||||
if (cancelled()) return;
|
||||
phase = 'approved';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.grantId) {
|
||||
if (fromRequestUri) {
|
||||
// The handle is now consumed — rewrite to the grant URL so
|
||||
// reloads resume via getGrant instead of a dead request_uri.
|
||||
await goto(resolve(`/oauth2/consent?grant_id=${result.grantId}`), {
|
||||
replaceState: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
await loadConsent(result.grantId, cancelled, loggedInAccount);
|
||||
return;
|
||||
}
|
||||
error = OAuth2ErrorMessage.AUTHORIZE_FAILED;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
async function resumeFromRequestUri(
|
||||
clientId: string | null,
|
||||
requestUri: string,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
const loggedInAccount = await getAccount();
|
||||
if (cancelled()) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Dereferencing while logged out can only 401; keep the
|
||||
// single-use handle untouched and go straight to login.
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// The server rejects request_uri combined with any other
|
||||
// authorization param; only client_id may accompany it.
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId: clientId ?? undefined,
|
||||
requestUri
|
||||
});
|
||||
if (cancelled()) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, true, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
// Since only the handle is sent, oauth2_invalid_request can only
|
||||
// mean the handle is unusable.
|
||||
if (e instanceof AppwriteException && e.type === OAuth2ErrorType.INVALID_REQUEST) {
|
||||
error = OAuth2ErrorMessage.HANDLE_EXPIRED;
|
||||
phase = 'error';
|
||||
return;
|
||||
}
|
||||
fail(e, OAuth2ErrorMessage.AUTHORIZE_FAILED);
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-login entry with raw authorize params in the URL.
|
||||
async function startAuthorize(
|
||||
clientId: string,
|
||||
params: URLSearchParams,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
const loggedInAccount = await getAccount();
|
||||
if (cancelled()) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Carry only a short request_uri through login — the full
|
||||
// consent URL travels inside the OAuth provider's `state`
|
||||
// during GitHub sign-in and can exceed its size limits.
|
||||
try {
|
||||
const par = await sdk.forConsole.oauth2.createPAR({
|
||||
clientId,
|
||||
...readAuthorizeParams(params)
|
||||
});
|
||||
if (cancelled()) return;
|
||||
goSignIn(
|
||||
`${resolve('/oauth2/consent')}?client_id=${encodeURIComponent(clientId)}&request_uri=${encodeURIComponent(par.request_uri)}`
|
||||
);
|
||||
} catch {
|
||||
if (cancelled()) return;
|
||||
// PAR unavailable (older server) or invalid request —
|
||||
// fall back to the legacy full-URL redirect.
|
||||
goSignIn();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Authenticated: ask the server to create a grant (or detect an
|
||||
// existing approved identity), then render consent or redirect.
|
||||
try {
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId,
|
||||
...readAuthorizeParams(params)
|
||||
});
|
||||
if (cancelled()) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, false, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
fail(e, OAuth2ErrorMessage.AUTHORIZE_FAILED);
|
||||
}
|
||||
}
|
||||
|
||||
async function init(params: URLSearchParams, cancelled: () => boolean): Promise<void> {
|
||||
const grantId = params.get('grant_id');
|
||||
if (grantId) {
|
||||
await resumeFromGrant(grantId, cancelled);
|
||||
return;
|
||||
}
|
||||
|
||||
const clientId = params.get('client_id');
|
||||
const requestUri = params.get('request_uri');
|
||||
if (requestUri) {
|
||||
await resumeFromRequestUri(clientId, requestUri, cancelled);
|
||||
return;
|
||||
}
|
||||
if (clientId) {
|
||||
await startAuthorize(clientId, params, cancelled);
|
||||
return;
|
||||
}
|
||||
|
||||
error = OAuth2ErrorMessage.MISSING_REQUEST;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
function onDone(outcome: OAuth2Outcome, redirectUrl?: string) {
|
||||
completedRedirectUrl = redirectUrl;
|
||||
phase = outcome === 'approved' ? 'approved' : 'denied';
|
||||
@@ -39,227 +249,23 @@
|
||||
// already-consumed single-use request_uri.
|
||||
const authorizeQuery = $derived(page.url.searchParams.toString());
|
||||
|
||||
let currentRun = 0;
|
||||
|
||||
// Re-runs when the authorize params change (this route can stay mounted as
|
||||
// the router moves between requests). Reset to loading so a previously
|
||||
// loaded grant can never be approved against a different request.
|
||||
$effect(() => {
|
||||
const query = authorizeQuery;
|
||||
const params = new URLSearchParams(authorizeQuery);
|
||||
const run = ++currentRun;
|
||||
|
||||
let cancelled = false;
|
||||
phase = 'loading';
|
||||
error = null;
|
||||
completedRedirectUrl = undefined;
|
||||
|
||||
const currentRelativeUrl = () => window.location.pathname + window.location.search;
|
||||
|
||||
const goSignIn = (resumeUrl?: string) => {
|
||||
const target = resumeUrl ?? currentRelativeUrl();
|
||||
void goto(`${base}/login?redirect=${encodeURIComponent(target)}`, {
|
||||
replaceState: true
|
||||
});
|
||||
};
|
||||
|
||||
// Load a grant + its app branding and render the consent card.
|
||||
async function loadConsent(
|
||||
grantId: string,
|
||||
knownAccount?: Models.User<Models.Preferences> | null
|
||||
): Promise<void> {
|
||||
const loadedGrant = await sdk.forConsole.oauth2.getGrant({ grantId });
|
||||
const [loadedApp, loadedAccount] = await Promise.all([
|
||||
sdk.forConsole.apps.get({ appId: loadedGrant.appId }),
|
||||
knownAccount !== undefined
|
||||
? Promise.resolve(knownAccount)
|
||||
: (sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null) as Promise<Models.User<Models.Preferences> | null>)
|
||||
]);
|
||||
if (cancelled) return;
|
||||
grant = loadedGrant;
|
||||
app = loadedApp;
|
||||
account = loadedAccount;
|
||||
phase = 'ready';
|
||||
}
|
||||
|
||||
async function init(): Promise<void> {
|
||||
const params = new URLSearchParams(query);
|
||||
const grantId = params.get('grant_id');
|
||||
|
||||
if (grantId) {
|
||||
try {
|
||||
await loadConsent(grantId);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return;
|
||||
if (e instanceof AppwriteException && e.code === 401) {
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
error =
|
||||
(e as Error)?.message ??
|
||||
'This authorization request is invalid or has expired.';
|
||||
phase = 'error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
async function handleAuthorizeResult(
|
||||
result: Models.Oauth2Authorize,
|
||||
loggedInAccount: Models.User<Models.Preferences>,
|
||||
clientId: string | null,
|
||||
fromRequestUri: boolean
|
||||
): Promise<void> {
|
||||
if (result.redirectUrl) {
|
||||
// Already consented — go straight back to the client.
|
||||
window.location.href = result.redirectUrl;
|
||||
if (!isWebRedirect(result.redirectUrl)) {
|
||||
completedRedirectUrl = result.redirectUrl;
|
||||
account = loggedInAccount;
|
||||
app = clientId
|
||||
? await sdk.forConsole.apps.get({ appId: clientId }).catch(() => null)
|
||||
: null;
|
||||
if (cancelled) return;
|
||||
phase = 'approved';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.grantId) {
|
||||
if (fromRequestUri) {
|
||||
// The handle is now consumed — rewrite to the grant URL so
|
||||
// reloads resume via getGrant instead of a dead request_uri.
|
||||
await goto(`${base}/oauth2/consent?grant_id=${result.grantId}`, {
|
||||
replaceState: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
await loadConsent(result.grantId, loggedInAccount);
|
||||
return;
|
||||
}
|
||||
error = 'Could not start authorization.';
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
const clientId = params.get('client_id');
|
||||
const requestUri = params.get('request_uri');
|
||||
|
||||
if (requestUri) {
|
||||
const loggedInAccount = (await sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null)) as Models.User<Models.Preferences> | null;
|
||||
if (cancelled) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Dereferencing while logged out can only 401; keep the
|
||||
// single-use handle untouched and go straight to login.
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// The server rejects request_uri combined with any other
|
||||
// authorization param; only client_id may accompany it.
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId: clientId ?? undefined,
|
||||
requestUri
|
||||
});
|
||||
if (cancelled) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, true);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return;
|
||||
// Every dead-handle case (expired, consumed, malformed) is
|
||||
// reported as oauth2_invalid_request; since only the handle
|
||||
// is sent, that type can only mean the handle is unusable.
|
||||
const invalidHandle =
|
||||
e instanceof AppwriteException && e.type === 'oauth2_invalid_request';
|
||||
error = invalidHandle
|
||||
? 'This sign-in request has expired. Return to the application and try connecting again.'
|
||||
: ((e as Error)?.message ?? 'Could not start authorization.');
|
||||
phase = 'error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// No grant yet: this is the pre-login entry with raw authorize params.
|
||||
if (clientId) {
|
||||
const loggedInAccount = (await sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null)) as Models.User<Models.Preferences> | null;
|
||||
if (cancelled) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Carry only a short request_uri through login — the full
|
||||
// consent URL travels inside the OAuth provider's `state`
|
||||
// during GitHub sign-in and can exceed its size limits.
|
||||
const resources = params.getAll('resource');
|
||||
try {
|
||||
const par = await sdk.forConsole.oauth2.createPAR({
|
||||
clientId,
|
||||
redirectUri: params.get('redirect_uri') ?? '',
|
||||
responseType: params.get('response_type') ?? 'code',
|
||||
scope: params.get('scope') ?? '',
|
||||
state: params.get('state') ?? undefined,
|
||||
nonce: params.get('nonce') ?? undefined,
|
||||
codeChallenge: params.get('code_challenge') ?? undefined,
|
||||
codeChallengeMethod: params.get('code_challenge_method') ?? undefined,
|
||||
prompt: params.get('prompt') ?? undefined,
|
||||
maxAge: parseMaxAge(params.get('max_age')),
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined,
|
||||
// SDK types `resource` as string; the server accepts
|
||||
// a URI list (RFC 8707).
|
||||
resource:
|
||||
resources.length > 0 ? (resources as unknown as string) : undefined
|
||||
});
|
||||
if (cancelled) return;
|
||||
goSignIn(
|
||||
`${base}/oauth2/consent?client_id=${encodeURIComponent(clientId)}&request_uri=${encodeURIComponent(par.request_uri)}`
|
||||
);
|
||||
} catch {
|
||||
if (cancelled) return;
|
||||
// PAR unavailable (older server) or invalid request —
|
||||
// fall back to the legacy full-URL redirect.
|
||||
goSignIn();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Authenticated: ask the server to create a grant (or detect an
|
||||
// existing approved identity) via the SDK, then render consent or
|
||||
// redirect.
|
||||
try {
|
||||
const resources = params.getAll('resource');
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId,
|
||||
redirectUri: params.get('redirect_uri') ?? '',
|
||||
responseType: params.get('response_type') ?? 'code',
|
||||
scope: params.get('scope') ?? '',
|
||||
state: params.get('state') ?? undefined,
|
||||
nonce: params.get('nonce') ?? undefined,
|
||||
codeChallenge: params.get('code_challenge') ?? undefined,
|
||||
codeChallengeMethod: params.get('code_challenge_method') ?? undefined,
|
||||
prompt: params.get('prompt') ?? undefined,
|
||||
maxAge: parseMaxAge(params.get('max_age')),
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined,
|
||||
// SDK types `resource` as string; the server accepts
|
||||
// a URI list (RFC 8707).
|
||||
resource:
|
||||
resources.length > 0 ? (resources as unknown as string) : undefined
|
||||
});
|
||||
if (cancelled) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, false);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return;
|
||||
error = (e as Error)?.message ?? 'Could not start authorization.';
|
||||
phase = 'error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
error = 'Missing authorization request. Open this page from an application sign-in.';
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
void init();
|
||||
void init(params, () => run !== currentRun);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
currentRun++;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
@@ -286,7 +292,7 @@
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
{error}
|
||||
</Typography.Text>
|
||||
<Button on:click={() => goto(base, { replaceState: true })}>
|
||||
<Button on:click={() => goto(resolve('/'), { replaceState: true })}>
|
||||
Go to console
|
||||
</Button>
|
||||
</Layout.Stack>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Exception `type` values returned by the OAuth2 endpoints. The SDK does not
|
||||
* export these, so they are mirrored here.
|
||||
*/
|
||||
export const OAuth2ErrorType = {
|
||||
/**
|
||||
* Covers every dead request_uri handle case (expired, consumed, malformed).
|
||||
*/
|
||||
INVALID_REQUEST: 'oauth2_invalid_request'
|
||||
} as const;
|
||||
|
||||
export const OAuth2ErrorMessage = {
|
||||
AUTHORIZE_FAILED: 'Could not start authorization.',
|
||||
GRANT_INVALID: 'This authorization request is invalid or has expired.',
|
||||
HANDLE_EXPIRED:
|
||||
'This sign-in request has expired. Return to the application and try connecting again.',
|
||||
MISSING_REQUEST: 'Missing authorization request. Open this page from an application sign-in.'
|
||||
} as const;
|
||||
Reference in new issue
Block a user