Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation to check document ids before api calling #164

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

cp-sneh-s
Copy link
Collaborator

@cp-sneh-s cp-sneh-s commented Jan 10, 2025

Changelog

  • Added validation for checking blank ids of documents before making api call.

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling and input validation across multiple services
    • Enhanced null safety checks in authentication and user management
    • Prevented potential invalid document references in location and journey services
  • Refactor

    • Streamlined code to handle nullable user IDs more robustly
    • Updated methods to use safer null-checking approaches
    • Improved overall code reliability and exception prevention

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

This pull request focuses on improving null safety, error handling, and input validation across several services and repositories in the YourSpace application. The changes primarily involve modifying how user IDs, space IDs, and current user references are handled, ensuring more robust code by preventing potential null pointer exceptions and enforcing stricter input validation. The modifications span multiple files, including location and journey services, authentication service, and space repository.

Changes

File Change Summary
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt Enhanced input validation for document references by removing fallback to "null" and ensuring non-blank spaceId and userId
data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt Improved error handling by directly using spaceId without fallback and enforcing stricter validation for document references
app/src/main/java/com/canopas/yourspace/ui/flow/settings/SettingsViewModel.kt Added null safety check to authService.getUserFlow() to prevent potential null pointer exceptions
data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt Updated methods to handle nullable user IDs more safely, adding conditional checks before performing space-related operations
data/src/main/java/com/canopas/yourspace/data/service/auth/AuthService.kt Replaced direct null checks with let function and conditional statements to improve null safety in various methods

Possibly related PRs

Suggested reviewers

  • cp-megh-l
  • cp-radhika-s

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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 or 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: 1

🧹 Nitpick comments (11)
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (3)

40-44: Enhance error message for better debugging.

While the validation is correct, consider making the error message more descriptive to aid in debugging.

-        throw IllegalArgumentException("Space ID is empty")
+        throw IllegalArgumentException("Space ID cannot be blank when creating space member reference")

46-50: Enhance error message for better debugging.

Consider making the error message more descriptive to aid in debugging.

-        throw IllegalArgumentException("User ID is empty")
+        throw IllegalArgumentException("User ID cannot be blank when creating journey reference")

52-57: Multiple improvements suggested.

  1. The error message could be more descriptive.
  2. The indentation on line 57 is inconsistent.
  3. Consider extracting the hardcoded document ID to a constant.
