Skip to content

[Feature] OAuth Refactor - #510

Merged
Fermionic-Lyu merged 13 commits into
mainfrom
oauth-refactor-fix
Oct 23, 2025
Merged

Fermionic-Lyu merged 13 commits into
mainfrom
oauth-refactor-fix

Conversation

@Fermionic-Lyu

@Fermionic-Lyu Fermionic-Lyu commented Oct 22, 2025 •

Copy link
Copy Markdown
Member

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.

image

You can test it as well at https://oauth-test-nu.vercel.app/

Summary by CodeRabbit

  • New Features

    • Added LinkedIn and Microsoft OAuth authentication support.
    • Unified OAuth flow for streamlined authentication across all providers.
  • Chores

    • Updated React and React DOM to version 19.2.0.
    • Removed unused type dependencies.

Laaaaksh and others added 9 commits October 22, 2025 14:21
- 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
@coderabbitai

coderabbitai Bot commented Oct 22, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This 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

Cohort / File(s) Change Summary
Dependency cleanup
backend/package.json
Removed unused type definitions: @types/node-pg-migrate and @types/socket.io.
OAuth routes refactor
backend/src/api/routes/auth.oauth.ts
Introduced generic OAuth flow with unified routes: GET /api/auth/oauth/:provider (initiate), GET /api/auth/oauth/shared/callback/:state and GET /api/auth/oauth/:provider/callback (handle callbacks). Added provider validation via oAuthProvidersSchema. Changed config endpoints to return JSON directly instead of using response helper.
Auth service provider methods
backend/src/core/auth/auth.ts
Renamed provider-specific URL generators (e.g., generateGoogleAuthUrl → generateGoogleOAuthUrl) with stricter return types (string instead of string | undefined). Added generic generateOAuthUrl() and handleOAuthCallback() dispatchers. Introduced private provider-specific callback handlers for all six providers. Updated LinkedIn issuer to https://www.linkedin.com/oauth.
OAuth config DAO & types
backend/src/core/auth/oauth.ts
Changed CreateOAuthConfigInput.provider from string to OAuthProvidersSchema. Added id, createdAt, and updatedAt fields to all DAO queries. Expanded default scopes mapping for all supported providers. Updated createConfig and updateConfig to include and return timestamp fields.
OAuth seeding
backend/src/utils/seed.ts
Replaced hard-coded per-provider blocks with a loop over defaultProviders and new envMappings structure. Added support for Discord, LinkedIn, and Microsoft providers via environment variables.
Docker environment configuration
docker-compose.yml, docker-compose.prod.yml
Added four new environment variables: MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, LINKEDIN_CLIENT_ID, LINKEDIN_CLIENT_SECRET to the insforge service.
Frontend React version
frontend/package.json
Updated React and React-DOM from pinned 19.1.1 to caret-compatible ^19.2.0. Updated corresponding TypeScript type definitions to ^19.2.2.
Frontend OAuth components
frontend/src/features/auth/components/AddOAuthDialog.tsx, AuthMethodTab.tsx
Updated component props and internal state types to use OAuthProvidersSchema instead of literal union types for provider IDs. Refactored state initialization and helper methods accordingly.
Frontend OAuth dialog
frontend/src/features/auth/components/OAuthConfigDialog.tsx
Added sharedKeyProviders constant (typed as readonly OAuthProvidersSchema[]) to define providers supporting shared keys. Updated isSharedKeysAvailable to use the constant instead of hard-coded array.
Frontend provider icon rendering
frontend/src/features/auth/components/UsersDataGrid.tsx
Added switch case for 'microsoft' provider in ProviderIcon component with appropriate label and styling.
Frontend OAuth hook
frontend/src/features/auth/hooks/useOAuthConfig.ts
Updated selectedProvider state type from string | null to OAuthProvidersSchema | null. Updated helper callback signatures (isProviderConfigured, getProviderConfig) to accept OAuthProvidersSchema.
Shared schemas
shared-schemas/src/auth.schema.ts
Updated OAuthConfigSchema to include id (UUID), createdAt, and updatedAt fields. Changed provider field from string to oAuthProvidersSchema enum.
Request schemas
shared-schemas/src/auth-api.schema.ts
Updated createOAuthConfigRequestSchema to omit timestamp fields before extension. Updated updateOAuthConfigRequestSchema to omit timestamp and provider fields, then apply .partial() instead of explicit omission.

Sequence Diagram

sequenceDiagram
    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
Loading

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

  • tonychang04

Poem

