Repository navigation
feat: added facebook oauth provider - #445
Conversation
WalkthroughAdds Facebook OAuth end-to-end: backend route to initiate flow, AuthService methods to generate/exchange tokens and fetch FB user info, default Facebook scopes, a Facebook user type, and frontend UI updates to expose Facebook as an OAuth provider. (49 words) Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant FE as Frontend
participant BE as Backend
participant FB as Facebook
participant DB as Database
Note over FE,BE: Start Facebook OAuth flow
User->>FE: Click "Add Facebook OAuth"
FE->>BE: GET /api/auth/oauth/facebook?redirect_uri=...
BE->>BE: validate redirect_uri, create signed state JWT
BE-->>FE: return Facebook auth URL
FE->>FB: Redirect user to Facebook auth (with state)
FB->>User: Prompt login & consent
FB-->>FE: Redirect back with code & state
FE->>BE: GET /api/auth/oauth/facebook/callback?code=...&state=...
BE->>BE: verify state JWT
BE->>FB: Exchange code for access token
FB-->>BE: access token
BE->>FB: GET /me?fields=...&access_token=...
FB-->>BE: FacebookUserInfo
BE->>DB: findOrCreate user, create session
DB-->>BE: user/session record
BE-->>FE: success / session created
FE->>User: Show success / logged-in state
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (4)
frontend/src/features/auth/components/AddOAuthDialog.tsx (1)
17-19: Deduplicate provider ID unions by referencing OAuthProviderInfo['id'].Prevents drift across files and simplifies maintenance.
Add near the top (outside the shown ranges):
type ProviderId = OAuthProviderInfo['id'];Apply diffs:
- onConfirm: (selectedId: 'google' | 'github' | 'facebook') => void; - enabledProviders: Record<'google' | 'github' | 'facebook', boolean>; + onConfirm: (selectedId: ProviderId) => void; + enabledProviders: Record<ProviderId, boolean>;- const [selectedId, setSelectedId] = useState<'google' | 'github' | 'facebook' | null>(null); + const [selectedId, setSelectedId] = useState<ProviderId | null>(null);- const selectProvider = (id: 'google' | 'github' | 'facebook') => { + const selectProvider = (id: ProviderId) => {Also applies to: 28-28, 42-42
backend/src/core/auth/auth.ts (3)
794-810: Align shared-key flow with existing providers and add error handlingUse fetch + ok check (as in Google/GitHub) and log failures.
Apply this diff:
- const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; - const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; - const response = await axios.get( - `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, - { - headers: { - 'Content-Type': 'application/json', - }, - } - ); - return response.data.auth_url || response.data.url || ''; + const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; + const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; + const authUrl = await fetch( + `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, + { + method: 'GET', + headers: { 'Content-Type': 'application/json' }, + } + ); + if (!authUrl.ok) { + logger.error('Failed to fetch Facebook auth URL', { + status: authUrl.status, + statusText: authUrl.statusText, + }); + throw new Error(`Failed to fetch Facebook auth URL: ${authUrl.statusText}`); + } + const responseData = (await authUrl.json()) as { auth_url?: string; url?: string }; + return responseData.auth_url || responseData.url || '';
842-851: Validate presence of clientSecret before token exchangeAvoid opaque Graph API errors; fail fast with a clear message.
Apply this diff:
- const clientSecret = await oauthConfigService.getClientSecretByProvider('facebook'); + const clientSecret = await oauthConfigService.getClientSecretByProvider('facebook'); + if (!clientSecret) { + throw new Error('Facebook Client Secret not configured'); + }
863-872: Ensure avatar URL reliability from Graph APIRequest picture URL explicitly; current fields may not always include a URL.
Apply this diff:
- const response = await axios.get('https://graph.facebook.com/v18.0/me', { + const response = await axios.get('https://graph.facebook.com/v18.0/me', { params: { - fields: 'id,email,name,first_name,last_name,picture', + fields: 'id,email,name,first_name,last_name,picture.type(large)', access_token: accessToken, }, });Note: Facebook may omit email if permission not granted. See follow-up fix below in findOrCreateFacebookUser. Also consider making
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
frontend/src/assets/logos/facebook.svgis excluded by!**/*.svg
📒 Files selected for processing (6)
backend/src/api/routes/auth.oauth.ts(3 hunks)backend/src/core/auth/auth.ts(4 hunks)backend/src/core/auth/oauth.ts(1 hunks)backend/src/types/auth.ts(1 hunks)frontend/src/features/auth/components/AddOAuthDialog.tsx(3 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(5 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/types/auth.tsbackend/src/core/auth/oauth.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
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/types/auth.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/types/auth.tsbackend/src/core/auth/oauth.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
**/[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/types/auth.tsbackend/src/core/auth/oauth.tsbackend/src/api/routes/auth.oauth.tsbackend/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/oauth.tsbackend/src/core/auth/auth.ts
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
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/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (3)
GoogleUserInfo(66-75)GitHubUserInfo(77-83)FacebookUserInfo(92-103)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-400)backend/src/utils/environment.ts (1)
getApiBaseUrl(41-43)
🪛 GitHub Actions: Lint and Format Check
backend/src/core/auth/auth.ts
[error] 285-285: Prettier formatting issue: Replace multi-line union with a single line. Example: Replace ⏎······|·GoogleUserInfo⏎······|·GitHubUserInfo⏎······|·FacebookUserInfo⏎····· with ·GoogleUserInfo·|·GitHubUserInfo·|·FacebookUserInfo.
🪛 GitHub Check: lint-and-format
backend/src/core/auth/auth.ts
[failure] 285-285:
Replace ⏎······|·GoogleUserInfo⏎······|·GitHubUserInfo⏎······|·FacebookUserInfo⏎····· with ·GoogleUserInfo·|·GitHubUserInfo·|·FacebookUserInfo
[failure] 368-368:
Replace ⏎······|·GoogleUserInfo⏎······|·GitHubUserInfo⏎······|·FacebookUserInfo⏎····· with ·GoogleUserInfo·|·GitHubUserInfo·|·FacebookUserInfo
frontend/src/features/auth/components/AuthMethodTab.tsx
[failure] 71-71:
Replace providerId:·'google'·|·'github'·|·'facebook',·providerName:·string with ⏎····providerId:·'google'·|·'github'·|·'facebook',⏎····providerName:·string⏎··
🔇 Additional comments (8)
backend/src/core/auth/oauth.ts (1)
185-186: Default Facebook scopes look good.backend/src/api/routes/auth.oauth.ts (1)
229-237: Verify redirectUri usage in Facebook token exchange.Facebook’s token exchange typically requires the same redirect_uri. Ensure exchangeFacebookCodeForToken uses the correct redirectUri; pass it if needed.
- const accessToken = await authService.exchangeFacebookCodeForToken(code as string); + // If service requires redirectUri to match FB app config: + const accessToken = await authService.exchangeFacebookCodeForToken( + code as string, + redirectUri + );frontend/src/features/auth/components/AuthMethodTab.tsx (5)
6-6: Facebook logo import looks good.
35-41: Facebook provider entry added correctly.
45-45: Provider ID union updated appropriately.
106-106: Enabled providers updated with Facebook — looks good.
115-115: Selection handler updated to include Facebook — looks good.backend/src/core/auth/auth.ts (1)
22-28: LGTM: imported FacebookUserInfo correctlyImport and type usage align with new provider support.
| export interface FacebookUserInfo { | ||
| id: string; | ||
| email: string; | ||
| name?: string; | ||
| picture?: { | ||
| data?: { | ||
| url?: string; | ||
| }; | ||
| }; | ||
| first_name?: string; | ||
| last_name?: string; | ||
| } |
There was a problem hiding this comment.
Make email optional in FacebookUserInfo (email may be absent even with scope).
Facebook often omits email (no email set, unverified, or permission denied). Treating it as required can break user creation flows and DB constraints.
export interface FacebookUserInfo {
id: string;
- email: string;
+ email?: string;
name?: string;
picture?: {
data?: {
url?: string;
};
};
first_name?: string;
last_name?: string;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export interface FacebookUserInfo { | |
| id: string; | |
| email: string; | |
| name?: string; | |
| picture?: { | |
| data?: { | |
| url?: string; | |
| }; | |
| }; | |
| first_name?: string; | |
| last_name?: string; | |
| } | |
| export interface FacebookUserInfo { | |
| id: string; | |
| email?: string; | |
| name?: string; | |
| picture?: { | |
| data?: { | |
| url?: string; | |
| }; | |
| }; | |
| first_name?: string; | |
| last_name?: string; | |
| } |
🤖 Prompt for AI Agents
In backend/src/types/auth.ts around lines 92 to 103, the FacebookUserInfo type
incorrectly requires email; make email optional (email?: string) so code
handling Facebook responses and user creation won't assume an email is always
present; update the interface declaration and then run a quick type-check to
find and adjust any call sites or database mapping that assumed a non-null
email.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
71-74: LGTM!The parameter formatting issue from the previous review has been correctly addressed by breaking the parameters across multiple lines. The function signature properly includes 'facebook' in the providerId union type.
backend/src/core/auth/auth.ts (1)
869-883: Critical: handle missing Facebook email to avoid runtime crash.The code at Line 872 calls
facebookUserInfo.email.split('@')which will throw if email is missing. Facebook OAuth doesn't guarantee the email field if users deny the email permission. This is a critical bug that was flagged in previous review comments.Apply this diff:
async findOrCreateFacebookUser( facebookUserInfo: FacebookUserInfo ): Promise<CreateSessionResponse> { - const userName = facebookUserInfo.name || facebookUserInfo.email.split('@')[0]; - const avatarUrl = facebookUserInfo.picture?.data?.url || ''; - - return this.findOrCreateThirdPartyUser( - 'facebook', - facebookUserInfo.id, - facebookUserInfo.email, - userName, - avatarUrl, - facebookUserInfo - ); + const fallbackEmail = `${facebookUserInfo.id}@users.facebook.com`; + const email = facebookUserInfo.email || fallbackEmail; + const userName = + facebookUserInfo.name || + (facebookUserInfo.email ? facebookUserInfo.email.split('@')[0] : `fb_${facebookUserInfo.id}`); + const avatarUrl = facebookUserInfo.picture?.data?.url || ''; + + return this.findOrCreateThirdPartyUser( + 'facebook', + facebookUserInfo.id, + email, + userName, + avatarUrl, + facebookUserInfo + ); }
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
855-864: Add error handling and response validation.The method lacks error handling for the
axios.getrequest and doesn't validate the response structure. Consider adding try-catch and logging, similar to other OAuth methods.Apply this diff:
async getFacebookUserInfo(accessToken: string): Promise<FacebookUserInfo> { - const response = await axios.get('https://graph.facebook.com/v18.0/me', { - params: { - fields: 'id,email,name,first_name,last_name,picture', - access_token: accessToken, - }, - }); - - return response.data; + try { + const response = await axios.get('https://graph.facebook.com/v18.0/me', { + params: { + fields: 'id,email,name,first_name,last_name,picture', + access_token: accessToken, + }, + }); + + if (!response.data.id) { + throw new Error('Invalid Facebook user info response'); + } + + return response.data; + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + logger.error('Facebook user info fetch failed', { + status: error.response.status, + error: error.response.data, + }); + throw new Error(`Facebook user info error: ${JSON.stringify(error.response.data)}`); + } + throw error; + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/core/auth/auth.ts(4 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(5 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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:
frontend/src/features/auth/components/AuthMethodTab.tsxbackend/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/AuthMethodTab.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/AuthMethodTab.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/AuthMethodTab.tsx
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
frontend/src/features/auth/components/AuthMethodTab.tsxbackend/src/core/auth/auth.ts
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/AuthMethodTab.tsx
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
**/[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 (3)
backend/src/types/auth.ts (3)
GoogleUserInfo(66-75)GitHubUserInfo(77-83)FacebookUserInfo(92-103)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-400)backend/src/utils/environment.ts (1)
getApiBaseUrl(41-43)
🔇 Additional comments (9)
frontend/src/features/auth/components/AuthMethodTab.tsx (5)
6-6: LGTM!The Facebook logo import follows the same pattern as the existing Google and GitHub imports.
35-41: LGTM!The Facebook provider configuration is complete and follows the same structure as Google and GitHub, with an appropriate setup URL pointing to the Facebook Developer console.
45-45: LGTM!The type definition correctly includes 'facebook' in the union type, maintaining type safety across the component.
109-109: LGTM!The
enabledProvidersobject correctly includes Facebook, maintaining consistency with the Google and GitHub provider tracking.
118-118: LGTM!The function signature correctly includes 'facebook' in the selectedId parameter type, ensuring type safety throughout the OAuth provider selection flow.
backend/src/core/auth/auth.ts (4)
22-28: LGTM!The import additions correctly include
FacebookUserInfoalongside the existing OAuth user info types, following the established pattern.
285-285: LGTM!The union type correctly includes
FacebookUserInfoand is properly formatted on a single line.
364-364: LGTM!The union type correctly includes
FacebookUserInfofor the private method signature, maintaining consistency with the public method.
808-808: Verify Facebook Graph API version
Confirm via the official changelog (https://developers.facebook.com/docs/graph-api/changelog/) that v18.0 remains supported; if it’s deprecated, update the URL to the current stable version.
| const response = await axios.get( | ||
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| } | ||
| ); | ||
| return response.data.auth_url || response.data.url || ''; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Add error handling for the shared key flow.
The axios.get call lacks error handling. If the request fails, it could throw an unhandled error. Consider wrapping this in a try-catch block and providing a meaningful error message, following the pattern used in generateGoogleAuthUrl (lines 454-472).
Apply this diff:
- const response = await axios.get(
- `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`,
- {
- headers: {
- 'Content-Type': 'application/json',
- },
- }
- );
- return response.data.auth_url || response.data.url || '';
+ try {
+ const response = await axios.get(
+ `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`,
+ {
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ }
+ );
+ if (response.status !== 200) {
+ logger.error('Failed to fetch Facebook auth URL:', {
+ status: response.status,
+ statusText: response.statusText,
+ });
+ throw new Error(`Failed to fetch Facebook auth URL: ${response.statusText}`);
+ }
+ return response.data.auth_url || response.data.url || '';
+ } catch (error) {
+ logger.error('Facebook shared auth URL request failed:', error);
+ throw new Error('Failed to fetch Facebook auth URL from cloud service');
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const response = await axios.get( | |
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| } | |
| ); | |
| return response.data.auth_url || response.data.url || ''; | |
| try { | |
| const response = await axios.get( | |
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| } | |
| ); | |
| if (response.status !== 200) { | |
| logger.error('Failed to fetch Facebook auth URL:', { | |
| status: response.status, | |
| statusText: response.statusText, | |
| }); | |
| throw new Error(`Failed to fetch Facebook auth URL: ${response.statusText}`); | |
| } | |
| return response.data.auth_url || response.data.url || ''; | |
| } catch (error) { | |
| logger.error('Facebook shared auth URL request failed:', error); | |
| throw new Error('Failed to fetch Facebook auth URL from cloud service'); | |
| } |
🤖 Prompt for AI Agents
In backend/src/core/auth/auth.ts around lines 793 to 801, the axios.get call for
the Facebook shared key flow has no error handling; wrap the request in a
try-catch similar to generateGoogleAuthUrl (lines 454-472), catch any error,
include the error details in a clear error message (e.g., "Failed to generate
Facebook shared auth URL" plus error.message or response data), and either log
it and return an empty string fallback or rethrow a new Error with that message
to preserve calling behavior; ensure you preserve the existing return of
response.data.auth_url || response.data.url || '' when successful.
0e9bdd8 to
b0045af
Compare
|
@tonychang04 pls review |
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
The changes looks good in general, just a few comments here:
- facebook api v18 seems very outdated. Can you change it to the latest stable version?
- The shared callback route for facebook is missing
Do you mind addressing these and provide a video for the whole auth flow? i.e. a simple app or just a html file that calls for facebook login, then correctly create an insforge user with facebook as provider after authentication
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (4)
backend/src/api/routes/auth.oauth.ts (1)
25-55: Hardcoded JWT secret fallback remains unaddressed (applies to all OAuth routes).The Facebook OAuth route uses
process.env.JWT_SECRET || 'default_secret'on line 38, which was flagged in a previous review. This same insecure pattern is duplicated across all OAuth initialization routes (Google line 70, GitHub line 102, Discord line 135, LinkedIn line 168).As noted in the previous review, require
JWT_SECRETto be set and fail fast when missing.backend/src/core/auth/auth.ts (3)
1101-1109: Missing error handling for shared key request remains unaddressed.The
axios.getcall for the Facebook shared key flow lacks error handling, which was flagged in a previous review. If the cloud service request fails, it will throw an unhandled error.As noted in the previous review, wrap the request in a try-catch block and provide a meaningful error message, following the pattern used in
generateDiscordAuthUrl(lines 567-584).
1134-1158: Missing error handling for token exchange remains unaddressed.The
exchangeFacebookCodeForTokenmethod lacks error handling for theaxios.getrequest, which was flagged in a previous review. This is inconsistent withexchangeCodeToTokenByGoogle(lines 626-675), which includes comprehensive error handling.As noted in the previous review, wrap the token exchange in a try-catch block, detect Axios errors, log appropriately, and throw a clear error message with HTTP status and response data when the exchange fails.
1177-1192: Verify and implement the suggested deterministic email fallback for missing Facebook emails.Based on code inspection, the concern is valid. The
findOrCreateThirdPartyUsermethod at line 325 executesSELECT * FROM _accounts WHERE email = ?, and if no user exists, line 334 callscreateThirdPartyUserwhich INSERTs the email into the database. Passing an empty string creates inconsistency with other OAuth providers and risks database constraint violations.Compare these implementations:
- GitHub (line 814):
const email = githubUserInfo.email || \${githubUserInfo.login}@users.noreply.github.com`;`- Discord (line 887):
const email = discordUserInfo.email || \${discordUserInfo.id}@users.noreply.discord.local`;`- Facebook (line 1180):
const email = facebookUserInfo.email || '';← inconsistentApply the suggested fix to align with the established pattern:
- const email = facebookUserInfo.email || ''; + const email = facebookUserInfo.email || `${facebookUserInfo.id}@users.facebook.com`;
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
1163-1172: Consider adding error handling for Facebook user info request.The method lacks error handling for the Facebook Graph API call. While this pattern is consistent with similar methods like
getGitHubUserInfoandgetDiscordUserInfo, adding a try-catch block would improve reliability and provide clearer error messages when Facebook API calls fail.Apply this diff to add error handling:
async getFacebookUserInfo(accessToken: string): Promise<FacebookUserInfo> { - const response = await axios.get('https://graph.facebook.com/v21.0/me', { - params: { - fields: 'id,email,name,first_name,last_name,picture', - access_token: accessToken, - }, - }); - - return response.data; + try { + const response = await axios.get('https://graph.facebook.com/v21.0/me', { + params: { + fields: 'id,email,name,first_name,last_name,picture', + access_token: accessToken, + }, + }); + + return response.data; + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + logger.error('Facebook user info request failed', { + status: error.response.status, + error: error.response.data, + }); + throw new Error(`Failed to fetch Facebook user info: ${JSON.stringify(error.response.data)}`); + } + throw error; + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/api/routes/auth.oauth.ts(4 hunks)backend/src/core/auth/auth.ts(4 hunks)backend/src/core/auth/oauth.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{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/api/routes/auth.oauth.tsbackend/src/core/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/api/routes/auth.oauth.tsbackend/src/core/auth/oauth.tsbackend/src/core/auth/auth.ts
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
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/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/api/routes/auth.oauth.tsbackend/src/core/auth/oauth.tsbackend/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/oauth.tsbackend/src/core/auth/auth.ts
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (1)
FacebookUserInfo(110-121)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-404)backend/src/utils/environment.ts (1)
getApiBaseUrl(41-43)
🪛 GitHub Actions: Lint and Format Check
backend/src/core/auth/auth.ts
[error] 1181-1181: prettier/prettier: Replace facebookUserInfo.name || facebookUserInfo.first_name || with a multiline version.
🪛 GitHub Check: lint-and-format
backend/src/core/auth/auth.ts
[failure] 1181-1181:
Replace ·facebookUserInfo.name·||·facebookUserInfo.first_name·|| with ⏎······facebookUserInfo.name·||⏎······facebookUserInfo.first_name·||⏎·····
🔇 Additional comments (7)
backend/src/api/routes/auth.oauth.ts (4)
213-213: LGTM!Provider validation correctly updated to include Facebook alongside existing providers.
270-278: LGTM!Facebook payload handling correctly maps provider data to the
FacebookUserInfostructure and follows the same pattern as other OAuth providers.
316-316: LGTM!Provider validation correctly includes Facebook in the provider-specific callback.
322-329: LGTM!Facebook OAuth callback correctly implements the authorization code flow, following the same pattern as GitHub and Discord.
backend/src/core/auth/auth.ts (3)
23-23: LGTM!Import statement correctly adds
FacebookUserInfotype.
287-292: LGTM!The
identityDataparameter correctly includesFacebookUserInfoin the union type, extending OAuth support to Facebook.
372-377: LGTM!The private
createThirdPartyUsermethod correctly includesFacebookUserInfoin the union type, maintaining consistency with the public API.
cf7f5f0 to
600fbbd
Compare
600fbbd to
c05e68f
Compare
|
@Fermionic-Lyu created a video for demo and made all the requested changes Screen.Recording.2025-10-20.at.1.mp4 |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
backend/src/core/auth/auth.ts (2)
1081-1129: Implementation follows established patterns.The Facebook auth URL generation correctly follows the pattern established by Google, GitHub, and Discord providers. The use of comma-separated scopes (line 1122) is appropriate for Facebook's API requirements.
Note: The shared key flow (lines 1101-1109) still lacks error handling as flagged in a previous review.
1134-1158: Note: Missing error handling already flagged.The token exchange implementation lacks error handling around the axios call, which was identified in a previous review. This remains unaddressed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
backend/src/core/auth/auth.ts(4 hunks)
🧰 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 (4)
backend/src/types/auth.ts (1)
FacebookUserInfo(110-121)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-404)backend/src/utils/environment.ts (1)
getApiBaseUrl(41-43)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(185-185)
🔇 Additional comments (3)
backend/src/core/auth/auth.ts (3)
23-23: LGTM!The FacebookUserInfo import follows the established pattern for other OAuth providers.
287-293: LGTM!The union type extensions to include
FacebookUserInfoare consistent with the existing pattern, and the formatting issues from previous reviews have been resolved.Also applies to: 372-378
1163-1172: LGTM!The method correctly fetches Facebook user information with appropriate fields. The error handling pattern (letting errors bubble to the caller) is consistent with similar methods like
getGitHubUserInfoandgetDiscordUserInfo.
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
Changes LGTM in general, the only concern left is you removed the scope for email. I know the facebook app review is painful, and it's hard to test if email scope is included. The thing is we are using email as some sort of primary identifier for the user, so leaving it blank may be problematic and casue conflicts. If you don't have an approved facebook app to test with, that's fine, but you should keep the email scope. Developers who need facebook login should deal with these by themselves.
cc @tonychang04 to co-review this email issue
cfd8b36 to
05c4970
Compare
|
@Fermionic-Lyu that really makes sense , i reverted the scopes and added email again thanks for pointing it out , Cc: @tonychang04 |
|
Sry for mised msg. code itself LGTM lets test. Thanks @HarshSharma0801 for doing this! and @Fermionic-Lyu for reviewing!!! |
closes #383
Added Facebook OAuth support following the same pattern as Google/GitHub OAuth. Users can now configure Facebook authentication in the dashboard with shared keys or custom credentials.
Backend Changes:
auth.oauth.tsFacebookUserInfotype definition and default scopes (email, public_profile)Frontend Changes:
How did you test this change?
docker compose up_oauth_configstable with correct scopesSummary by CodeRabbit
New Features
Bug Fixes / Improvements