+    private companion object {
+        private const val GROUP_KEYS_DOC_ID = FIRESTORE_COLLECTION_SPACE_GROUP_KEYS
+    }

     private fun spaceGroupKeysRef(spaceId: String) = if (spaceId.isBlank()) {
-        throw IllegalArgumentException("Space ID is empty")
+        throw IllegalArgumentException("Space ID cannot be blank when creating group keys reference")
     } else {
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
-            .document(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
+            .document(GROUP_KEYS_DOC_ID)
     }
data/src/main/java/com/canopas/yourspace/data/service/messages/ApiMessagesService.kt (2)

31-35: Consider enhancing error message and documentation.

While the validation is good, we can make it more helpful for debugging.

Consider this enhancement:

-    private fun threadMessagesRef(threadId: String) = if (threadId.isBlank()) {
-        throw IllegalArgumentException("Thread ID cannot be empty")
+    /**
+     * Returns a reference to the messages collection for a thread.
+     * @param threadId The ID of the thread
+     * @throws IllegalArgumentException if threadId is blank
+     */
+    private fun threadMessagesRef(threadId: String) = if (threadId.isBlank()) {
+        throw IllegalArgumentException("Thread ID cannot be empty or blank. Provided: '$threadId'")

31-35: Consider consistent error handling across the service.

While we're validating threadId in threadMessagesRef, other methods like createThread, joinThread, etc. might benefit from similar input validation.

Consider adding similar validation for:

  • spaceId and adminId in createThread
  • threadId and userIds in joinThread
  • Other methods accepting IDs as parameters

Would you like me to propose specific validation changes for these methods?

data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (2)

54-58: LGTM! Consider adding KDoc documentation.

The validation logic is correct and aligns with the PR objectives. Early validation of blank IDs will prevent downstream issues.

Consider adding KDoc documentation to clarify the function's behavior and the conditions under which it throws exceptions:

/**
 * Returns a reference to the space members collection.
 * @param spaceId The ID of the space
 * @throws IllegalArgumentException if spaceId is blank
 */

67-72: LGTM! Consider extracting the duplicate constant.

The validation logic is correct, but there's a minor improvement possible.

The constant FIRESTORE_COLLECTION_SPACE_GROUP_KEYS is used twice. Consider extracting it to a local variable for better maintainability:

     private fun spaceGroupKeysRef(spaceId: String) = if (spaceId.isBlank()) {
         throw IllegalArgumentException("Space ID cannot be blank")
     } else {
+        val groupKeysCollection = FIRESTORE_COLLECTION_SPACE_GROUP_KEYS
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
-            .document(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
+            .document(groupKeysCollection)
     }
data/src/main/java/com/canopas/yourspace/data/service/user/ApiUserService.kt (1)

54-55: Consider documenting the null return case.

The early validation for blank user IDs is good. Consider adding a KDoc comment to document that the function returns null for blank IDs.

+    /**
+     * Retrieves a user from Firestore by their ID.
+     * @param userId The ID of the user to retrieve
+     * @return null if userId is blank, user doesn't exist, or an error occurs
+     */
     suspend fun getUser(userId: String): ApiUser? {
data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt (2)

46-52: Consider documenting error handling for cryptographic operations

Good validation. Since this function is used in cryptographic operations (e.g., distributeSenderKeyToSpaceMembers), consider adding documentation about error handling requirements for security-critical flows.

Add KDoc to document the validation:

+    /**
+     * Returns the document reference for space group keys.
+     * @param spaceId The space identifier
+     * @throws IllegalArgumentException if spaceId is blank
+     */
     private fun spaceGroupKeysDoc(spaceId: String) = if (spaceId.isBlank()) {

40-52: Consider standardizing error handling across services

The validation approach is good, but since this is part of a broader effort to improve error handling across services (ApiJourneyService, ApiLocationService, etc.), consider:

  1. Creating a common validation utility class for consistent ID validation
  2. Standardizing error messages across services
  3. Documenting the error handling strategy for the entire data layer

This would ensure consistency and make the validation behavior more maintainable.

Example utility class:

object ValidationUtils {
    fun validateSpaceId(spaceId: String, context: String = "") {
        if (spaceId.isBlank()) {
            throw IllegalArgumentException("${context}Space ID cannot be empty")
        }
    }
    // Add other validation methods as needed
}
data/src/main/java/com/canopas/yourspace/data/service/place/ApiPlaceService.kt (1)

31-38: LGTM! Consider improving readability.

The improved validation for blank IDs is good. However, the indentation of the collection chain could be more readable.

Consider this formatting for better readability:

     private fun spacePlacesSettingsRef(spaceId: String, placeId: String) =
         if (spaceId.isEmpty() || placeId.isEmpty()) {
             throw IllegalStateException("Space ID or Place ID is empty")
         } else {
-            spaceRef.document(spaceId).collection(Config.FIRESTORE_COLLECTION_SPACE_PLACES)
-                .document(placeId).collection(
-                    Config.FIRESTORE_COLLECTION_SPACE_PLACES_MEMBER_SETTINGS
-                )
+            spaceRef
+                .document(spaceId)
+                .collection(Config.FIRESTORE_COLLECTION_SPACE_PLACES)
+                .document(placeId)
+                .collection(Config.FIRESTORE_COLLECTION_SPACE_PLACES_MEMBER_SETTINGS)
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6391d5e and 909e7f8.

📒 Files selected for processing (6)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/messages/ApiMessagesService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/place/ApiPlaceService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/user/ApiUserService.kt (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (8)
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (1)

40-57: Overall implementation looks good!

The validation checks for blank IDs are well-placed and will prevent potential issues with invalid Firestore references. The implementation is consistent across all reference-creating functions and aligns well with similar validation patterns in other files.

data/src/main/java/com/canopas/yourspace/data/service/messages/ApiMessagesService.kt (1)

31-35: LGTM! Good addition of input validation.

The change improves error handling by preventing operations with invalid thread IDs early, which aligns well with the PR objectives.

Let's verify the impact on callers of this function:

✅ Verification successful

Validation change is safe and properly handled

The change is verified to be safe because:

  • All calls to threadMessagesRef are wrapped in try-catch blocks in the ViewModel layer
  • Exceptions are properly propagated and displayed to users via UI state updates
  • The validation is consistently applied across all message operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to threadMessagesRef or methods that use it
ast-grep --pattern 'threadMessagesRef($$$)' 

# Search for error handling patterns in callers
rg -A 5 'getLatestMessages|getMessages|sendMessage|generateMessage'

Length of output: 11391

data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1)

Line range hint 74-190: Review error handling in dependent functions.

The reference functions now throw IllegalArgumentException instead of returning null references. The dependent functions (saveLastKnownLocation, saveCurrentLocation, getCurrentLocation) should be updated to handle these exceptions appropriately.

Please verify the error handling in these functions. Here's a script to find all usages:

Consider updating the error handling in dependent functions:

try {
    // Existing code
} catch (e: Exception) {
    when (e) {
        is IllegalArgumentException -> {
            Timber.e(e, "Invalid ID provided")
            // Handle invalid ID appropriately
        }
        is NoSessionException -> {
            // Existing handling
        }
        // Other existing cases
    }
}
✅ Verification successful

Existing error handling is appropriate

The dependent functions already implement comprehensive error handling through null checks, early returns, and try-catch blocks. The IllegalArgumentException from reference functions serves as input validation, preventing invalid states from propagating. No changes are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of the reference functions to verify error handling

# Search for function calls
rg -A 5 "spaceMemberRef|spaceMemberLocationRef|spaceGroupKeysRef" --type kotlin

# Search for try-catch blocks that might need updating
rg -B 2 -A 5 "catch \((Exception|Throwable)" --type kotlin

Length of output: 16082

data/src/main/java/com/canopas/yourspace/data/service/user/ApiUserService.kt (2)

Line range hint 1-276: Consider consistent ID validation across all methods.

Several other methods in this class accept userId as a parameter but don't validate for blank IDs:

  • deleteUser
  • updateUser
  • registerFcmToken
  • addSpaceId
  • updateBatteryPct
  • updateSessionState
  • getUserSession
  • getUserNetworkStatus

Consider adding similar validation to maintain consistency across the service.

Let's verify which methods might need validation:

✅ Verification successful

Validation needed in methods using userId parameter

The review comment is correct. Several methods in ApiUserService use userId without validation:

  • deleteUser(userId) directly uses it in userRef.document(userId).delete()
  • registerFcmToken(userId, token) uses it in document reference
  • addSpaceId(userId, spaceId) uses it for document update
  • updateBatteryPct(userId, batteryPct) uses it in document reference
  • updateSessionState(userId, state) uses it for document update
  • getUserSession(userId) uses it in sessionRef
  • getUserNetworkStatus(userId, lastUpdatedTime, onStatusChecked) uses it in function parameters

Since sessionRef and getUser already validate for blank userId, the same validation should be added to maintain consistency and prevent potential issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all public methods that take userId as parameter
ast-grep --pattern 'fun $methodName($$$userId: String$$$)' | rg -B 2 -A 2 'fun.*userId.*String'

Length of output: 97


Script:

#!/bin/bash
# Try different patterns to find methods with userId parameter
ast-grep --pattern 'suspend fun $name($$$userId: String$$$)'

echo "=== Using ripgrep as fallback ==="
rg "fun.*\(.*userId:\s*String" -A 2

Length of output: 17706


46-50: LGTM! Verify impact on dependent methods.

The validation for blank user IDs is a good addition that aligns with the PR objectives. The error message is clear and descriptive.

Let's verify the impact on methods that call sessionRef:

✅ Verification successful

Validation in sessionRef is appropriately placed and handled

The IllegalArgumentException for blank user IDs is well-placed in this private utility method. Some calling methods like getUser and saveUser already validate their inputs, while others appropriately allow the exception to propagate for invalid inputs, which is the correct behavior for these internal service methods.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all methods that call sessionRef to ensure they handle the new exception
ast-grep --pattern 'sessionRef($$$)' | rg -A 5 'sessionRef'

Length of output: 852


Script:

#!/bin/bash
# Get the complete implementation of methods containing sessionRef calls
ast-grep --pattern 'fun $$$sessionRef($$$)' | rg -B 5 -A 15 'sessionRef'

Length of output: 72


Script:

#!/bin/bash
# Get implementations of methods containing sessionRef with more context
rg -B 10 -A 20 "fun (get|sign|register|.*Session)" data/src/main/java/com/canopas/yourspace/data/service/user/ApiUserService.kt

Length of output: 5168

data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt (1)

40-44: Validate error handling in calling methods

Good addition of input validation. However, since this is a private function used by multiple public methods, we should ensure proper error handling in the calling methods.

Let's verify the error handling in calling methods:

✅ Verification successful

Input validation implementation is appropriate

The validation in spaceMemberRef is well-implemented:

  • Validates input at the service layer where the space ID is first used
  • Uses appropriate exception type (IllegalArgumentException) for invalid arguments
  • Follows Kotlin's suspend function error propagation patterns
  • Consistent with other methods in the class (e.g., spaceGroupKeysDoc)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all methods that call spaceMemberRef
ast-grep --pattern 'fun $FUNC($ARGS) {
  $$$
  spaceMemberRef($SPACE_ID)
  $$$
}'

Length of output: 83


Script:

#!/bin/bash
# View the content of the file to understand its structure
cat data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt

Length of output: 9942


Script:

#!/bin/bash
# Search for ViewModel classes that might be handling these service calls
rg -l "ApiSpaceService" --type kotlin | grep -i "viewmodel"

Length of output: 57

data/src/main/java/com/canopas/yourspace/data/service/place/ApiPlaceService.kt (2)

24-38: Consider standardizing empty ID handling across all methods.

I notice that listenAllPlaces handles empty spaceId differently by returning emptyFlow() instead of throwing an exception. Consider standardizing the approach across all methods for consistency:

  1. Either make all methods throw exceptions for empty IDs
  2. Or make all methods handle empty IDs gracefully (return null/empty)

Let's check for inconsistent empty ID handling:

✅ Verification successful

Empty ID handling is correctly implemented

The current implementation follows a good pattern:

  • Internal reference methods fail fast with exceptions to prevent invalid database operations
  • Public-facing methods handle empty IDs gracefully by returning empty collections
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all methods that check for empty IDs
rg -A 2 "isEmpty\(\)" data/src/main/java/com/canopas/yourspace/data/service/place/ApiPlaceService.kt

Length of output: 706


24-28: LGTM! Verify exception handling in callers.

The improved error handling for blank space IDs is a good change. However, since this is a breaking change (throwing exception instead of returning null), ensure that all calling methods properly handle the IllegalStateException.

Let's verify the exception handling in all callers:

✅ Verification successful

Exception handling approach is appropriate

The verification shows that:

  • Most methods properly propagate exceptions through suspend functions
  • listenAllPlaces() already handles empty space IDs defensively
  • Service layer should fail fast on invalid inputs rather than silently continuing

The change from returning null to throwing an exception is appropriate here as it:

  1. Prevents silent failures
  2. Forces proper error handling in the presentation layer
  3. Maintains consistency with Kotlin's fail-fast principles
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all methods that call spacePlacesRef
ast-grep --pattern 'spacePlacesRef($$$)'

Length of output: 793


Script:

#!/bin/bash
# Get context of methods containing spacePlacesRef calls
ast-grep --pattern 'suspend fun $$$($$$) {
  $$$
  spacePlacesRef($$$)
  $$$
}'

# Also check for try-catch blocks around these calls
ast-grep --pattern 'try {
  $$$
  spacePlacesRef($$$)
  $$$
} catch'

Length of output: 152


Script:

#!/bin/bash
# Get context around spacePlacesRef calls with ripgrep
rg "spacePlacesRef" data/src/main/java/com/canopas/yourspace/data/service/place/ApiPlaceService.kt -B 5 -A 5

Length of output: 1920

@cp-sneh-s cp-sneh-s changed the title Add validation for blank ids before api calling Add validation to check document ids before api calling Jan 10, 2025
@cp-megh-l cp-megh-l self-requested a review January 10, 2025 08:46
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: 7

♻️ Duplicate comments (1)
data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1)

58-59: ⚠️ Potential issue

Add validation for both spaceId and userId.

The function needs validation for both parameters to prevent invalid document references.

As suggested in the previous review, implement validation for both parameters:

 private fun spaceMemberLocationRef(spaceId: String, userId: String) =
+    when {
+        userId.isBlank() -> throw IllegalArgumentException("User ID cannot be blank")
+        spaceId.isBlank() -> throw IllegalArgumentException("Space ID cannot be blank")
+        else ->
         spaceMemberRef(spaceId).document(userId)
             .collection(Config.FIRESTORE_COLLECTION_USER_LOCATIONS)
+    }
🧹 Nitpick comments (4)
app/src/main/java/com/canopas/yourspace/ui/flow/settings/SettingsViewModel.kt (1)

40-42: LGTM! Consider enhancing error handling.

The null-safe operator is a good addition for preventing NPEs. However, consider adding explicit error handling and logging for the null case.

Here's a suggested improvement:

-        authService.getUserFlow()?.collectLatest { user ->
-            _state.emit(_state.value.copy(user = user))
-        }
+        try {
+            val userFlow = authService.getUserFlow()
+            if (userFlow == null) {
+                Timber.e("getUserFlow() returned null")
+                _state.emit(_state.value.copy(error = "Failed to get user data"))
+                return@launch
+            }
+            userFlow.collectLatest { user ->
+                _state.emit(_state.value.copy(user = user, error = null))
+            }
+        } catch (e: Exception) {
+            Timber.e(e, "Failed to get user")
+            _state.emit(_state.value.copy(error = e.localizedMessage))
+        }
data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1)

55-63: Consider implementing a unified validation approach.

The validation logic is duplicated across multiple functions. Consider extracting the validation into a reusable extension function or utility method.

+ private fun requireValidId(id: String, type: String) {
+     if (id.isBlank()) {
+         throw IllegalArgumentException("$type ID cannot be blank")
+     }
+ }

 private fun spaceMemberRef(spaceId: String) =
+    requireValidId(spaceId, "Space").let {
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
+    }

 private fun spaceMemberLocationRef(spaceId: String, userId: String) =
+    requireValidId(spaceId, "Space").also { requireValidId(userId, "User") }.let {
         spaceMemberRef(spaceId).document(userId)
             .collection(Config.FIRESTORE_COLLECTION_USER_LOCATIONS)
+    }

 private fun spaceGroupKeysRef(spaceId: String) =
+    requireValidId(spaceId, "Space").let {
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
             .document(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
+    }
data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt (2)

Line range hint 188-200: Consider adding error logging for null userId case

While the null safety improvements are good, consider adding error logging when userId is null to help with debugging and monitoring.

 val userId = authService.currentUser?.id
+ if (userId == null) {
+     Timber.w("Attempted to delete user spaces with null userId")
+     return
+ }
 val allSpace = userId?.let { getUserSpaces(it).firstOrNull() } ?: emptyList()

207-212: Consider extracting space selection logic

The chain of operations for selecting the next current space is complex. Consider extracting it into a separate method for better readability and maintainability.

+ private suspend fun getNextAvailableSpaceId(userId: String): String {
+     return getUserSpaces(userId)
+         .firstOrNull()
+         ?.sortedBy { it.created_at }
+         ?.firstOrNull()
+         ?.id ?: ""
+ }

 val userId = authService.currentUser?.id
-currentSpaceId =
-    userId?.let { getUserSpaces(it).firstOrNull()?.sortedBy { it.created_at }?.firstOrNull()?.id }
-        ?: ""
+currentSpaceId = userId?.let { getNextAvailableSpaceId(it) } ?: ""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 909e7f8 and a8681e8.

📒 Files selected for processing (5)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/SettingsViewModel.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt (4 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/auth/AuthService.kt (2 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt
🔇 Additional comments (2)
data/src/main/java/com/canopas/yourspace/data/service/location/ApiLocationService.kt (1)

62-63: ⚠️ Potential issue

Add validation for spaceId in encryption-related reference.

This function is used in encryption operations (getGroupCipherAndDistributionMessage), making it critical to validate the spaceId to prevent security issues.

 private fun spaceGroupKeysRef(spaceId: String) =
+    if (spaceId.isBlank()) {
+        throw IllegalArgumentException("Space ID cannot be blank")
+    } else {
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
             .document(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
+    }

Likely invalid or redundant comment.

data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt (1)

118-119: LGTM! Improved null safety handling

The changes properly handle the case where currentUser.id might be null, preventing potential NPEs and aligning with the PR's objective of adding validation before API calls.

@@ -52,16 +52,14 @@ class ApiLocationService @Inject constructor(
private val spaceRef by lazy { db.collection(FIRESTORE_COLLECTION_SPACES) }

private fun spaceMemberRef(spaceId: String) =
spaceRef.document(spaceId.takeIf { it.isNotBlank() } ?: "null")
.collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
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 validation for blank spaceId.

As per the PR objectives, we need to validate document IDs before making API calls. Add a validation check for blank spaceId to prevent potential runtime errors.

 private fun spaceMemberRef(spaceId: String) =
+    if (spaceId.isBlank()) {
+        throw IllegalArgumentException("Space ID cannot be blank")
+    } else {
         spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
+    }
📝 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
spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
private fun spaceMemberRef(spaceId: String) =
if (spaceId.isBlank()) {
throw IllegalArgumentException("Space ID cannot be blank")
} else {
spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_MEMBERS)
}

Comment on lines +223 to +227
val userId = authService.currentUser?.id
if (userId != null) {
spaceService.removeUserFromSpace(spaceId, userId)
}
val user = userId?.let { userService.getUser(it) }
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and consider code reuse

  1. The user space update logic is duplicated between leaveSpace() and deleteSpace(). Consider extracting this common functionality.
  2. Add error logging for the case when userId is null.
+ private suspend fun updateUserSpaceIds(userId: String, spaceId: String) {
+     val user = userService.getUser(userId) ?: return
+     val updatedSpaceIds = user.space_ids.toMutableList().apply {
+         remove(spaceId)
+     }
+     user.copy(space_ids = updatedSpaceIds).let {
+         userService.updateUser(it)
+     }
+ }

 suspend fun leaveSpace(spaceId: String) {
     val userId = authService.currentUser?.id
+    if (userId == null) {
+        Timber.w("Attempted to leave space with null userId")
+        return
+    }
-    if (userId != null) {
-        spaceService.removeUserFromSpace(spaceId, userId)
-    }
-    val user = userId?.let { userService.getUser(it) }
-    val updatedSpaceIds = user?.space_ids?.toMutableList()?.apply {
-        remove(spaceId)
-    } ?: return
-
-    user.copy(space_ids = updatedSpaceIds).let {
-        userService.updateUser(it)
-    }
+    spaceService.removeUserFromSpace(spaceId, userId)
+    updateUserSpaceIds(userId, spaceId)
 }

Committable suggestion skipped: line range outside the PR's diff.

signOut()
}

suspend fun generateAndSaveUserKeys(passKey: String) {
val user = currentUser ?: throw IllegalStateException("No user logged in")
val user = currentUser
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 blank ID validation and simplify null check.

While the null safety is improved, consider:

  1. Adding validation for blank user ID as per PR objectives
  2. Simplifying by removing the redundant local variable
-        val user = currentUser
-            val updatedUser = user?.let { apiUserService.generateAndSaveUserKeys(it, passKey) }
+            val updatedUser = currentUser?.let { user ->
+                require(user.id.isNotBlank()) { "User ID cannot be blank" }
+                apiUserService.generateAndSaveUserKeys(user, passKey)
+            }

Also applies to: 131-131

Comment on lines +160 to +163
val currentUser = currentUser
if (currentUser != null) {
apiUserService.updateSessionState(currentUser.id, state)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve null safety pattern and add blank ID validation.

Consider:

  1. Using Kotlin's ?.let for consistency with other methods
  2. Adding validation for blank user ID
  3. Removing redundant local variable
-        val currentUser = currentUser
-        if (currentUser != null) {
-            apiUserService.updateSessionState(currentUser.id, state)
-        }
+        currentUser?.let { user ->
+            require(user.id.isNotBlank()) { "User ID cannot be blank" }
+            apiUserService.updateSessionState(user.id, state)
+        }
📝 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
val currentUser = currentUser
if (currentUser != null) {
apiUserService.updateSessionState(currentUser.id, state)
}
currentUser?.let { user ->
require(user.id.isNotBlank()) { "User ID cannot be blank" }
apiUserService.updateSessionState(user.id, state)
}

Comment on lines +148 to +149
suspend fun getUser(): ApiUser? = currentUser?.id?.let { apiUserService.getUser(it) }
suspend fun getUserFlow() = currentUser?.id?.let { apiUserService.getUserFlow(it) }
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 blank ID validation to user retrieval methods.

While the null safety is improved, add validation for blank user IDs as per PR objectives:

-    suspend fun getUser(): ApiUser? = currentUser?.id?.let { apiUserService.getUser(it) }
-    suspend fun getUserFlow() = currentUser?.id?.let { apiUserService.getUserFlow(it) }
+    suspend fun getUser(): ApiUser? = currentUser?.id?.let { id ->
+        require(id.isNotBlank()) { "User ID cannot be blank" }
+        apiUserService.getUser(id)
+    }
+    suspend fun getUserFlow() = currentUser?.id?.let { id ->
+        require(id.isNotBlank()) { "User ID cannot be blank" }
+        apiUserService.getUserFlow(id)
+    }
📝 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
suspend fun getUser(): ApiUser? = currentUser?.id?.let { apiUserService.getUser(it) }
suspend fun getUserFlow() = currentUser?.id?.let { apiUserService.getUserFlow(it) }
suspend fun getUser(): ApiUser? = currentUser?.id?.let { id ->
require(id.isNotBlank()) { "User ID cannot be blank" }
apiUserService.getUser(id)
}
suspend fun getUserFlow() = currentUser?.id?.let { id ->
require(id.isNotBlank()) { "User ID cannot be blank" }
apiUserService.getUserFlow(id)
}

Comment on lines +123 to +124
val currentUser = currentUser
currentUser?.let { apiUserService.deleteUser(it.id) }
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 blank ID validation and simplify null check.

While the null safety is improved, consider:

  1. Adding validation for blank user ID as per PR objectives
  2. Simplifying by removing the redundant local variable
-        val currentUser = currentUser
-        currentUser?.let { apiUserService.deleteUser(it.id) }
+        currentUser?.let { user ->
+            require(user.id.isNotBlank()) { "User ID cannot be blank" }
+            apiUserService.deleteUser(user.id)
+        }
📝 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
val currentUser = currentUser
currentUser?.let { apiUserService.deleteUser(it.id) }
currentUser?.let { user ->
require(user.id.isNotBlank()) { "User ID cannot be blank" }
apiUserService.deleteUser(user.id)
}

Comment on lines +139 to +140
val user = currentUser
val validationResult = user?.let { apiUserService.validatePasskey(it, passKey) }
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 blank ID validation and simplify null check.

While the null safety is improved, consider:

  1. Adding validation for blank user ID as per PR objectives
  2. Simplifying by removing the redundant local variable
-        val user = currentUser
-        val validationResult = user?.let { apiUserService.validatePasskey(it, passKey) }
+        val validationResult = currentUser?.let { user ->
+            require(user.id.isNotBlank()) { "User ID cannot be blank" }
+            apiUserService.validatePasskey(user, passKey)
+        }
📝 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
val user = currentUser
val validationResult = user?.let { apiUserService.validatePasskey(it, passKey) }
val validationResult = currentUser?.let { user ->
require(user.id.isNotBlank()) { "User ID cannot be blank" }
apiUserService.validatePasskey(user, passKey)
}

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