🐰 Six providers once stood tall and lone,
Now unified through schemas, neatly sewn!
Generic routes dispatch with flair so bright,
OAuth flows consolidated into light ✨
LinkedIn, Microsoft join the harmonious song,
One schema to rule them, the refactor's so strong!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "[Feature] OAuth Refactor" directly and accurately reflects the primary objective of this pull request. The changeset demonstrates a comprehensive refactoring of the OAuth system across backend and frontend codebases, introducing a generic provider-based OAuth flow, consolidating provider-specific endpoints, renaming methods, updating schemas to use OAuthProvidersSchema, and extending support for multiple providers. The PR objectives explicitly state "Refactor OAuth Login system into a more maintainable manner," which aligns precisely with the title. The title is concise, uses appropriate naming conventions with the [Feature] prefix, and is specific enough to convey meaningful information without attempting to enumerate individual changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch oauth-refactor-fix

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7059efa and c77825c.

📒 Files selected for processing (3)
  • backend/src/core/auth/auth.ts (13 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{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/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/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper database transaction handling

Files:

  • backend/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/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/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (5)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-441)
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)
🔇 Additional comments (4)
backend/src/core/auth/auth.ts (4)

20-20: LGTM - Imports support unified OAuth architecture.

The new imports provide type safety (OAuthProvidersSchema) and standardized error handling capabilities (AppError, ERROR_CODES) that align well with the refactoring objectives.

Also applies to: 35-36


456-456: LGTM - Consistent naming convention.

The URL generation methods have been consistently renamed to include "OAuth" (e.g., generateGoogleOAuthUrl), improving clarity and maintainability across all providers.

Also applies to: 508-508, 555-555, 832-832, 1017-1017, 1199-1199


1320-1365: LGTM - Clean dispatcher pattern for provider-agnostic OAuth handling.

The generic generateOAuthUrl and handleOAuthCallback methods provide a unified interface for OAuth operations across all providers. The switch statements are comprehensive and the default cases appropriately handle unsupported providers.


868-868: LGTM - Implementation details are correct.

The consistent use of getApiBaseUrl() utility, reasonable email fallback for Microsoft users, and updated LinkedIn issuer URL all appear correct and well-aligned with OAuth provider specifications.

Also applies to: 912-912, 1025-1025, 1095-1095, 1159-1159


Comment @coderabbitai help to get the list of available commands and usage tips.

@Fermionic-Lyu
Fermionic-Lyu marked this pull request as ready for review October 23, 2025 00:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the getApiBaseUrl() 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 OAuthProvidersSchema values 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:

  1. The payload validation is deferred to individual handlers, but could be validated at this entry point for consistency
  2. 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 string type assertions that are unnecessary since the guard conditions on lines 1448 and 1464 already ensure payload.code is 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

📥 Commits

Reviewing files that changed from the base of the PR and between b2e3dc7 and 7059efa.

⛔ Files ignored due to path filters (1)
  • package-lock.json is 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.ts
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/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.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/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.ts
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/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.ts
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/core/auth/oauth.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/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.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • frontend/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.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • frontend/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.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.ts
  • backend/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 OAuthProvidersSchema enables type-safe provider handling throughout the seeding logic.


68-79: LGTM! Refactored default OAuth config seeding.

The loop-based approach over defaultProviders reduces 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 envMappings array 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 OAuthProvidersSchema enables 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 (google, github, discord, linkedin, facebook) have shared key implementations in the backend with checks for config?.useSharedKey and 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 OAuthProvidersSchema enables type-safe provider handling in this hook.


16-16: LGTM! Strengthened type for selected provider.

Changing selectedProvider from string | null to OAuthProvidersSchema | null ensures only valid provider values can be selected at compile time.


86-96: LGTM! Type-safe helper functions.

The parameter type updates to OAuthProvidersSchema in isProviderConfigured and getProviderConfig ensure 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 generateXAuthUrl to generateXOAuthUrl improves naming consistency
  • Adding explicit async keyword and Promise<string> return type improves type safety

Also 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 mail field by providing a noreply email address, consistent with other OAuth providers in this file.


1159-1159: No action required—issuer URL is correct.

The issuer URL https://www.linkedin.com/oauth is the correct endpoint for LinkedIn OpenID Connect, matching LinkedIn's official OAuth documentation.

Comment thread .env.example Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread backend/src/core/auth/oauth.ts Resolved
Comment thread shared-schemas/src/auth-api.schema.ts Resolved
Comment thread shared-schemas/src/auth.schema.ts Resolved
@tonychang04

Copy link
Copy Markdown
Member
Screenshot 2025-10-23 at 15 57 18 for microsfot i got this. but other login works. (didn't test facebooko cuz i don't have account..

@Fermionic-Lyu

Copy link
Copy Markdown
Member Author

Screenshot 2025-10-23 at 15 57 18 for microsfot i got this. but other login works. (didn't test facebooko cuz i don't have account..

Yeah, big company oauth system is brutal. We will let developers figure it out if they really want to support microsoft login...Google is da best.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants