Skip to content

Conversation

@kanchn-https
Copy link

@kanchn-https kanchn-https commented Aug 1, 2025

#29 Related Issue


Description

Added GitHub OAuth authentication with enhanced login UI. Users can now sign in with their GitHub account or continue with email/password.

Features:

  • ✨ "Sign in with GitHub" button with official styling
  • 🔐 Complete OAuth flow integration
  • 🎨 Enhanced login UI with password toggle
  • 📱 Responsive design with dark/light theme support
  • 🔄 GitHub callback handling with loading states

How Has This Been Tested?

  • ✅ Tested GitHub OAuth flow end-to-end
  • ✅ Verified responsive design on desktop/mobile
  • ✅ Confirmed dark/light theme switching
  • ✅ Tested error handling and loading states

Type of Change

  • [>] New feature
  • [>] Code style update
  • [>] Documentation update

Summary by CodeRabbit

  • New Features

    • Added GitHub OAuth login, allowing users to sign in with their GitHub accounts.
    • Introduced a dedicated GitHub OAuth callback page with user feedback and automatic redirection.
    • Implemented password visibility toggle on the login form for easier password entry.
    • Enhanced login UI with a divider and improved button states for OAuth and email login.
  • Documentation

    • Added a comprehensive setup guide for GitHub OAuth integration, including environment configuration, deployment, and troubleshooting.
  • Bug Fixes

    • Improved login form state handling to clear messages before new login or OAuth attempts.

@netlify
Copy link

netlify bot commented Aug 1, 2025

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit dedf12e
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/688cc22ec7f6ef000801163c
😎 Deploy Preview https://deploy-preview-170--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 1, 2025

Walkthrough

This change introduces GitHub OAuth authentication to the application. It adds backend support for GitHub OAuth, updates the user model, implements a new OAuth callback route and handler, and enhances the frontend with OAuth login UI and logic. Comprehensive documentation for GitHub OAuth setup is also included.

Changes

Cohort / File(s) Change Summary
Documentation: GitHub OAuth Setup
GITHUB_OAUTH_SETUP.md
Added a detailed guide for configuring GitHub OAuth integration, including app registration, environment variables, deployment, and troubleshooting.
Backend: User Model Update
backend/models/User.js
Extended the User schema with GitHub OAuth fields (githubId, githubUsername, avatarUrl, timestamps), and added a pre-save hook for updatedAt.
Backend: OAuth Callback Route
backend/routes/auth.js
Added a new POST /github/callback route to handle GitHub OAuth, exchanging code for token, fetching user profile, and creating/updating users accordingly.
Frontend: Router Update
src/Routes/Router.tsx
Added route mapping for /auth/github/callback to the new GitHubCallback component.
Frontend: Auth Context
src/context/AuthContext.tsx
Introduced a new React authentication context to manage user state, authentication status, and related async actions across the app.
Frontend: GitHub OAuth Callback Handler
src/pages/GitHubCallback/GitHubCallback.tsx
Added a new component to process the OAuth callback, handle backend communication, display status, and redirect users.
Frontend: Login Page Enhancements
src/pages/Login/Login.tsx
Enhanced login UI with "Sign in with GitHub" button, loading states, password visibility toggle, and improved form feedback.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant GitHub

    User->>Frontend: Clicks "Sign in with GitHub"
    Frontend->>GitHub: Redirects to GitHub OAuth authorize URL
    GitHub->>User: Prompts for authorization
    User->>GitHub: Authorizes app
    GitHub->>Frontend: Redirects with ?code=...
    Frontend->>Frontend: GitHubCallback component extracts code
    Frontend->>Backend: POST /github/callback { code }
    Backend->>GitHub: Exchanges code for access token
    GitHub-->>Backend: Returns access token
    Backend->>GitHub: Fetches user profile & email
    GitHub-->>Backend: Returns user data
    Backend->>Backend: Create/update user in DB
    Backend-->>Frontend: Returns user info / success
    Frontend->>User: Displays status, redirects accordingly
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Assessment against linked issues

Objective Addressed Explanation
Implement "Sign In with GitHub" authentication flow (#29)
Add backend support for GitHub OAuth, including user model changes (#29)
Update frontend with GitHub OAuth login UI and callback handling (#29)
Provide documentation for GitHub OAuth setup (#29)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Suggested labels

gssoc2025, level2

Suggested reviewers

  • mehul-m-prajapati

Poem

A bunny hopped through code today,
Adding GitHub sign-in the OAuth way!
With tokens exchanged and users anew,
The login screen sparkles with something cool and true.
Docs in tow, the path is clear—
Now GitHub logins bring users near!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (4)
backend/models/User.js (1)

31-39: Consider using Mongoose's built-in timestamps option

Mongoose provides a built-in timestamps option that automatically manages createdAt and updatedAt fields, eliminating the need for manual implementation.

Remove the manual timestamp fields and the updatedAt pre-save hook (lines 56-60), then add the timestamps option to the schema:

 const UserSchema = new mongoose.Schema({
   // ... existing fields ...
-  // Timestamps
-  createdAt: {
-    type: Date,
-    default: Date.now,
-  },
-  updatedAt: {
-    type: Date,
-    default: Date.now,
-  },
-});
+}, {
+  timestamps: true
+});
src/pages/GitHubCallback/GitHubCallback.tsx (1)

56-59: Avoid using 'any' type for errors

Use 'unknown' type for better type safety when handling errors.

-} catch (error: any) {
+} catch (error) {
   setStatus('error');
-  setMessage(error.message || 'Failed to authenticate with GitHub');
+  setMessage(error instanceof Error ? error.message : 'Failed to authenticate with GitHub');
   setTimeout(() => navigate('/login'), 3000);
GITHUB_OAUTH_SETUP.md (2)

23-26: Add language specifiers to code blocks

Code blocks should have language specifiers for proper syntax highlighting.

Line 23:

-```
+```env

Line 29:

-```
+```env

Also applies to: 29-36


65-66: Format bare URLs as proper links

Use proper Markdown link syntax for better readability.

-   - Frontend: http://localhost:5174
-   - Backend: http://localhost:5000
+   - Frontend: <http://localhost:5174>
+   - Backend: <http://localhost:5000>

-1. Go to http://localhost:5174/login
+1. Go to <http://localhost:5174/login>

Also applies to: 70-70

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f47b7c and 7121440.

📒 Files selected for processing (7)
  • GITHUB_OAUTH_SETUP.md (1 hunks)
  • backend/models/User.js (2 hunks)
  • backend/routes/auth.js (1 hunks)
  • src/Routes/Router.tsx (2 hunks)
  • src/context/AuthContext.tsx (1 hunks)
  • src/pages/GitHubCallback/GitHubCallback.tsx (1 hunks)
  • src/pages/Login/Login.tsx (7 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
GITHUB_OAUTH_SETUP.md

23-23: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


29-29: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


65-65: Bare URL used

(MD034, no-bare-urls)


66-66: Bare URL used

(MD034, no-bare-urls)


70-70: Bare URL used

(MD034, no-bare-urls)

🔇 Additional comments (18)
src/Routes/Router.tsx (1)

9-9: LGTM!

The GitHub OAuth callback route is correctly implemented and placed.

Also applies to: 19-19

backend/routes/auth.js (1)

110-125: LGTM!

Session establishment and user data response are properly implemented.

src/pages/Login/Login.tsx (7)

6-6: LGTM!

The new icon imports are correctly added and used appropriately throughout the component for the enhanced UI features.


19-20: LGTM!

The new state variables are properly typed and serve clear purposes for the password visibility toggle and GitHub loading state management.


34-34: Good UX improvement!

Clearing the message state before login attempts ensures old error messages don't persist, providing better user feedback.


109-121: LGTM!

The GitHub sign-in button is well-implemented with proper loading states, disabled handling, theme support, and appropriate styling consistent with GitHub's branding guidelines.


123-133: LGTM!

The divider implementation follows standard UI patterns for separating authentication methods and properly supports both light and dark themes.


155-155: LGTM!

The password visibility toggle is well-implemented with proper state management, appropriate icons, good positioning, and consistent theming. This enhances user experience significantly.

Also applies to: 162-162, 168-178


184-196: LGTM!

The enhanced submit button provides excellent user feedback with proper loading states, spinner animation, and icon usage. The implementation is clean and user-friendly.

src/context/AuthContext.tsx (9)

4-18: LGTM!

The interface definitions are comprehensive and well-typed. The User interface captures essential user data, and AuthContextType provides a complete authentication API with proper TypeScript typing.


20-28: LGTM!

The context creation and useAuth hook follow React best practices with proper TypeScript typing and error handling to ensure the hook is used within the provider.


30-32: LGTM!

The AuthProviderProps interface is correctly defined with proper ReactNode typing for the children prop.


34-38: LGTM!

The component setup is well-structured with appropriate initial state values and proper environment variable handling with a sensible fallback.


40-56: LGTM!

The checkAuthStatus method is well-implemented with proper error handling, credential inclusion, and ensures the loading state is always updated in the finally block.


58-74: LGTM!

The login method is well-implemented with proper credential handling, specific success message checking, state updates, and useful boolean return value for caller feedback.


76-88: Verify the intended signup flow.

The signup method doesn't set the user state upon successful registration, unlike the login method. This means users will still appear as unauthenticated after signup.

Is this the intended behavior? Should users be automatically logged in after successful signup, or is a separate login required? If auto-login is intended, consider updating the user state similar to the login method.


90-100: LGTM!

The logout method correctly clears the user state regardless of API response, ensuring the local authentication state is properly reset. The error handling is appropriate.


102-121: LGTM!

The useEffect properly initializes authentication status on mount, and the context value object correctly implements the AuthContextType interface with all required properties and methods.

Comment on lines 98 to 100
// Set a random password since GitHub users don't have passwords
password: Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-10)
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use cryptographically secure random password generation

Math.random() is not cryptographically secure. Use Node.js crypto module for generating secure random passwords.

+const crypto = require('crypto');
+
 // ... in the user creation block ...
-password: Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-10)
+password: crypto.randomBytes(32).toString('hex')

Consider making the password field optional in the schema for OAuth users to avoid storing unnecessary data.

🤖 Prompt for AI Agents
In backend/routes/auth.js around lines 98 to 100, replace the use of
Math.random() for password generation with the Node.js crypto module's secure
random byte generation to create a cryptographically secure password.
Additionally, update the user schema to make the password field optional for
OAuth users to avoid storing unnecessary password data.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (5)
backend/routes/auth.js (3)

40-53: Timeout implementation looks good.

The addition of AbortSignal.timeout(10000) addresses the previous concern about hanging requests. The timeout configuration is appropriate for OAuth token exchange.


55-64: Error handling improvements implemented correctly.

The response status check before JSON parsing and generic error messages address the previous security and reliability concerns.


107-107: Security issue: Use cryptographically secure random password generation.

Math.random() is not cryptographically secure and should be replaced with Node.js crypto module for generating secure random passwords.

Apply this diff to use secure random generation:

+const crypto = require('crypto');
+
 // ... in the user creation block ...
-password: Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-10)
+password: crypto.randomBytes(32).toString('hex')

