Repository navigation
[Feature] OAuth Refactor - #510
Conversation
- Replace hardcoded provider routes with unified wildcard endpoint - Implement generic OAuth methods using OAuthProvidersSchema - Add comprehensive error handling for unsupported providers - Remove repetitive code and improve maintainability - Fix route ordering to prevent wildcard route conflicts - Enhance type safety across frontend and backend - Add dynamic provider management in frontend - Remove noisy else statements for cleaner code"
feat: refactor OAuth system for scalability and type safety
WalkthroughThis PR refactors OAuth provider handling into a generic, provider-agnostic architecture. It introduces unified OAuth initiation and callback routes, consolidates provider-specific handler methods into generic dispatchers, adds support for LinkedIn and Microsoft providers, extends OAuth configs with timestamps and strict schema typing, and updates frontend components to use the new strongly-typed OAuthProvidersSchema. Changes
Sequence DiagramsequenceDiagram
participant Client
participant Routes as auth.oauth routes
participant AuthSvc as auth service
participant OAuthDAO as oauth DAO
participant Provider as OAuth Provider
rect rgb(200, 220, 240)
Note over Client,Provider: Generic OAuth Initiation Flow
Client->>Routes: GET /api/auth/oauth/:provider<br/>(with redirect_uri)
Routes->>Routes: validate provider via schema
Routes->>Routes: generate state JWT
Routes->>AuthSvc: generateOAuthUrl(provider, state)
AuthSvc->>AuthSvc: dispatch to provider-specific URL gen
AuthSvc-->>Routes: return authUrl
Routes-->>Client: return authUrl (JSON)
end
rect rgb(220, 240, 200)
Note over Client,Provider: Generic OAuth Callback Flow
Client->>Provider: user authorizes
Provider-->>Client: redirect with code/token + state
Client->>Routes: GET /api/auth/oauth/:provider/callback<br/>(with code, state)
Routes->>Routes: validate state JWT to extract redirectUri
Routes->>Routes: validate provider via schema
Routes->>AuthSvc: handleOAuthCallback(provider, {code})
AuthSvc->>AuthSvc: dispatch to provider-specific handler
AuthSvc->>Provider: exchange code for tokens
AuthSvc->>OAuthDAO: find/create user by provider ID
AuthSvc-->>Routes: return {accessToken, refreshToken}
Routes-->>Client: redirect to redirectUri with tokens
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes The refactor spans multiple layers (routes, services, DAO, schemas, frontend) with heterogeneous logic patterns. While individual changes are straightforward (routing to generic dispatchers), the breadth of affected files and type system changes across backend and frontend requires careful verification of consistency across the provider dispatch chain and schema validation. The introduction of new timestamp fields and the consolidation of six provider-specific handlers into generic flows adds moderate logic density. Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
🧰 Additional context used📓 Path-based instructions (5)**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
backend/src/**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
backend/src/{controllers,core}/**/*.ts📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/*.{tsx,ts}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/[a-z][a-z0-9-]*.ts📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
🧬 Code graph analysis (1)backend/src/core/auth/auth.ts (5)
🔇 Additional comments (4)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
96-112: Await the delete call and refresh configs; otherwise errors are uncaught and UI may not update.- const deleteOAuthConfig = async (providerId: OAuthProvidersSchema, providerName: string) => { + const deleteOAuthConfig = async (providerId: OAuthProvidersSchema, providerName: string) => { const shouldDelete = await confirm({ title: `Delete ${providerName} OAuth`, description: `Are you sure you want to delete the ${providerName} configuration? This action cannot be undone.`, confirmText: 'Delete', cancelText: 'Cancel', destructive: true, }); if (shouldDelete) { try { - deleteConfig(providerId); + await deleteConfig(providerId); + await refetchConfigs(); } catch (error) { console.error(`Failed to delete ${providerId} OAuth:`, error); } } };backend/src/core/auth/auth.ts (1)
868-868: Inconsistent base URL retrieval across OAuth providers.Lines 868, 1025, and 1095 use
process.env.API_BASE_URL || 'http://localhost:7130'directly, while other providers (Google, GitHub, Discord, Facebook) use thegetApiBaseUrl()helper. This inconsistency can cause redirect URI mismatches if the helper function applies different logic or reads from different environment variables.Apply this diff to use the consistent helper:
async exchangeCodeToTokenByMicrosoft( code: string ): Promise<{ access_token: string; id_token?: string }> { const oauthConfigService = OAuthConfigService.getInstance(); const config = await oauthConfigService.getConfigByProvider('microsoft'); if (!config) { throw new Error('Microsoft OAuth not configured'); } const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft'); - const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; + const selfBaseUrl = getApiBaseUrl(); const body = new URLSearchParams({ client_id: config.clientId ?? '', client_secret: clientSecret ?? '', code, redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`, grant_type: 'authorization_code', scope: config.scopes && config.scopes.length > 0 ? config.scopes.join(' ') : 'openid email profile offline_access User.Read', });async generateLinkedInOAuthUrl(state?: string): Promise<string> { const oauthConfigService = OAuthConfigService.getInstance(); const config = await oauthConfigService.getConfigByProvider('linkedin'); if (!config) { throw new Error('LinkedIn OAuth not configured'); } - const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; + const selfBaseUrl = getApiBaseUrl();logger.info('Exchanging LinkedIn code for tokens', { hasCode: !!code, clientId: config.clientId?.substring(0, 10) + '...', }); const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin'); - const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; + const selfBaseUrl = getApiBaseUrl(); const response = await axios.post(Also applies to: 1025-1025, 1095-1095
🧹 Nitpick comments (10)
frontend/src/features/auth/components/AuthMethodTab.tsx (2)
22-22: Use a type-only import for schema types (avoids runtime import with TS verbatimModuleSyntax).-import { OAuthProvidersSchema } from '@insforge/shared-schemas'; +import type { OAuthProvidersSchema } from '@insforge/shared-schemas';
128-136: Make enabledProviders a Partial<Record<…>> to reflect sparse population and remove unsafe assertion.- const enabledProviders = useMemo(() => { - const enabled: Record<OAuthProvidersSchema, boolean> = {} as Record< - OAuthProvidersSchema, - boolean - >; - providers.forEach((provider) => { - enabled[provider.id] = isProviderConfigured(provider.id); - }); - return enabled; - }, [isProviderConfigured]); + const enabledProviders = useMemo(() => { + const enabled: Partial<Record<OAuthProvidersSchema, boolean>> = {}; + providers.forEach((provider) => { + enabled[provider.id] = isProviderConfigured(provider.id); + }); + return enabled; + }, [isProviderConfigured]);Note: Update AddOAuthDialog prop accordingly (see its review).
frontend/src/features/auth/components/AddOAuthDialog.tsx (2)
12-12: Use a type-only import for schema types.-import { OAuthProvidersSchema } from '@insforge/shared-schemas'; +import type { OAuthProvidersSchema } from '@insforge/shared-schemas';
18-20: Align prop typing with actual map shape and make filtering explicit.- onConfirm: (selectedId: OAuthProvidersSchema) => void; - enabledProviders: Record<OAuthProvidersSchema, boolean>; + onConfirm: (selectedId: OAuthProvidersSchema) => void; + enabledProviders: Partial<Record<OAuthProvidersSchema, boolean>>;- const availableProviders = providers.filter((provider) => !enabledProviders[provider.id]); + const availableProviders = providers.filter( + (provider) => enabledProviders[provider.id] !== true + );Also applies to: 41-42
backend/src/core/auth/oauth.ts (1)
365-376: Update updated_at when only the secret changes (reflects actual mutation).- // Only secret was updated - await client.query('COMMIT'); + // Only secret was updated; bump updated_at for traceability + await client.query( + `UPDATE _oauth_configs SET updated_at = NOW() WHERE LOWER(provider) = LOWER($1)`, + [provider] + ); + await client.query('COMMIT');backend/src/api/routes/auth.oauth.ts (2)
39-49: Use successResponse for consistency with the rest of the API.- const response: ListOAuthConfigsResponse = { + const response: ListOAuthConfigsResponse = { data: configs, count: configs.length, }; - res.json(response); + successResponse(res, response);As per coding guidelines (consistent API responses).
61-77: Return via successResponse for consistency.- res.json({ - ...config, - clientSecret: clientSecret || undefined, - }); + successResponse(res, { + ...config, + clientSecret: clientSecret || undefined, + });As per coding guidelines.
backend/src/core/auth/auth.ts (3)
1320-1340: Add exhaustiveness check for type safety.The default case in the switch statement should use an exhaustiveness check pattern to ensure all
OAuthProvidersSchemavalues are handled at compile time. This prevents runtime errors if new providers are added to the schema but not implemented here.Apply this diff to add compile-time exhaustiveness checking:
async generateOAuthUrl(provider: OAuthProvidersSchema, state?: string): Promise<string> { switch (provider) { case 'google': return this.generateGoogleOAuthUrl(state); case 'github': return this.generateGitHubOAuthUrl(state); case 'discord': return this.generateDiscordOAuthUrl(state); case 'linkedin': return this.generateLinkedInOAuthUrl(state); case 'facebook': return this.generateFacebookOAuthUrl(state); case 'microsoft': return this.generateMicrosoftOAuthUrl(state); default: - throw new Error(`OAuth provider ${provider} is not implemented yet.`); + const _exhaustiveCheck: never = provider; + throw new Error(`OAuth provider ${_exhaustiveCheck} is not implemented yet.`); } }
1342-1365: Add exhaustiveness check and validate payload.Two improvements needed:
- The payload validation is deferred to individual handlers, but could be validated at this entry point for consistency
- The default case should use an exhaustiveness check pattern for compile-time safety
Apply this diff:
async handleOAuthCallback( provider: OAuthProvidersSchema, payload: { code?: string; token?: string } ): Promise<CreateSessionResponse> { + if (!payload.code && !payload.token) { + throw new AppError( + 'No authorization code or token provided', + 400, + ERROR_CODES.INVALID_INPUT + ); + } + switch (provider) { case 'google': return this.handleGoogleCallback(payload); case 'github': return this.handleGitHubCallback(payload); case 'discord': return this.handleDiscordCallback(payload); case 'linkedin': return this.handleLinkedInCallback(payload); case 'facebook': return this.handleFacebookCallback(payload); case 'microsoft': return this.handleMicrosoftCallback(payload); default: - throw new Error(`OAuth provider ${provider} is not implemented yet.`); + const _exhaustiveCheck: never = provider; + throw new Error(`OAuth provider ${_exhaustiveCheck} is not implemented yet.`); } }
1452-1452: Remove unnecessary type assertions.Lines 1452 and 1468 use
as stringtype assertions that are unnecessary since the guard conditions on lines 1448 and 1464 already ensurepayload.codeis defined.Apply this diff to remove unnecessary type assertions:
private async handleFacebookCallback(payload: { code?: string; token?: string; }): Promise<CreateSessionResponse> { if (!payload.code) { throw new AppError('No authorization code provided', 400, ERROR_CODES.INVALID_INPUT); } - const accessToken = await this.exchangeFacebookCodeForToken(payload.code as string); + const accessToken = await this.exchangeFacebookCodeForToken(payload.code); const facebookUserInfo = await this.getFacebookUserInfo(accessToken); return this.findOrCreateFacebookUser(facebookUserInfo); }private async handleMicrosoftCallback(payload: { code?: string; token?: string; }): Promise<CreateSessionResponse> { if (!payload.code) { throw new AppError('No authorization code provided', 400, ERROR_CODES.INVALID_INPUT); } - const accessToken = await this.exchangeCodeToTokenByMicrosoft(payload.code as string); + const accessToken = await this.exchangeCodeToTokenByMicrosoft(payload.code); const microsoftUserInfo = await this.getMicrosoftUserInfo(accessToken.access_token); return this.findOrCreateMicrosoftUser(microsoftUserInfo); }Also applies to: 1468-1468
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (16)
.env.example(1 hunks)backend/package.json(0 hunks)backend/src/api/routes/auth.oauth.ts(5 hunks)backend/src/core/auth/auth.ts(11 hunks)backend/src/core/auth/oauth.ts(6 hunks)backend/src/utils/seed.ts(4 hunks)docker-compose.prod.yml(1 hunks)docker-compose.yml(1 hunks)frontend/package.json(2 hunks)frontend/src/features/auth/components/AddOAuthDialog.tsx(3 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(4 hunks)frontend/src/features/auth/components/OAuthConfigDialog.tsx(2 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(1 hunks)frontend/src/features/auth/hooks/useOAuthConfig.ts(2 hunks)shared-schemas/src/auth-api.schema.ts(1 hunks)shared-schemas/src/auth.schema.ts(1 hunks)
💤 Files with no reviewable changes (1)
- backend/package.json
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/utils/seed.tsfrontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxshared-schemas/src/auth.schema.tsfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/core/auth/oauth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxshared-schemas/src/auth-api.schema.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/utils/seed.tsbackend/src/core/auth/oauth.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/utils/seed.tsfrontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxshared-schemas/src/auth.schema.tsfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/core/auth/oauth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxshared-schemas/src/auth-api.schema.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/utils/seed.tsshared-schemas/src/auth.schema.tsfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/core/auth/oauth.tsshared-schemas/src/auth-api.schema.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/hooks/useOAuthConfig.tsfrontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/hooks/useOAuthConfig.tsfrontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/OAuthConfigDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/use[A-Z]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Hook files must be named usePascalCase.ts (e.g., useAuth.ts)
Files:
frontend/src/features/auth/hooks/useOAuthConfig.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/oauth.tsbackend/src/core/auth/auth.ts
**/.env.example
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document environment variables and configuration in .env.example
Files:
.env.example
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
🧬 Code graph analysis (9)
backend/src/utils/seed.ts (1)
shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)
frontend/src/features/auth/components/OAuthConfigDialog.tsx (2)
shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)frontend/src/lib/utils/utils.ts (1)
isInsForgeCloudProject(158-160)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)
frontend/src/features/auth/components/AddOAuthDialog.tsx (2)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
OAuthProviderInfo(69-75)shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)
frontend/src/features/auth/hooks/useOAuthConfig.ts (1)
shared-schemas/src/auth.schema.ts (2)
OAuthProvidersSchema(110-110)OAuthConfigSchema(109-109)
backend/src/core/auth/oauth.ts (1)
shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (1)
oAuthConfigSchema(77-86)
backend/src/api/routes/auth.oauth.ts (3)
backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/api/middleware/auth.ts (2)
verifyAdmin(71-116)AuthRequest(8-17)shared-schemas/src/auth.schema.ts (1)
oAuthProvidersSchema(57-69)
backend/src/core/auth/auth.ts (3)
shared-schemas/src/auth.schema.ts (1)
OAuthProvidersSchema(110-110)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(195-195)backend/src/api/middleware/error.ts (1)
AppError(7-17)
🪛 dotenv-linter (4.0.0)
.env.example
[warning] 71-71: [EndingBlankLine] No blank line at the end of the file
(EndingBlankLine)
[warning] 71-71: [UnorderedKey] The APP_KEY key should go before the DEPLOYMENT_ID key
(UnorderedKey)
🔇 Additional comments (20)
frontend/package.json (2)
53-53: Type definitions version alignment looks good.The type definitions at 19.2.2 are ahead of the runtime at 19.2.0 by two patch levels, which is normal and acceptable. The major.minor versions match (19.2), ensuring proper type safety for React 19.2 features and the OAuth schema refactor.
Also applies to: 54-54
39-39: No issues found with React 19.2.0 update. The breaking change in React 19.2 (useId prefix change to "r") does not affect this codebase. The useId is used only internally within the Form component for accessibility attributes (aria-describedby) and is not exposed to external selectors, tests, or styling. The app does not use SSR or server-side rendering APIs. The caret constraint (^19.2.0) is standard practice and safe.Also applies to: 41-41
docker-compose.prod.yml (1)
99-102: LGTM! OAuth provider environment variables added.The addition of Microsoft and LinkedIn OAuth credentials is consistent with the existing OAuth provider pattern and aligns with the broader OAuth refactor.
docker-compose.yml (1)
102-105: LGTM! OAuth provider environment variables added.The addition of Microsoft and LinkedIn OAuth credentials mirrors the changes in docker-compose.prod.yml and maintains consistency across development and production environments.
backend/src/utils/seed.ts (3)
7-7: LGTM! Type-safe import for OAuth providers.The import of
OAuthProvidersSchemaenables type-safe provider handling throughout the seeding logic.
68-79: LGTM! Refactored default OAuth config seeding.The loop-based approach over
defaultProvidersreduces code duplication and improves maintainability. The type constraint ensures only valid providers are seeded.
99-145: LGTM! Environment-driven OAuth seeding is more maintainable.The
envMappingsarray structure eliminates repetitive code and makes it easy to add or modify provider configurations. All five providers (google, github, discord, linkedin, microsoft) are properly mapped with their respective environment variables.frontend/src/features/auth/components/UsersDataGrid.tsx (1)
54-59: LGTM! Microsoft provider display support added.The new case for Microsoft follows the established pattern and uses consistent styling with other enterprise providers.
frontend/src/features/auth/components/OAuthConfigDialog.tsx (2)
18-22: LGTM! Type-safe OAuth provider imports.The import of
OAuthProvidersSchemaenables compile-time validation of provider values.
71-80: No issues found—review comment is based on incorrect assumptions.The frontend list and backend shared key infrastructure are fully aligned. All five providers (
github,discord,config?.useSharedKeyand corresponding cloud API endpoints. The seed.ts file only initializes['google', 'github']as defaults, but this is a separate configuration decision—not a limitation of shared key support. The discrepancy between what's seeded and what supports shared keys is intentional.Likely an incorrect or invalid review comment.
frontend/src/features/auth/hooks/useOAuthConfig.ts (3)
8-8: LGTM! Type-safe OAuth provider import.The import of
OAuthProvidersSchemaenables type-safe provider handling in this hook.
16-16: LGTM! Strengthened type for selected provider.Changing
selectedProviderfromstring | nulltoOAuthProvidersSchema | nullensures only valid provider values can be selected at compile time.
86-96: LGTM! Type-safe helper functions.The parameter type updates to
OAuthProvidersSchemainisProviderConfiguredandgetProviderConfigensure callers can only pass valid provider identifiers.frontend/src/features/auth/components/AuthMethodTab.tsx (1)
143-154: LGTM on schema-driven selection.frontend/src/features/auth/components/AddOAuthDialog.tsx (1)
29-29: LGTM on state and handler typing.Also applies to: 43-45
shared-schemas/src/auth-api.schema.ts (1)
147-156: LGTM on update schema omission + partial.backend/src/api/routes/auth.oauth.ts (1)
17-18: Provider validation with oAuthProvidersSchema is solid.backend/src/core/auth/auth.ts (3)
456-456: LGTM: Method signature updates.The method signature changes are correct:
- Renaming from
generateXAuthUrltogenerateXOAuthUrlimproves naming consistency- Adding explicit
asynckeyword andPromise<string>return type improves type safetyAlso applies to: 508-508, 555-555, 832-832, 1017-1017, 1199-1199
900-920: LGTM: Microsoft user info handling.The email fallback logic properly handles the nullable
1159-1159: No action required—issuer URL is correct.The issuer URL
https://www.linkedin.com/oauthis the correct endpoint for LinkedIn OpenID Connect, matching LinkedIn's official OAuth documentation.


Summary
Refactor OAuth Login system into a more maintainable manner.
Also cleaned/updated some packages
How did you test this change?
Tested with both custom keys and shared keys.
You can test it as well at https://oauth-test-nu.vercel.app/
Summary by CodeRabbit
New Features
Chores