Add OAuth flows and UI integration

- Implemented OAuth endpoints (providers list, authorization, callback, linked accounts management).
- Added UI translations for OAuth workflows (auth process messages, linked accounts management).
- Extended TypeScript types and React hooks to support OAuth features.
- Updated app configuration with OAuth-specific settings and provider details.
- Introduced skeleton implementations for authorization and token endpoints in provider mode.
- Included unit test and integration hooks for OAuth capabilities.
This commit is contained in:
Felipe Cardoso
2025-11-25 07:59:20 +01:00
parent 063a35e698
commit 84e0a7fe81
14 changed files with 1711 additions and 4 deletions

View File

@@ -3,7 +3,7 @@
import { type Client, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client';
import { client } from './client.gen';
import type { AdminActivateUserData, AdminActivateUserErrors, AdminActivateUserResponses, AdminAddOrganizationMemberData, AdminAddOrganizationMemberErrors, AdminAddOrganizationMemberResponses, AdminBulkUserActionData, AdminBulkUserActionErrors, AdminBulkUserActionResponses, AdminCreateOrganizationData, AdminCreateOrganizationErrors, AdminCreateOrganizationResponses, AdminCreateUserData, AdminCreateUserErrors, AdminCreateUserResponses, AdminDeactivateUserData, AdminDeactivateUserErrors, AdminDeactivateUserResponses, AdminDeleteOrganizationData, AdminDeleteOrganizationErrors, AdminDeleteOrganizationResponses, AdminDeleteUserData, AdminDeleteUserErrors, AdminDeleteUserResponses, AdminGetOrganizationData, AdminGetOrganizationErrors, AdminGetOrganizationResponses, AdminGetStatsData, AdminGetStatsResponses, AdminGetUserData, AdminGetUserErrors, AdminGetUserResponses, AdminListOrganizationMembersData, AdminListOrganizationMembersErrors, AdminListOrganizationMembersResponses, AdminListOrganizationsData, AdminListOrganizationsErrors, AdminListOrganizationsResponses, AdminListSessionsData, AdminListSessionsErrors, AdminListSessionsResponses, AdminListUsersData, AdminListUsersErrors, AdminListUsersResponses, AdminRemoveOrganizationMemberData, AdminRemoveOrganizationMemberErrors, AdminRemoveOrganizationMemberResponses, AdminUpdateOrganizationData, AdminUpdateOrganizationErrors, AdminUpdateOrganizationResponses, AdminUpdateUserData, AdminUpdateUserErrors, AdminUpdateUserResponses, ChangeCurrentUserPasswordData, ChangeCurrentUserPasswordErrors, ChangeCurrentUserPasswordResponses, CleanupExpiredSessionsData, CleanupExpiredSessionsResponses, ConfirmPasswordResetData, ConfirmPasswordResetErrors, ConfirmPasswordResetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, GetCurrentUserProfileData, GetCurrentUserProfileResponses, GetMyOrganizationsData, GetMyOrganizationsErrors, GetMyOrganizationsResponses, GetOrganizationData, GetOrganizationErrors, GetOrganizationMembersData, GetOrganizationMembersErrors, GetOrganizationMembersResponses, GetOrganizationResponses, GetUserByIdData, GetUserByIdErrors, GetUserByIdResponses, HealthCheckData, HealthCheckResponses, ListMySessionsData, ListMySessionsResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginOauthData, LoginOauthErrors, LoginOauthResponses, LoginResponses, LogoutAllData, LogoutAllResponses, LogoutData, LogoutErrors, LogoutResponses, RefreshTokenData, RefreshTokenErrors, RefreshTokenResponses, RegisterData, RegisterErrors, RegisterResponses, RequestPasswordResetData, RequestPasswordResetErrors, RequestPasswordResetResponses, RevokeSessionData, RevokeSessionErrors, RevokeSessionResponses, RootGetData, RootGetResponses, UpdateCurrentUserData, UpdateCurrentUserErrors, UpdateCurrentUserResponses, UpdateOrganizationData, UpdateOrganizationErrors, UpdateOrganizationResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses } from './types.gen';
import type { AdminActivateUserData, AdminActivateUserErrors, AdminActivateUserResponses, AdminAddOrganizationMemberData, AdminAddOrganizationMemberErrors, AdminAddOrganizationMemberResponses, AdminBulkUserActionData, AdminBulkUserActionErrors, AdminBulkUserActionResponses, AdminCreateOrganizationData, AdminCreateOrganizationErrors, AdminCreateOrganizationResponses, AdminCreateUserData, AdminCreateUserErrors, AdminCreateUserResponses, AdminDeactivateUserData, AdminDeactivateUserErrors, AdminDeactivateUserResponses, AdminDeleteOrganizationData, AdminDeleteOrganizationErrors, AdminDeleteOrganizationResponses, AdminDeleteUserData, AdminDeleteUserErrors, AdminDeleteUserResponses, AdminGetOrganizationData, AdminGetOrganizationErrors, AdminGetOrganizationResponses, AdminGetStatsData, AdminGetStatsResponses, AdminGetUserData, AdminGetUserErrors, AdminGetUserResponses, AdminListOrganizationMembersData, AdminListOrganizationMembersErrors, AdminListOrganizationMembersResponses, AdminListOrganizationsData, AdminListOrganizationsErrors, AdminListOrganizationsResponses, AdminListSessionsData, AdminListSessionsErrors, AdminListSessionsResponses, AdminListUsersData, AdminListUsersErrors, AdminListUsersResponses, AdminRemoveOrganizationMemberData, AdminRemoveOrganizationMemberErrors, AdminRemoveOrganizationMemberResponses, AdminUpdateOrganizationData, AdminUpdateOrganizationErrors, AdminUpdateOrganizationResponses, AdminUpdateUserData, AdminUpdateUserErrors, AdminUpdateUserResponses, ChangeCurrentUserPasswordData, ChangeCurrentUserPasswordErrors, ChangeCurrentUserPasswordResponses, CleanupExpiredSessionsData, CleanupExpiredSessionsResponses, ConfirmPasswordResetData, ConfirmPasswordResetErrors, ConfirmPasswordResetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, GetCurrentUserProfileData, GetCurrentUserProfileResponses, GetMyOrganizationsData, GetMyOrganizationsErrors, GetMyOrganizationsResponses, GetOauthAuthorizationUrlData, GetOauthAuthorizationUrlErrors, GetOauthAuthorizationUrlResponses, GetOauthServerMetadataData, GetOauthServerMetadataResponses, GetOrganizationData, GetOrganizationErrors, GetOrganizationMembersData, GetOrganizationMembersErrors, GetOrganizationMembersResponses, GetOrganizationResponses, GetUserByIdData, GetUserByIdErrors, GetUserByIdResponses, HandleOauthCallbackData, HandleOauthCallbackErrors, HandleOauthCallbackResponses, HealthCheckData, HealthCheckResponses, ListMySessionsData, ListMySessionsResponses, ListOauthAccountsData, ListOauthAccountsResponses, ListOauthProvidersData, ListOauthProvidersResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginOauthData, LoginOauthErrors, LoginOauthResponses, LoginResponses, LogoutAllData, LogoutAllResponses, LogoutData, LogoutErrors, LogoutResponses, OauthProviderAuthorizeData, OauthProviderAuthorizeErrors, OauthProviderAuthorizeResponses, OauthProviderRevokeData, OauthProviderRevokeErrors, OauthProviderRevokeResponses, OauthProviderTokenData, OauthProviderTokenErrors, OauthProviderTokenResponses, RefreshTokenData, RefreshTokenErrors, RefreshTokenResponses, RegisterData, RegisterErrors, RegisterOauthClientData, RegisterOauthClientErrors, RegisterOauthClientResponses, RegisterResponses, RequestPasswordResetData, RequestPasswordResetErrors, RequestPasswordResetResponses, RevokeSessionData, RevokeSessionErrors, RevokeSessionResponses, RootGetData, RootGetResponses, StartOauthLinkData, StartOauthLinkErrors, StartOauthLinkResponses, UnlinkOauthAccountData, UnlinkOauthAccountErrors, UnlinkOauthAccountResponses, UpdateCurrentUserData, UpdateCurrentUserErrors, UpdateCurrentUserResponses, UpdateOrganizationData, UpdateOrganizationErrors, UpdateOrganizationResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
/**
@@ -224,6 +224,240 @@ export const logoutAll = <ThrowOnError extends boolean = false>(options?: Option
});
};
/**
* List OAuth Providers
*
* Get list of enabled OAuth providers for the login/register UI.
*
* Returns:
* List of enabled providers with display info.
*/
export const listOauthProviders = <ThrowOnError extends boolean = false>(options?: Options<ListOauthProvidersData, ThrowOnError>) => {
return (options?.client ?? client).get<ListOauthProvidersResponses, unknown, ThrowOnError>({
responseType: 'json',
url: '/api/v1/oauth/providers',
...options
});
};
/**
* Get OAuth Authorization URL
*
* Get the authorization URL to redirect the user to the OAuth provider.
*
* The frontend should redirect the user to the returned URL.
* After authentication, the provider will redirect back to the callback URL.
*
* **Rate Limit**: 10 requests/minute
*/
export const getOauthAuthorizationUrl = <ThrowOnError extends boolean = false>(options: Options<GetOauthAuthorizationUrlData, ThrowOnError>) => {
return (options.client ?? client).get<GetOauthAuthorizationUrlResponses, GetOauthAuthorizationUrlErrors, ThrowOnError>({
responseType: 'json',
url: '/api/v1/oauth/authorize/{provider}',
...options
});
};
/**
* OAuth Callback
*
* Handle OAuth callback from provider.
*
* The frontend should call this endpoint with the code and state
* parameters received from the OAuth provider redirect.
*
* Returns:
* JWT tokens for the authenticated user.
*
* **Rate Limit**: 10 requests/minute
*/
export const handleOauthCallback = <ThrowOnError extends boolean = false>(options: Options<HandleOauthCallbackData, ThrowOnError>) => {
return (options.client ?? client).post<HandleOauthCallbackResponses, HandleOauthCallbackErrors, ThrowOnError>({
responseType: 'json',
url: '/api/v1/oauth/callback/{provider}',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
};
/**
* List Linked OAuth Accounts
*
* Get list of OAuth accounts linked to the current user.
*
* Requires authentication.
*/
export const listOauthAccounts = <ThrowOnError extends boolean = false>(options?: Options<ListOauthAccountsData, ThrowOnError>) => {
return (options?.client ?? client).get<ListOauthAccountsResponses, unknown, ThrowOnError>({
responseType: 'json',
security: [
{
scheme: 'bearer',
type: 'http'
}
],
url: '/api/v1/oauth/accounts',
...options
});
};
/**
* Unlink OAuth Account
*
* Unlink an OAuth provider from the current user.
*
* The user must have either a password set or another OAuth provider
* linked to ensure they can still log in.
*
* **Rate Limit**: 5 requests/minute
*/
export const unlinkOauthAccount = <ThrowOnError extends boolean = false>(options: Options<UnlinkOauthAccountData, ThrowOnError>) => {
return (options.client ?? client).delete<UnlinkOauthAccountResponses, UnlinkOauthAccountErrors, ThrowOnError>({
responseType: 'json',
security: [
{
scheme: 'bearer',
type: 'http'
}
],
url: '/api/v1/oauth/accounts/{provider}',
...options
});
};
/**
* Start Account Linking
*
* Start the OAuth flow to link a new provider to the current user.
*
* This is a convenience endpoint that redirects to /authorize/{provider}
* with the current user context.
*
* **Rate Limit**: 10 requests/minute
*/
export const startOauthLink = <ThrowOnError extends boolean = false>(options: Options<StartOauthLinkData, ThrowOnError>) => {
return (options.client ?? client).post<StartOauthLinkResponses, StartOauthLinkErrors, ThrowOnError>({
responseType: 'json',
security: [
{
scheme: 'bearer',
type: 'http'
}
],
url: '/api/v1/oauth/link/{provider}',
...options
});
};
/**
* OAuth Server Metadata
*
* OAuth 2.0 Authorization Server Metadata (RFC 8414).
*
* Returns server metadata including supported endpoints, scopes,
* and capabilities for MCP clients.
*/
export const getOauthServerMetadata = <ThrowOnError extends boolean = false>(options?: Options<GetOauthServerMetadataData, ThrowOnError>) => {
return (options?.client ?? client).get<GetOauthServerMetadataResponses, unknown, ThrowOnError>({
responseType: 'json',
url: '/api/v1/oauth/.well-known/oauth-authorization-server',
...options
});
};
/**
* Authorization Endpoint (Skeleton)
*
* OAuth 2.0 Authorization Endpoint.
*
* **NOTE**: This is a skeleton implementation. In a full implementation,
* this would:
* 1. Validate client_id and redirect_uri
* 2. Display consent screen to user
* 3. Generate authorization code
* 4. Redirect back to client with code
*
* Currently returns a 501 Not Implemented response.
*/
export const oauthProviderAuthorize = <ThrowOnError extends boolean = false>(options: Options<OauthProviderAuthorizeData, ThrowOnError>) => {
return (options.client ?? client).get<OauthProviderAuthorizeResponses, OauthProviderAuthorizeErrors, ThrowOnError>({
responseType: 'json',
url: '/api/v1/oauth/provider/authorize',
...options
});
};
/**
* Token Endpoint (Skeleton)
*
* OAuth 2.0 Token Endpoint.
*
* **NOTE**: This is a skeleton implementation. In a full implementation,
* this would exchange authorization codes for access tokens.
*
* Currently returns a 501 Not Implemented response.
*/
export const oauthProviderToken = <ThrowOnError extends boolean = false>(options: Options<OauthProviderTokenData, ThrowOnError>) => {
return (options.client ?? client).post<OauthProviderTokenResponses, OauthProviderTokenErrors, ThrowOnError>({
...urlSearchParamsBodySerializer,
responseType: 'json',
url: '/api/v1/oauth/provider/token',
...options,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...options.headers
}
});
};
/**
* Token Revocation Endpoint (Skeleton)
*
* OAuth 2.0 Token Revocation Endpoint (RFC 7009).
*
* **NOTE**: This is a skeleton implementation.
*
* Currently returns a 501 Not Implemented response.
*/
export const oauthProviderRevoke = <ThrowOnError extends boolean = false>(options: Options<OauthProviderRevokeData, ThrowOnError>) => {
return (options.client ?? client).post<OauthProviderRevokeResponses, OauthProviderRevokeErrors, ThrowOnError>({
...urlSearchParamsBodySerializer,
responseType: 'json',
url: '/api/v1/oauth/provider/revoke',
...options,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...options.headers
}
});
};
/**
* Register OAuth Client (Admin)
*
* Register a new OAuth client (admin only).
*
* This endpoint allows creating MCP clients that can authenticate
* against this API.
*
* **NOTE**: This is a minimal implementation.
*/
export const registerOauthClient = <ThrowOnError extends boolean = false>(options: Options<RegisterOauthClientData, ThrowOnError>) => {
return (options.client ?? client).post<RegisterOauthClientResponses, RegisterOauthClientErrors, ThrowOnError>({
...urlSearchParamsBodySerializer,
responseType: 'json',
url: '/api/v1/oauth/provider/clients',
...options,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...options.headers
}
});
};
/**
* List Users
*

View File

@@ -145,6 +145,108 @@ export type BodyLoginOauth = {
client_secret?: string | null;
};
/**
* Body_oauth_provider_revoke
*/
export type BodyOauthProviderRevoke = {
/**
* Token
*
* Token to revoke
*/
token: string;
/**
* Token Type Hint
*
* Token type hint (access_token, refresh_token)
*/
token_type_hint?: string | null;
/**
* Client Id
*
* Client ID
*/
client_id?: string | null;
/**
* Client Secret
*
* Client secret
*/
client_secret?: string | null;
};
/**
* Body_oauth_provider_token
*/
export type BodyOauthProviderToken = {
/**
* Grant Type
*
* Grant type (authorization_code)
*/
grant_type: string;
/**
* Code
*
* Authorization code
*/
code?: string | null;
/**
* Redirect Uri
*
* Redirect URI
*/
redirect_uri?: string | null;
/**
* Client Id
*
* Client ID
*/
client_id?: string | null;
/**
* Client Secret
*
* Client secret
*/
client_secret?: string | null;
/**
* Code Verifier
*
* PKCE code verifier
*/
code_verifier?: string | null;
/**
* Refresh Token
*
* Refresh token
*/
refresh_token?: string | null;
};
/**
* Body_register_oauth_client
*/
export type BodyRegisterOauthClient = {
/**
* Client Name
*
* Client application name
*/
client_name: string;
/**
* Redirect Uris
*
* Comma-separated list of redirect URIs
*/
redirect_uris: string;
/**
* Client Type
*
* public or confidential
*/
client_type?: string;
};
/**
* BulkAction
*
@@ -256,6 +358,230 @@ export type MessageResponse = {
message: string;
};
/**
* OAuthAccountResponse
*
* Schema for OAuth account response to clients.
*/
export type OAuthAccountResponse = {
/**
* Provider
*
* OAuth provider name
*/
provider: string;
/**
* Provider Email
*
* Email from OAuth provider
*/
provider_email?: string | null;
/**
* Id
*/
id: string;
/**
* Created At
*/
created_at: string;
};
/**
* OAuthAccountsListResponse
*
* Response containing list of linked OAuth accounts.
*/
export type OAuthAccountsListResponse = {
/**
* Accounts
*/
accounts: Array<OAuthAccountResponse>;
};
/**
* OAuthCallbackRequest
*
* Request parameters for OAuth callback.
*/
export type OAuthCallbackRequest = {
/**
* Code
*
* Authorization code from provider
*/
code: string;
/**
* State
*
* State parameter for CSRF protection
*/
state: string;
};
/**
* OAuthCallbackResponse
*
* Response after successful OAuth authentication.
*/
export type OAuthCallbackResponse = {
/**
* Access Token
*
* JWT access token
*/
access_token: string;
/**
* Refresh Token
*
* JWT refresh token
*/
refresh_token: string;
/**
* Token Type
*/
token_type?: string;
/**
* Expires In
*
* Token expiration in seconds
*/
expires_in: number;
/**
* Is New User
*
* Whether a new user was created
*/
is_new_user?: boolean;
};
/**
* OAuthProviderInfo
*
* Information about an available OAuth provider.
*/
export type OAuthProviderInfo = {
/**
* Provider
*
* Provider identifier (google, github)
*/
provider: string;
/**
* Name
*
* Human-readable provider name
*/
name: string;
/**
* Icon
*
* Icon identifier for frontend
*/
icon?: string | null;
};
/**
* OAuthProvidersResponse
*
* Response containing list of enabled OAuth providers.
*/
export type OAuthProvidersResponse = {
/**
* Enabled
*
* Whether OAuth is globally enabled
*/
enabled: boolean;
/**
* Providers
*
* List of enabled providers
*/
providers?: Array<OAuthProviderInfo>;
};
/**
* OAuthServerMetadata
*
* OAuth 2.0 Authorization Server Metadata (RFC 8414).
*/
export type OAuthServerMetadata = {
/**
* Issuer
*
* Authorization server issuer URL
*/
issuer: string;
/**
* Authorization Endpoint
*
* Authorization endpoint URL
*/
authorization_endpoint: string;
/**
* Token Endpoint
*
* Token endpoint URL
*/
token_endpoint: string;
/**
* Registration Endpoint
*
* Dynamic client registration endpoint
*/
registration_endpoint?: string | null;
/**
* Revocation Endpoint
*
* Token revocation endpoint
*/
revocation_endpoint?: string | null;
/**
* Scopes Supported
*
* Supported scopes
*/
scopes_supported?: Array<string>;
/**
* Response Types Supported
*
* Supported response types
*/
response_types_supported?: Array<string>;
/**
* Grant Types Supported
*
* Supported grant types
*/
grant_types_supported?: Array<string>;
/**
* Code Challenge Methods Supported
*
* Supported PKCE methods
*/
code_challenge_methods_supported?: Array<string>;
};
/**
* OAuthUnlinkResponse
*
* Response after unlinking an OAuth account.
*/
export type OAuthUnlinkResponse = {
/**
* Success
*
* Whether the unlink was successful
*/
success: boolean;
/**
* Message
*
* Status message
*/
message: string;
};
/**
* OrgDistributionData
*/
@@ -1097,6 +1423,352 @@ export type LogoutAllResponses = {
export type LogoutAllResponse = LogoutAllResponses[keyof LogoutAllResponses];
export type ListOauthProvidersData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/oauth/providers';
};
export type ListOauthProvidersResponses = {
/**
* Successful Response
*/
200: OAuthProvidersResponse;
};
export type ListOauthProvidersResponse = ListOauthProvidersResponses[keyof ListOauthProvidersResponses];
export type GetOauthAuthorizationUrlData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string;
};
path: {
/**
* Provider
*/
provider: string;
};
query: {
/**
* Redirect Uri
*
* Frontend callback URL after OAuth completes
*/
redirect_uri: string;
};
url: '/api/v1/oauth/authorize/{provider}';
};
export type GetOauthAuthorizationUrlErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetOauthAuthorizationUrlError = GetOauthAuthorizationUrlErrors[keyof GetOauthAuthorizationUrlErrors];
export type GetOauthAuthorizationUrlResponses = {
/**
* Response Get Oauth Authorization Url
*
* Successful Response
*/
200: {
[key: string]: unknown;
};
};
export type GetOauthAuthorizationUrlResponse = GetOauthAuthorizationUrlResponses[keyof GetOauthAuthorizationUrlResponses];
export type HandleOauthCallbackData = {
body: OAuthCallbackRequest;
path: {
/**
* Provider
*/
provider: string;
};
query: {
/**
* Redirect Uri
*
* Must match the redirect_uri used in authorization
*/
redirect_uri: string;
};
url: '/api/v1/oauth/callback/{provider}';
};
export type HandleOauthCallbackErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type HandleOauthCallbackError = HandleOauthCallbackErrors[keyof HandleOauthCallbackErrors];
export type HandleOauthCallbackResponses = {
/**
* Successful Response
*/
200: OAuthCallbackResponse;
};
export type HandleOauthCallbackResponse = HandleOauthCallbackResponses[keyof HandleOauthCallbackResponses];
export type ListOauthAccountsData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/oauth/accounts';
};
export type ListOauthAccountsResponses = {
/**
* Successful Response
*/
200: OAuthAccountsListResponse;
};
export type ListOauthAccountsResponse = ListOauthAccountsResponses[keyof ListOauthAccountsResponses];
export type UnlinkOauthAccountData = {
body?: never;
path: {
/**
* Provider
*/
provider: string;
};
query?: never;
url: '/api/v1/oauth/accounts/{provider}';
};
export type UnlinkOauthAccountErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type UnlinkOauthAccountError = UnlinkOauthAccountErrors[keyof UnlinkOauthAccountErrors];
export type UnlinkOauthAccountResponses = {
/**
* Successful Response
*/
200: OAuthUnlinkResponse;
};
export type UnlinkOauthAccountResponse = UnlinkOauthAccountResponses[keyof UnlinkOauthAccountResponses];
export type StartOauthLinkData = {
body?: never;
path: {
/**
* Provider
*/
provider: string;
};
query: {
/**
* Redirect Uri
*
* Frontend callback URL after OAuth completes
*/
redirect_uri: string;
};
url: '/api/v1/oauth/link/{provider}';
};
export type StartOauthLinkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type StartOauthLinkError = StartOauthLinkErrors[keyof StartOauthLinkErrors];
export type StartOauthLinkResponses = {
/**
* Response Start Oauth Link
*
* Successful Response
*/
200: {
[key: string]: unknown;
};
};
export type StartOauthLinkResponse = StartOauthLinkResponses[keyof StartOauthLinkResponses];
export type GetOauthServerMetadataData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/oauth/.well-known/oauth-authorization-server';
};
export type GetOauthServerMetadataResponses = {
/**
* Successful Response
*/
200: OAuthServerMetadata;
};
export type GetOauthServerMetadataResponse = GetOauthServerMetadataResponses[keyof GetOauthServerMetadataResponses];
export type OauthProviderAuthorizeData = {
body?: never;
path?: never;
query: {
/**
* Response Type
*
* Must be 'code'
*/
response_type: string;
/**
* Client Id
*
* OAuth client ID
*/
client_id: string;
/**
* Redirect Uri
*
* Redirect URI
*/
redirect_uri: string;
/**
* Scope
*
* Requested scopes
*/
scope?: string;
/**
* State
*
* CSRF state parameter
*/
state?: string;
/**
* Code Challenge
*
* PKCE code challenge
*/
code_challenge?: string | null;
/**
* Code Challenge Method
*
* PKCE method (S256)
*/
code_challenge_method?: string | null;
};
url: '/api/v1/oauth/provider/authorize';
};
export type OauthProviderAuthorizeErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type OauthProviderAuthorizeError = OauthProviderAuthorizeErrors[keyof OauthProviderAuthorizeErrors];
export type OauthProviderAuthorizeResponses = {
/**
* Response Oauth Provider Authorize
*
* Successful Response
*/
200: unknown;
};
export type OauthProviderTokenData = {
body: BodyOauthProviderToken;
path?: never;
query?: never;
url: '/api/v1/oauth/provider/token';
};
export type OauthProviderTokenErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type OauthProviderTokenError = OauthProviderTokenErrors[keyof OauthProviderTokenErrors];
export type OauthProviderTokenResponses = {
/**
* Response Oauth Provider Token
*
* Successful Response
*/
200: unknown;
};
export type OauthProviderRevokeData = {
body: BodyOauthProviderRevoke;
path?: never;
query?: never;
url: '/api/v1/oauth/provider/revoke';
};
export type OauthProviderRevokeErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type OauthProviderRevokeError = OauthProviderRevokeErrors[keyof OauthProviderRevokeErrors];
export type OauthProviderRevokeResponses = {
/**
* Response Oauth Provider Revoke
*
* Successful Response
*/
200: unknown;
};
export type RegisterOauthClientData = {
body: BodyRegisterOauthClient;
path?: never;
query?: never;
url: '/api/v1/oauth/provider/clients';
};
export type RegisterOauthClientErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type RegisterOauthClientError = RegisterOauthClientErrors[keyof RegisterOauthClientErrors];
export type RegisterOauthClientResponses = {
/**
* Response Register Oauth Client
*
* Successful Response
*/
200: unknown;
};
export type ListUsersData = {
body?: never;
path?: never;

View File

@@ -0,0 +1,235 @@
/**
* OAuth React Query Hooks
* Provides hooks for OAuth authentication flows
*/
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
listOauthProviders,
getOauthAuthorizationUrl,
handleOauthCallback,
listOauthAccounts,
unlinkOauthAccount,
startOauthLink,
getCurrentUserProfile,
} from '@/lib/api/generated';
import type {
OAuthProvidersResponse,
OAuthAccountsListResponse,
OAuthCallbackResponse,
UserResponse,
} from '@/lib/api/generated';
import { useAuth } from '@/lib/auth/AuthContext';
import config from '@/config/app.config';
// ============================================================================
// Query Keys
// ============================================================================
export const oauthKeys = {
all: ['oauth'] as const,
providers: () => [...oauthKeys.all, 'providers'] as const,
accounts: () => [...oauthKeys.all, 'accounts'] as const,
};
// ============================================================================
// Provider Queries
// ============================================================================
/**
* Fetch available OAuth providers
* Returns which providers are enabled for login/registration
*/
export function useOAuthProviders() {
return useQuery({
queryKey: oauthKeys.providers(),
queryFn: async () => {
const response = await listOauthProviders();
return response.data as OAuthProvidersResponse;
},
staleTime: 5 * 60 * 1000, // Providers don't change often
gcTime: 30 * 60 * 1000,
});
}
// ============================================================================
// OAuth Flow Mutations
// ============================================================================
/**
* Start OAuth login/registration flow
* Redirects user to the OAuth provider
*/
export function useOAuthStart() {
return useMutation({
mutationFn: async ({
provider,
mode,
}: {
provider: string;
mode: 'login' | 'register' | 'link';
}) => {
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
const response = await getOauthAuthorizationUrl({
path: { provider },
query: { redirect_uri: redirectUri },
});
if (response.data) {
// Store mode in sessionStorage for callback handling
sessionStorage.setItem('oauth_mode', mode);
sessionStorage.setItem('oauth_provider', provider);
// Response is { [key: string]: unknown }, so cast authorization_url
const authUrl = (response.data as { authorization_url: string }).authorization_url;
// Redirect to OAuth provider
window.location.href = authUrl;
}
return response.data;
},
});
}
/**
* Handle OAuth callback after provider redirect
* Exchanges the code for tokens and logs the user in
*/
export function useOAuthCallback() {
const { setAuth } = useAuth();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
provider,
code,
state,
}: {
provider: string;
code: string;
state: string;
}) => {
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
// Exchange code for tokens
const response = await handleOauthCallback({
path: { provider },
query: { redirect_uri: redirectUri },
body: {
code,
state,
},
});
const tokenData = response.data as OAuthCallbackResponse;
// Fetch user profile using the new access token
// We need to make this request with the new token
const userResponse = await getCurrentUserProfile({
headers: {
authorization: `Bearer ${tokenData.access_token}`,
},
});
return {
tokens: tokenData,
user: userResponse.data as UserResponse,
};
},
onSuccess: (data) => {
if (data?.tokens && data?.user) {
// Set auth state with tokens and user from OAuth
setAuth(
data.user,
data.tokens.access_token,
data.tokens.refresh_token,
data.tokens.expires_in
);
// Invalidate relevant queries
queryClient.invalidateQueries({ queryKey: ['user'] });
}
// Clean up session storage
sessionStorage.removeItem('oauth_mode');
sessionStorage.removeItem('oauth_provider');
},
onError: () => {
// Clean up session storage on error too
sessionStorage.removeItem('oauth_mode');
sessionStorage.removeItem('oauth_provider');
},
});
}
// ============================================================================
// Account Management
// ============================================================================
/**
* Fetch linked OAuth accounts for the current user
*/
export function useOAuthAccounts() {
const { isAuthenticated } = useAuth();
return useQuery({
queryKey: oauthKeys.accounts(),
queryFn: async () => {
const response = await listOauthAccounts();
return response.data as OAuthAccountsListResponse;
},
enabled: isAuthenticated,
staleTime: 60 * 1000, // 1 minute
});
}
/**
* Start OAuth account linking flow
* For users who want to add another OAuth provider to their account
*/
export function useOAuthLink() {
return useMutation({
mutationFn: async ({ provider }: { provider: string }) => {
const redirectUri = `${config.app.url}${config.oauth.callbackPath}/${provider}`;
const response = await startOauthLink({
path: { provider },
query: { redirect_uri: redirectUri },
});
if (response.data) {
// Store mode in sessionStorage for callback handling
sessionStorage.setItem('oauth_mode', 'link');
sessionStorage.setItem('oauth_provider', provider);
// Response is { [key: string]: unknown }, so cast authorization_url
const authUrl = (response.data as { authorization_url: string }).authorization_url;
// Redirect to OAuth provider
window.location.href = authUrl;
}
return response.data;
},
});
}
/**
* Unlink an OAuth account from the current user
*/
export function useOAuthUnlink() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ provider }: { provider: string }) => {
const response = await unlinkOauthAccount({
path: { provider },
});
return response.data;
},
onSuccess: () => {
// Invalidate accounts query to refresh the list
queryClient.invalidateQueries({ queryKey: oauthKeys.accounts() });
},
});
}