Consider making the password field optional in the User schema for OAuth users to avoid storing unnecessary data.

src/pages/Login/Login.tsx (2)

50-69: Excellent GitHub OAuth implementation.

All previous concerns have been addressed:

  • Environment variable validation prevents unsafe fallbacks
  • Correct OAuth scope (user:email) limits permissions appropriately
  • Proper error handling without dead code in finally block
  • Clean redirect implementation

218-223: Proper React Router navigation implementation.

The Link component usage correctly enables client-side navigation instead of full page reloads, addressing the previous concern about SPA navigation.

🧹 Nitpick comments (1)
backend/routes/auth.js (1)

100-116: Consider optimizing user creation/update logic.

The current approach creates users with unnecessary password data for OAuth users. Consider making the password field optional or using a different approach for OAuth-only users.

 if (!user) {
   // Create new user with GitHub data
   user = new User({
     username: userData.login,
     email: primaryEmail,
     githubId: userData.id.toString(),
     githubUsername: userData.login,
     avatarUrl: userData.avatar_url,
-    // Set a random password since GitHub users don't have passwords
-    password: crypto.randomBytes(32).toString('hex')
+    // OAuth users don't need passwords
+    isOAuthUser: true
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7121440 and 736b193.

📒 Files selected for processing (4)
  • backend/models/User.js (2 hunks)
  • backend/routes/auth.js (1 hunks)
  • src/pages/GitHubCallback/GitHubCallback.tsx (1 hunks)
  • src/pages/Login/Login.tsx (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/models/User.js
  • src/pages/GitHubCallback/GitHubCallback.tsx
🔇 Additional comments (10)
backend/routes/auth.js (4)

30-36: LGTM! Good input validation.

The route correctly validates the required authorization code parameter and returns appropriate error responses.


69-93: Well-structured API calls with proper timeout handling.

The GitHub API calls for user data and emails are properly implemented with timeouts and error handling. The email selection logic correctly prioritizes primary email with fallback to public email.


118-133: Session management implementation is correct.

The use of req.login to establish the user session and the structured response with user data are properly implemented.


135-139: Good error handling and logging.

The catch block properly logs errors and returns appropriate error responses without exposing sensitive information.

src/pages/Login/Login.tsx (6)

1-6: Good import organization and icon usage.

The imports are well-organized and include the necessary React Router components and icons for the enhanced UI features.


19-20: Proper state management for new features.

The addition of showPassword and isGitHubLoading state variables appropriately supports the new password visibility toggle and GitHub OAuth loading states.


113-124: Well-designed GitHub sign-in button.

The button implementation includes proper loading states, accessibility considerations with disabled state, and follows GitHub's styling guidelines with the GitHub icon.


126-136: Excellent visual separation with divider.

The divider between GitHub OAuth and email/password login provides clear visual separation and improves user experience. The theme-aware styling is consistent with the rest of the component.


158-181: Great password visibility toggle implementation.

The password field enhancement with show/hide functionality improves user experience. The implementation correctly:

  • Uses conditional input type based on state
  • Provides proper button styling with hover effects
  • Uses appropriate icons for visual feedback
  • Adjusts padding to accommodate the toggle button

187-200: Enhanced submit button with loading states.

The submit button improvements with spinner animation and arrow icon provide excellent user feedback during form submission.

@mehul-m-prajapati
Copy link
Collaborator

mehul-m-prajapati commented Aug 1, 2025

@kanchn-https : cannot accept big changes in one commit.. Please split your commits into small changes.

https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/routes/auth.js (1)

96-117: Consider username preservation for existing users.

The user creation/update logic is well-implemented with secure password generation. However, consider whether existing users should have their username preserved when linking GitHub accounts, as the current implementation overwrites the original username with the GitHub login.

If username preservation is desired:

        } else {
            // Update existing user with GitHub info
            user.githubId = userData.id.toString(); // Convert to string
-           user.githubUsername = userData.login;
+           user.githubUsername = userData.login;
+           // Preserve original username unless it's empty
+           if (!user.username) {
+               user.username = userData.login;
+           }
            user.avatarUrl = userData.avatar_url;
            await user.save();
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 736b193 and dedf12e.

📒 Files selected for processing (1)
  • backend/routes/auth.js (2 hunks)
🔇 Additional comments (6)
backend/routes/auth.js (6)

4-4: LGTM! Good security practices.

The crypto import for secure random password generation and the basic validation of the authorization code parameter follow security best practices.

Also applies to: 31-37


39-67: LGTM! Previous feedback addressed.

The token exchange implementation properly handles timeouts, response status checking, and error handling as requested in previous reviews. The use of environment variables for sensitive data is appropriate.


69-82: LGTM! Consistent API handling.

The user data fetching follows the same robust pattern as the token exchange with proper authentication, timeout handling, and status checking.


84-95: LGTM! Good fallback strategy for email handling.

The email fetching logic properly handles the case where users may have multiple emails and appropriately falls back to the public email when a primary email isn't found.


119-134: LGTM! Proper session handling and user data response.

The login logic correctly establishes the user session and returns appropriate user data without exposing sensitive information.


136-140: LGTM! Appropriate error handling.

The error handling properly logs errors for debugging while returning generic error messages to prevent information leakage.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🚀 Feature: Add "Sign In with GitHub"

2 participants