Skip to content

O7E-242-FixPoliceToken#54

Merged
mlukanic merged 1 commit intomainfrom
O7E-242-FixPoliceToken
Jun 9, 2025
Merged

O7E-242-FixPoliceToken#54
mlukanic merged 1 commit intomainfrom
O7E-242-FixPoliceToken

Conversation

@mlukanic
Copy link
Copy Markdown
Contributor

@mlukanic mlukanic commented Jun 9, 2025

Police token will now be hashed after being used

@mlukanic mlukanic self-assigned this Jun 9, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 9, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved security by hashing police tokens after authentication and updating them in the database. This change helps protect sensitive information.

Walkthrough

The RegisterPolice method in the login service was updated to hash the police token after successful authentication. If hashing and database update succeed, the process continues as before; otherwise, errors are logged and returned. No changes were made to method signatures or other parts of the method.

Changes

File(s) Change Summary
service/loginService.go Modified RegisterPolice to hash and store the police token after user authentication. Error handling and logging were added for the hashing and update steps.

Poem

In the land of code, where tokens roam free,
A rabbit hashed a secret, as safe as can be.
With every login, a whisper of trust,
Police tokens now hidden, as security’s a must.
Hop, hop, hooray—hashing saves the day!

✨ 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
Copy Markdown
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: 1

🔭 Outside diff range comments (2)
service/loginService.go (2)

114-116: ⚠️ Potential issue

Critical Issue: Subsequent authentications will fail after first use.

The current implementation has a fundamental flaw. After the first successful authentication, the police_token in the database becomes hashed, but the query on line 115 still performs a plain text comparison. This means all subsequent authentication attempts will fail because you're comparing plain text input against a hashed value in the database.

Consider one of these approaches:

Option 1: Check if token is already hashed

-	if err := s.db.
-		Where("police_token = ?", code).
-		First(&user).
-		Error; err != nil {
+	// Try to find user by plain token first, then by hashed token
+	if err := s.db.Where("police_token = ?", code).First(&user).Error; err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			// Token might be hashed, try to find users and verify
+			var users []model.User
+			if err := s.db.Where("police_token IS NOT NULL AND police_token != ''").Find(&users).Error; err == nil {
+				for _, u := range users {
+					if auth.VerifyPassword(u.PoliceToken, code) {
+						user = u
+						goto found
+					}
+				}
+			}
+			s.logger.Debugf("Failed to register officer")
+			return nil, cerror.ErrInvalidCredentials
+		}
+		s.logger.Errorf("Error finding police officer, error = %+v", err)
+		return nil, err
+	}
+found:

Option 2: One-time use tokens (recommended)

+	// Invalidate the token after use instead of hashing
+	if err := s.db.Model(&user).Update("police_token", nil).Error; err != nil {
+		s.logger.Errorf("Failed to invalidate police token, error = %+v", err)
+		return nil, err
+	}

119-119: 🧹 Nitpick (assertive)

Fix error logging in authentication failure.

The error should not be logged when authentication fails with invalid credentials, as this is expected behavior. Also, the current code logs the error object even though it might be nil in some cases.

-			s.logger.Debugf("Failed to register officer", err)
+			s.logger.Debugf("Failed to register officer: invalid police token")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b781a0 and 3846a10.

📒 Files selected for processing (1)
  • service/loginService.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
service/loginService.go (1)
util/auth/password.go (1)
  • HashPassword (13-21)

Comment thread service/loginService.go
Comment on lines +127 to +138
// Hash the police token after successful authentication
hashedToken, err := auth.HashPassword(code)
if err != nil {
s.logger.Errorf("Failed to hash police token, error = %+v", err)
return nil, err
}

// Update the police token with the hashed version
if err := s.db.Model(&user).Update("police_token", hashedToken).Error; err != nil {
s.logger.Errorf("Failed to update police token, error = %+v", err)
return nil, err
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement proper transaction handling for token updates.

The token hashing and database update should be wrapped in a transaction to ensure consistency. If the database update fails after successful hashing, the system could be left in an inconsistent state.

+	// Use transaction for atomic operation
+	tx := s.db.Begin()
+	defer func() {
+		if r := recover(); r != nil {
+			tx.Rollback()
+		}
+	}()
+
	// Hash the police token after successful authentication
	hashedToken, err := auth.HashPassword(code)
	if err != nil {
		s.logger.Errorf("Failed to hash police token, error = %+v", err)
+		tx.Rollback()
		return nil, err
	}

	// Update the police token with the hashed version
-	if err := s.db.Model(&user).Update("police_token", hashedToken).Error; err != nil {
+	if err := tx.Model(&user).Update("police_token", hashedToken).Error; err != nil {
		s.logger.Errorf("Failed to update police token, error = %+v", err)
+		tx.Rollback()
		return nil, err
	}
+
+	if err := tx.Commit().Error; err != nil {
+		s.logger.Errorf("Failed to commit transaction, error = %+v", err)
+		return nil, err
+	}
📝 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
// Hash the police token after successful authentication
hashedToken, err := auth.HashPassword(code)
if err != nil {
s.logger.Errorf("Failed to hash police token, error = %+v", err)
return nil, err
}
// Update the police token with the hashed version
if err := s.db.Model(&user).Update("police_token", hashedToken).Error; err != nil {
s.logger.Errorf("Failed to update police token, error = %+v", err)
return nil, err
}
// Use transaction for atomic operation
tx := s.db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
// Hash the police token after successful authentication
hashedToken, err := auth.HashPassword(code)
if err != nil {
s.logger.Errorf("Failed to hash police token, error = %+v", err)
tx.Rollback()
return nil, err
}
// Update the police token with the hashed version
if err := tx.Model(&user).Update("police_token", hashedToken).Error; err != nil {
s.logger.Errorf("Failed to update police token, error = %+v", err)
tx.Rollback()
return nil, err
}
if err := tx.Commit().Error; err != nil {
s.logger.Errorf("Failed to commit transaction, error = %+v", err)
return nil, err
}
🤖 Prompt for AI Agents
In service/loginService.go around lines 127 to 138, the token hashing and
database update are not wrapped in a transaction, risking inconsistency if the
update fails after hashing. Refactor the code to start a database transaction
before hashing the token, perform the hashing and update within the transaction,
and commit the transaction only if both succeed. If any step fails, rollback the
transaction to maintain data consistency.

@mlukanic mlukanic merged commit 0ccedf5 into main Jun 9, 2025
2 checks 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