Skip to content

Conversation

@rixitgithub
Copy link
Contributor

@rixitgithub rixitgithub commented Jun 8, 2025

In this PR,
I fixed and added the following features

  • Added socials for user ( User will now be able to navigate to other's social profiles )
  • Made the charts data and eloHistory dynamic
  • Added filter to the eloRating chart
  • Made the page responsive

Closes Issue #87

Summary by CodeRabbit

  • New Features

    • Added support for linking and editing social media profiles (Twitter, Instagram, LinkedIn) in user profiles.
    • Introduced Elo rating filters and improved Elo trend chart with custom date range selection on the profile page.
    • Added a responsive and customizable calendar component and a popover UI component for enhanced date selection and popover interactions.
    • Included a new production configuration file for streamlined backend deployment.
  • Improvements

    • Enhanced profile editing experience with field-specific editing and auto-focus.
    • Improved error messages and response consistency in profile-related actions.
    • Updated leaderboard and debate history display for better clarity and responsiveness.
  • Dependencies

    • Added new frontend dependencies: @radix-ui/react-popover, date-fns, react-day-picker.
    • Upgraded @radix-ui/react-slot to a newer version.

@coderabbitai
Copy link

coderabbitai bot commented Jun 8, 2025

Walkthrough

The changes introduce support for social media fields in user profiles, Elo rating tracking, and enhanced profile data handling on both backend and frontend. Backend updates include new configuration options, JWT secret management, and expanded user and debate models. The frontend receives new UI components, profile editing improvements, Elo history filtering, and social media integration.

Changes

Files/Paths Change Summary
backend/cmd/server/main.go, backend/utils/auth.go JWT secret is now set via a setter function after DB connection; uses a package-level variable instead of environment lookup.
backend/config/config.go, backend/config/config.prod.yml Added YAML struct tags to config fields; introduced a production YAML config file with all environment-specific settings.
backend/models/user.go, backend/controllers/profile_controller.go, frontend/src/services/profileService.ts Added Twitter, Instagram, and LinkedIn fields to user profile; backend and frontend updated to support reading and updating these fields.
backend/models/debate.go, backend/controllers/profile_controller.go, frontend/src/Pages/Profile.tsx Added EloRating to Debate model; backend and frontend updated to record, aggregate, and visualize Elo rating history and stats.
frontend/package.json Added dependencies: @radix-ui/react-popover, date-fns, react-day-picker; upgraded @radix-ui/react-slot.
frontend/src/components/ui/calendar.tsx, frontend/src/components/ui/popover.tsx Introduced new reusable Calendar and Popover UI components for date picking and popover display.
frontend/src/Pages/Profile.tsx Major refactor: per-field editing, social media integration, Elo rating filters, improved charts, and responsive UI enhancements.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant DB

    User->>Frontend: Edit profile (displayName, bio, twitter, instagram, linkedin)
    Frontend->>Backend: PUT /user/updateprofile (with new fields)
    Backend->>DB: Update user document with new fields
    DB-->>Backend: Update result
    Backend-->>Frontend: Success or error response
    Frontend-->>User: Show updated profile with social links

    User->>Frontend: View profile page
    Frontend->>Backend: GET /user/profile
    Backend->>DB: Fetch user, debates, Elo history
    DB-->>Backend: User and debate data
    Backend-->>Frontend: Profile, stats, Elo history, social links
    Frontend-->>User: Display profile, Elo chart, debate history, social links
Loading

Possibly related issues

Poem

In the warren, profiles shine anew,
With Twitter, LinkedIn, and Insta in view.
Elo hops higher, tracked through the days,
Charts and popovers in dazzling arrays.
Rabbits code on, with carrots in sight—
Social and stats, all bundled just right!
🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 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

@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

🔭 Outside diff range comments (2)
backend/config/config.go (1)

39-46: ⚠️ Potential issue

Add missing YAML tags for SMTP configuration.

The SMTP struct and its fields are missing YAML tags, making this configuration section unparseable from YAML files.

-	SMTP struct { // Add SMTP configuration
-		Host        string
-		Port        int
-		Username    string // Gmail address
-		Password    string // App Password
-		SenderEmail string // Same as Username for Gmail
-		SenderName  string
-	}
+	SMTP struct { // Add SMTP configuration
+		Host        string `yaml:"host"`
+		Port        int    `yaml:"port"`
+		Username    string `yaml:"username"` // Gmail address
+		Password    string `yaml:"password"` // App Password
+		SenderEmail string `yaml:"senderEmail"` // Same as Username for Gmail
+		SenderName  string `yaml:"senderName"`
+	} `yaml:"smtp"`
backend/config/config.prod.yml (1)

1-44: 💡 Verification agent

🧩 Analysis chain

Critical security issue: Production config file with hardcoded placeholders.

This production configuration file contains placeholder values for sensitive credentials and could lead to serious security vulnerabilities:

  1. Accidental deployment: Placeholder values could be deployed to production
  2. Credential exposure: Config files with secrets shouldn't be in version control
  3. Security anti-pattern: Storing secrets in config files violates security best practices

Consider these alternatives:

  1. Use environment variables for secrets in production
  2. Create a config.prod.example.yml template file instead
  3. Use a secrets management system (HashiCorp Vault, AWS Secrets Manager, etc.)
  4. Add validation to ensure placeholder values aren't used in production
-# This file should be renamed to remove .prod and kept out of version control
+# This is a template file - copy to config.prod.yml and fill in real values
+# DO NOT commit config.prod.yml to version control

🏁 Script executed:

#!/bin/bash
# Check if there are any other config files that might contain secrets
fd -e yml -e yaml . | xargs grep -l "secret\|password\|key" | head -10

Length of output: 103


Prevent committing real secrets in config.prod.yml

The backend/config/config.prod.yml file currently contains placeholder secrets and is the only YAML file with sensitive keywords (secret, password, key). Storing even placeholders in a committed production config is risky.

• File to update:

  • backend/config/config.prod.yml

Please make the following changes:

-# backend/config/config.prod.yml
-# Production config with real credentials (do NOT commit)
+## backend/config/config.prod.example.yml
+# Template for production config. Copy to `config.prod.yml`, fill in real values, and add `config.prod.yml` to .gitignore.

 server:
   port: 1313

 database:
   uri: '<YOUR_MONGODB_URI>'

 gemini:
   apiKey: '<YOUR_GEMINI_API_KEY>'

 jwt:
   secret: '<YOUR_JWT_SECRET>'
   expiry: 1440

 smtp:
   host: 'smtp.gmail.com'
   port: 587
   username: '<YOUR_EMAIL_ADDRESS>'
   password: '<YOUR_EMAIL_PASSWORD_OR_APP_PASSWORD>'
   senderEmail: '<YOUR_EMAIL_ADDRESS>'
   senderName: 'DebateAI Team'

 googleOAuth:
   clientID: '<YOUR_GOOGLE_OAUTH_CLIENT_ID>'

Recommendations:

  1. Environment variables: Load secrets from process.env (or equivalent) in your code
  2. Secrets manager: Use Vault, AWS Secrets Manager, etc., for production credentials
  3. CI validation: Fail builds when placeholder values are detected
🧹 Nitpick comments (5)
backend/models/user.go (1)

17-19: LGTM! Consider adding validation for social media fields.

The social media field additions follow proper Go conventions and struct patterns. Consider adding validation for URL formats or handle constraints in the future.

backend/utils/auth.go (1)

25-29: Consider thread safety for JWT secret management.

The global variable approach for JWT secret storage could lead to race conditions if SetJWTSecret is called concurrently with JWT operations.

Consider adding synchronization:

+import "sync"

+var (
+	jwtSecret string
+	jwtMutex  sync.RWMutex
+)

 func SetJWTSecret(secret string) {
+	jwtMutex.Lock()
+	defer jwtMutex.Unlock()
 	jwtSecret = secret
 }
frontend/src/components/ui/calendar.tsx (1)

31-32: Consider using a more maintainable approach for RTL styles.

The use of String.raw with escaped backslashes for RTL styles is fragile and hard to read. Consider using a cleaner approach:

-        String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
-        String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
+        "rtl:[&_.rdp-button_next>svg]:rotate-180",
+        "rtl:[&_.rdp-button_previous>svg]:rotate-180",
backend/controllers/profile_controller.go (1)

74-75: Consider making the default display name configurable.

The hardcoded default name "Steve" should be configurable through environment variables or configuration:

-		displayName = "Steve"
+		displayName = os.Getenv("DEFAULT_DISPLAY_NAME")
+		if displayName == "" {
+			displayName = "Anonymous User"
+		}
frontend/src/Pages/Profile.tsx (1)

362-404: Consider extracting the Elo history filtering logic.

The filterEloHistory function is quite complex and would benefit from being extracted as a utility function for better testability and reusability:

// In a separate utils file:
export function filterEloHistory(
  eloHistory: Array<{elo: number; date: string}>,
  filter: "7days" | "30days" | "all" | "custom",
  customRange?: DateRange,
  currentElo?: number
) {
  // ... filtering logic here
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae592ec and f6c866b.

⛔ Files ignored due to path filters (1)
  • frontend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • backend/cmd/server/main.go (1 hunks)
  • backend/config/config.go (2 hunks)
  • backend/config/config.prod.yml (1 hunks)
  • backend/controllers/profile_controller.go (7 hunks)
  • backend/models/debate.go (1 hunks)
  • backend/models/user.go (1 hunks)
  • backend/utils/auth.go (1 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/Pages/Profile.tsx (16 hunks)
  • frontend/src/components/ui/calendar.tsx (1 hunks)
  • frontend/src/components/ui/popover.tsx (1 hunks)
  • frontend/src/services/profileService.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
backend/cmd/server/main.go (2)
backend/db/db.go (1)
  • ConnectMongoDB (33-55)
backend/utils/auth.go (1)
  • SetJWTSecret (27-29)
frontend/src/components/ui/popover.tsx (1)
frontend/src/lib/utils.ts (1)
  • cn (4-6)
frontend/src/components/ui/calendar.tsx (2)
frontend/src/components/ui/button.tsx (2)
  • Button (57-57)
  • buttonVariants (57-57)
frontend/src/lib/utils.ts (1)
  • cn (4-6)
backend/controllers/profile_controller.go (1)
backend/db/db.go (1)
  • MongoDatabase (17-17)
🪛 golangci-lint (1.64.8)
backend/controllers/profile_controller.go

81-81: composites: go.mongodb.org/mongo-driver/bson/primitive.E struct literal uses unkeyed fields

(govet)


125-125: composites: go.mongodb.org/mongo-driver/bson/primitive.E struct literal uses unkeyed fields

(govet)

🔇 Additional comments (8)
backend/models/debate.go (1)

16-16: LGTM! Well-structured field addition.

The EloRating field addition follows proper Go conventions with appropriate BSON/JSON tags and uses the correct data type for Elo ratings.

frontend/package.json (1)

17-17:

Details

❓ Verification inconclusive

Verify package versions for security and compatibility.

The new dependencies appear appropriate for the calendar/popover UI features, but please verify these package versions are current and secure.

Also applies to: 22-22, 28-28, 31-31


🏁 Script executed:

#!/bin/bash
# Description: Check for security advisories and verify latest versions for the new/updated packages

echo "Checking @radix-ui/react-popover..."
npm view @radix-ui/react-popover versions --json | jq '.[-5:]'
npm audit --audit-level=moderate --package-lock-only --json | jq '.vulnerabilities | keys[]' | grep -i popover || echo "No popover vulnerabilities found"

echo "Checking date-fns..."
npm view date-fns versions --json | jq '.[-5:]'
npm audit --audit-level=moderate --package-lock-only --json | jq '.vulnerabilities | keys[]' | grep -i "date-fns" || echo "No date-fns vulnerabilities found"

echo "Checking react-day-picker..."
npm view react-day-picker versions --json | jq '.[-5:]'
npm audit --audit-level=moderate --package-lock-only --json | jq '.vulnerabilities | keys[]' | grep -i "day-picker" || echo "No react-day-picker vulnerabilities found"

echo "Checking @radix-ui/react-slot..."
npm view @radix-ui/react-slot versions --json | jq '.[-5:]'

Length of output: 2613


Confirmed dependency versions are up-to-date

  • @radix-ui/react-popover → latest stable v1.1.14
  • date-fns → latest stable v4.1.0
  • react-day-picker → latest stable v9.7.0
  • @radix-ui/react-slot → latest stable v1.2.3

npm audit couldn’t run without a lockfile—please commit a package-lock.json (or yarn.lock) and re-run npm audit to ensure there are no known vulnerabilities before merging.

frontend/src/services/profileService.ts (1)

17-24: LGTM! Clean TypeScript implementation.

The function signature extension and JSON body update properly support the new social media fields with correct optional typing.

Also applies to: 31-31

frontend/src/components/ui/popover.tsx (1)

1-32: Well-implemented popover component following React best practices.

This implementation demonstrates excellent code quality:

  • Proper use of forwardRef for DOM element access
  • Correct TypeScript typing with Radix UI primitive types
  • Comprehensive styling with smooth animations and responsive behavior
  • Good default props (align="center", sideOffset=4)
  • Proper displayName setting for debugging
  • Clean re-exports of Radix primitives

The component follows the established UI library patterns and will integrate well with the profile page calendar functionality.

frontend/src/components/ui/calendar.tsx (1)

170-206: Well-implemented accessible calendar button component!

The focus management, data attributes for state tracking, and proper ref forwarding make this component both accessible and maintainable.

backend/controllers/profile_controller.go (1)

233-252: Good input sanitization and field updates!

The trimming of whitespace from all input fields and the addition of social media fields with proper error handling are well implemented.

frontend/src/Pages/Profile.tsx (2)

145-159: Excellent UX improvements with auto-focus and auto-clear!

The auto-focus on field editing and the 5-second auto-clear for success messages significantly improve the user experience.


466-940: Excellent responsive design and UI polish!

The comprehensive responsive design with proper text truncation, flexible layouts, and size adjustments across breakpoints creates a great user experience on all device sizes.

}
log.Println("Connected to MongoDB")

utils.SetJWTSecret(cfg.JWT.Secret)
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the configuration structure supports JWT.Secret field.

The JWT secret initialization looks correct and is well-placed after DB connection. Please ensure the config structure includes the JWT.Secret field.


🏁 Script executed:

#!/bin/bash
# Description: Verify that the config structure includes JWT.Secret field and the config file exists

# Check if config structure defines JWT.Secret
ast-grep --pattern $'type Config struct {
  $$$
  JWT $_ {
    $$$
    Secret $_
    $$$
  }
  $$$
}'

# Check if the config file exists and contains JWT secret
if [ -f "backend/config/config.prod.yml" ]; then
  echo "Checking config.prod.yml for JWT configuration:"
  cat backend/config/config.prod.yml | grep -A 5 -B 2 -i jwt || echo "No JWT section found in config file"
else
  echo "Config file backend/config/config.prod.yml not found"
fi

Length of output: 598


To confirm the Config struct’s definition and ensure it includes the JWT.Secret field, let’s locate its declaration in the codebase:


🏁 Script executed:

#!/bin/bash
# Locate and inspect the Config struct to verify JWT.Secret is defined
rg -n 'type Config struct' -A20 --color=never

Length of output: 1102


Add missing JWT field to the Config struct

The Config struct in backend/config/config.go does not define a JWT section, so cfg.JWT.Secret will not be populated. Please update the struct to include it:

• File: backend/config/config.go, inside type Config struct { … }

 type Config struct {
   Server struct {
     Port int `yaml:"port"`
   } `yaml:"server"`
   Cognito struct { … } `yaml:"cognito"`
   Openai struct { … } `yaml:"openai"`
   Gemini struct { … } `yaml:"gemini"`
   Database struct { … } `yaml:"database"`
+    JWT struct {
+      Secret string `yaml:"secret"`
+      Expiry int    `yaml:"expiry"` // if you also want to capture token expiry
+    } `yaml:"jwt"`
 }

• Ensure your YAML config (e.g. backend/config/config.prod.yml) remains:

jwt:
  secret: '<YOUR_JWT_SECRET>'
  expiry: 1440

After this change, utils.SetJWTSecret(cfg.JWT.Secret) will correctly receive the configured value.

🤖 Prompt for AI Agents
In backend/config/config.go around the definition of the Config struct, add a
JWT field that includes a Secret string field to match the expected structure
used in main.go. This will ensure cfg.JWT.Secret is properly populated from the
configuration file. Confirm the YAML config file backend/config/config.prod.yml
contains the jwt section with secret and expiry keys as expected. This update
will allow utils.SetJWTSecret(cfg.JWT.Secret) to receive the correct JWT secret
value.

Comment on lines 34 to 37
JWT struct {
Secret string // Add JWT secret
Expiry int // Token expiry in minutes
Secret string `yaml:"secret"`
Expiry int `yaml:"expiry"`
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add missing YAML struct tag for JWT configuration.

The JWT struct is missing the yaml:"jwt" tag, which will prevent proper parsing from YAML files.

 	JWT struct {
 		Secret string `yaml:"secret"`
 		Expiry int    `yaml:"expiry"`
-	}
+	} `yaml:"jwt"`
📝 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.

Suggested change
JWT struct {
Secret string // Add JWT secret
Expiry int // Token expiry in minutes
Secret string `yaml:"secret"`
Expiry int `yaml:"expiry"`
}
JWT struct {
Secret string `yaml:"secret"`
Expiry int `yaml:"expiry"`
- }
+ } `yaml:"jwt"`
🤖 Prompt for AI Agents
In backend/config/config.go around lines 34 to 37, the JWT struct lacks the
yaml:"jwt" tag needed for proper YAML parsing. Add the yaml:"jwt" struct tag to
the JWT struct definition so that the entire JWT configuration block is
correctly mapped when unmarshalling from YAML files.

Comment on lines +47 to 50
GoogleOAuth struct {
ClientID string `yaml:"clientID"`
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add missing YAML struct tag for GoogleOAuth configuration.

The GoogleOAuth struct is missing the yaml:"googleOAuth" tag, which will prevent proper parsing from YAML files.

 	GoogleOAuth struct {
 		ClientID string `yaml:"clientID"`
-	}
+	} `yaml:"googleOAuth"`
📝 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.

Suggested change
GoogleOAuth struct {
ClientID string `yaml:"clientID"`
}
}
GoogleOAuth struct {
ClientID string `yaml:"clientID"`
} `yaml:"googleOAuth"`
}
🤖 Prompt for AI Agents
In backend/config/config.go around lines 47 to 50, the GoogleOAuth struct lacks
the yaml struct tag for the entire struct, which is necessary for correct YAML
unmarshalling. Add the tag `yaml:"googleOAuth"` to the GoogleOAuth struct
definition to ensure it maps properly when parsing the YAML configuration file.

Comment on lines +27 to +29
func SetJWTSecret(secret string) {
jwtSecret = secret
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for JWT secret quality.

The SetJWTSecret function should validate that the provided secret meets security requirements.

 func SetJWTSecret(secret string) {
+	if len(secret) < 32 {
+		log.Fatal("JWT secret must be at least 32 characters long")
+	}
+	if secret == "" || strings.Contains(secret, "<") || strings.Contains(secret, ">") {
+		log.Fatal("JWT secret appears to be a placeholder value")
+	}
 	jwtSecret = secret
 }
📝 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.

Suggested change
func SetJWTSecret(secret string) {
jwtSecret = secret
}
func SetJWTSecret(secret string) {
if len(secret) < 32 {
log.Fatal("JWT secret must be at least 32 characters long")
}
if secret == "" || strings.Contains(secret, "<") || strings.Contains(secret, ">") {
log.Fatal("JWT secret appears to be a placeholder value")
}
jwtSecret = secret
}
🤖 Prompt for AI Agents
In backend/utils/auth.go around lines 27 to 29, the SetJWTSecret function
currently assigns the secret without validation. Add validation logic to ensure
the secret meets security requirements such as minimum length and complexity
before assigning it to jwtSecret. If the secret is invalid, handle the error
appropriately, for example by returning an error or logging a warning.

Comment on lines +31 to +36
func getJWTSecret() string {
if jwtSecret == "" {
log.Fatal("JWT secret is not set in config")
}
return jwtSecret
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace log.Fatal with proper error handling.

Using log.Fatal will crash the entire application when JWT secret is not set. This prevents graceful error handling and recovery.

-func getJWTSecret() string {
+func getJWTSecret() (string, error) {
 	if jwtSecret == "" {
-		log.Fatal("JWT secret is not set in config")
+		return "", errors.New("JWT secret is not set in config")
 	}
-	return jwtSecret
+	return jwtSecret, nil
 }

Then update callers to handle the error:

 func GenerateJWTToken(userID, email string) (string, error) {
 	// ... existing code ...
-	jwtSecret := []byte(getJWTSecret())
+	secretStr, err := getJWTSecret()
+	if err != nil {
+		return "", err
+	}
+	jwtSecret := []byte(secretStr)
📝 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.

Suggested change
func getJWTSecret() string {
if jwtSecret == "" {
log.Fatal("JWT secret is not set in config")
}
return jwtSecret
}
func getJWTSecret() (string, error) {
if jwtSecret == "" {
return "", errors.New("JWT secret is not set in config")
}
return jwtSecret, nil
}
🤖 Prompt for AI Agents
In backend/utils/auth.go around lines 31 to 36, replace the use of log.Fatal
with returning an error from getJWTSecret instead of crashing the application.
Change the function signature to return (string, error), check if jwtSecret is
empty and return an appropriate error rather than calling log.Fatal. Then update
all callers of getJWTSecret to handle the error properly by checking the
returned error and responding accordingly.

dbCtx,
bson.M{"email": email},
options.Find().SetSort(bson.M{"date": -1}).SetLimit(5),
options.Find().SetSort(bson.D{{"date", 1}}),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unkeyed fields in bson.D struct literal.

Use explicit field names for the sort operation:

-		options.Find().SetSort(bson.D{{"date", 1}}),
+		options.Find().SetSort(bson.D{{Key: "date", Value: 1}}),
📝 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.

Suggested change
options.Find().SetSort(bson.D{{"date", 1}}),
options.Find().SetSort(bson.D{{Key: "date", Value: 1}}),
🧰 Tools
🪛 golangci-lint (1.64.8)

125-125: composites: go.mongodb.org/mongo-driver/bson/primitive.E struct literal uses unkeyed fields

(govet)

🤖 Prompt for AI Agents
In backend/controllers/profile_controller.go at line 125, the bson.D struct
literal used for sorting has unkeyed fields. Replace the unkeyed field with an
explicit key-value pair by specifying the field name "Key" and the value "date"
to fix the struct literal. This means changing bson.D{{"date", 1}} to
bson.D{{Key: "date", Value: 1}}.

dbCtx,
bson.M{},
options.Find().SetSort(bson.M{"eloRating": -1}).SetLimit(10),
options.Find().SetSort(bson.D{{"eloRating", -1}}).SetLimit(5),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unkeyed fields in bson.D struct literal.

The static analysis tool correctly identifies unkeyed fields. Use explicit field names for better maintainability:

-		options.Find().SetSort(bson.D{{"eloRating", -1}}).SetLimit(5),
+		options.Find().SetSort(bson.D{{Key: "eloRating", Value: -1}}).SetLimit(5),
📝 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.

Suggested change
options.Find().SetSort(bson.D{{"eloRating", -1}}).SetLimit(5),
options.Find().SetSort(bson.D{{Key: "eloRating", Value: -1}}).SetLimit(5),
🧰 Tools
🪛 golangci-lint (1.64.8)

81-81: composites: go.mongodb.org/mongo-driver/bson/primitive.E struct literal uses unkeyed fields

(govet)

🤖 Prompt for AI Agents
In backend/controllers/profile_controller.go at line 81, the bson.D struct
literal uses unkeyed fields which reduces code clarity and maintainability.
Replace the unkeyed fields with explicit field names by specifying the Key and
Value fields in the bson.D struct literal, for example using bson.E{Key:
"eloRating", Value: -1} instead of just {"eloRating", -1}.

Comment on lines +234 to +241
<a
href={
field === "twitter"
? `https://twitter.com/${dashboard.profile[field]}`
: field === "instagram"
? `https://instagram.com/${dashboard.profile[field]}`
: `https://linkedin.com/in/${dashboard.profile[field]}`
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add URL validation for social media handles.

The social media URLs are constructed without validating the user input. Consider sanitizing special characters that could break the URLs:

  href={
    field === "twitter"
-     ? `https://twitter.com/${dashboard.profile[field]}`
+     ? `https://twitter.com/${encodeURIComponent(dashboard.profile[field] || '')}`
    : field === "instagram"
-     ? `https://instagram.com/${dashboard.profile[field]}`
+     ? `https://instagram.com/${encodeURIComponent(dashboard.profile[field] || '')}`
-     : `https://linkedin.com/in/${dashboard.profile[field]}`
+     : `https://linkedin.com/in/${encodeURIComponent(dashboard.profile[field] || '')}`
  }
📝 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.

Suggested change
<a
href={
field === "twitter"
? `https://twitter.com/${dashboard.profile[field]}`
: field === "instagram"
? `https://instagram.com/${dashboard.profile[field]}`
: `https://linkedin.com/in/${dashboard.profile[field]}`
}
<a
href={
field === "twitter"
? `https://twitter.com/${encodeURIComponent(dashboard.profile[field] || '')}`
: field === "instagram"
? `https://instagram.com/${encodeURIComponent(dashboard.profile[field] || '')}`
: `https://linkedin.com/in/${encodeURIComponent(dashboard.profile[field] || '')}`
}
🤖 Prompt for AI Agents
In frontend/src/Pages/Profile.tsx around lines 234 to 241, the social media URLs
are constructed directly from user input without validation, which can lead to
broken or unsafe URLs. To fix this, sanitize the dashboard.profile[field] values
by encoding special characters using a function like encodeURIComponent before
embedding them in the URLs. This ensures the URLs are valid and safe to use.

@bhavik-mangla bhavik-mangla merged commit f6c866b into AOSSIE-Org:main Jun 22, 2025
1 check passed
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.

2 participants