feat: centralize identity creation with router navigation guard

Migrate automatic identity creation from scattered view components to centralized
router navigation guard for consistent behavior across all entry points.

**Key Changes:**
- Add global beforeEach navigation guard in router/index.ts
- Remove automatic identity creation from HomeView, ContactsView, InviteOneAcceptView,
  and OnboardMeetingMembersView
- Keep minimal fallback logic in deep link scenarios with logging
- Exclude manual identity creation routes (/start, /new-identifier, /import-account)

**Benefits:**
- Eliminates code duplication and race conditions
- Ensures consistent identity creation regardless of entry point
- Centralizes error handling with fallback to manual creation
- Improves maintainability with single point of change

**Files Modified:**
- src/router/index.ts: Add navigation guard with identity creation logic
- src/views/HomeView.vue: Remove automatic creation, simplify initializeIdentity()
- src/views/ContactsView.vue: Add fallback with logging
- src/views/InviteOneAcceptView.vue: Add fallback with logging
- src/views/OnboardMeetingMembersView.vue: Add fallback with logging

**Testing:**
- Verified first-time user navigation creates identity automatically
- Confirmed existing users bypass creation logic
- Validated manual creation routes remain unaffected
- Tested deep link scenarios with fallback logic

**Documentation:**
- Created docs/identity-creation-migration.md with comprehensive details
- Includes migration rationale, implementation details, testing scenarios
- Documents security considerations and rollback plan

Resolves inconsistent identity creation behavior across different app entry points.
This commit is contained in:
Matthew Raymer
2025-07-17 04:03:05 +00:00
parent 5c7f58b5c8
commit d355d51ea3
15 changed files with 1121 additions and 99 deletions

View File

@@ -0,0 +1,189 @@
# Identity Creation Migration
## Overview
This document describes the migration of automatic identity creation from individual view components to a centralized router navigation guard. This change ensures that user identities are created consistently regardless of entry point, improving the user experience and reducing code duplication.
## Problem Statement
Previously, automatic identity creation was scattered across multiple view components:
- `HomeView.vue` - Primary entry point
- `InviteOneAcceptView.vue` - Deep link entry point
- `ContactsView.vue` - Contact management
- `OnboardMeetingMembersView.vue` - Meeting setup
This approach had several issues:
1. **Inconsistent behavior** - Different entry points could have different identity creation logic
2. **Code duplication** - Similar identity creation code repeated across multiple components
3. **Race conditions** - Multiple components could attempt identity creation simultaneously
4. **Maintenance overhead** - Changes to identity creation required updates in multiple files
## Solution: Router Navigation Guard
### Implementation
The solution moves identity creation to a global router navigation guard in `src/router/index.ts`:
```typescript
router.beforeEach(async (to, from, next) => {
try {
// Skip identity check for certain routes
const skipIdentityRoutes = ['/start', '/new-identifier', '/import-account', '/database-migration'];
if (skipIdentityRoutes.includes(to.path)) {
return next();
}
// Check if user has any identities
const allMyDids = await retrieveAccountDids();
// Create identity if none exists
if (allMyDids.length === 0) {
logger.info("[Router] No identities found, creating default seed-based identity");
await generateSaveAndActivateIdentity();
}
next();
} catch (error) {
logger.error("[Router] Identity creation failed:", error);
next('/start'); // Redirect to manual identity creation
}
});
```
### Benefits
1. **Centralized Logic** - All identity creation happens in one place
2. **Consistent Behavior** - Same identity creation process regardless of entry point
3. **Early Execution** - Identity creation happens before any view loads
4. **Error Handling** - Centralized error handling with fallback to manual creation
5. **Maintainability** - Single point of change for identity creation logic
## Migration Details
### Files Modified
1. **`src/router/index.ts`**
- Added global `beforeEach` navigation guard
- Added identity creation logic with error handling
- Added route exclusions for manual identity creation
2. **`src/views/HomeView.vue`**
- Removed automatic identity creation logic
- Removed `isCreatingIdentifier` state and UI
- Simplified `initializeIdentity()` method
- Added fallback error handling
3. **`src/views/InviteOneAcceptView.vue`**
- Kept identity creation as fallback for deep links
- Added logging for fallback scenarios
- Simplified logic since router guard handles most cases
4. **`src/views/ContactsView.vue`**
- Kept identity creation as fallback for invite processing
- Added logging for fallback scenarios
- Simplified logic since router guard handles most cases
5. **`src/views/OnboardMeetingMembersView.vue`**
- Kept identity creation as fallback for meeting setup
- Added logging for fallback scenarios
- Simplified logic since router guard handles most cases
### Route Exclusions
The following routes are excluded from automatic identity creation:
- `/start` - Manual identity creation selection
- `/new-identifier` - Manual seed-based identity creation
- `/import-account` - Manual account import
- `/database-migration` - Database migration process
### Fallback Strategy
For deep link scenarios and edge cases, individual views retain minimal identity creation logic as fallbacks:
- Only triggers if `activeDid` is missing
- Includes logging to identify when fallbacks are used
- Maintains backward compatibility
## Testing Considerations
### Test Scenarios
1. **First-time user navigation**
- Navigate to any route without existing identity
- Verify automatic identity creation
- Verify proper navigation to intended route
2. **Existing user navigation**
- Navigate to any route with existing identity
- Verify no unnecessary identity creation
- Verify normal navigation flow
3. **Manual identity creation routes**
- Navigate to `/start`, `/new-identifier`, `/import-account`
- Verify no automatic identity creation
- Verify manual creation flow works
4. **Error scenarios**
- Simulate identity creation failure
- Verify fallback to `/start` route
- Verify error logging
5. **Deep link scenarios**
- Test invite acceptance without existing identity
- Verify fallback identity creation works
- Verify proper invite processing
### Performance Impact
- **Positive**: Reduced code duplication and simplified view logic
- **Minimal**: Router guard adds negligible overhead
- **Improved**: Consistent identity creation timing
## Security Considerations
### Privacy Preservation
- Identity creation still uses the same secure seed generation
- No changes to cryptographic implementation
- Maintains user privacy and data sovereignty
### Error Handling
- Centralized error handling prevents identity creation failures from breaking the app
- Fallback to manual creation ensures users can always create identities
- Proper logging for debugging and monitoring
## Future Enhancements
### Potential Improvements
1. **Identity Type Selection**
- Allow users to choose identity type during automatic creation
- Support for different identity creation methods
2. **Progressive Enhancement**
- Add identity creation progress indicators
- Improve user feedback during creation process
3. **Advanced Fallbacks**
- Implement more sophisticated fallback strategies
- Add retry logic for failed identity creation
4. **Analytics Integration**
- Track identity creation success rates
- Monitor fallback usage patterns
## Rollback Plan
If issues arise, the migration can be rolled back by:
1. Removing the router navigation guard from `src/router/index.ts`
2. Restoring automatic identity creation in individual views
3. Reverting to the previous implementation pattern
## Conclusion
This migration successfully centralizes identity creation logic while maintaining backward compatibility and improving the overall user experience. The router navigation guard approach provides a robust, maintainable solution that ensures consistent identity creation across all entry points.
## Related Documentation
- [Database Migration Guide](../doc/database-migration-guide.md)
- [Migration Progress Tracker](../doc/migration-progress-tracker.md)
- [Platform Service Architecture](../doc/platformservicemixin-completion-plan.md)

View File

@@ -0,0 +1,112 @@
# Corrected Migration Assessment - Critical Files Analysis
**Date**: 2025-7
**Analysis Method**: Direct file inspection using grep and file reading tools
**Purpose**: Verify our initial assessment and identify actual issues vs false positives
## Executive Summary
After direct analysis of the critical files identified in our initial assessment, I found that **our evaluation was mostly accurate** but with some important corrections. The merge did preserve most migration infrastructure, but several components have legitimate incomplete migrations.
## Detailed Analysis Results
### 1 **MembersList.vue** - ✅ **CORRECTLY IDENTIFIED ISSUE**
**Status**: Mixed pattern - Incomplete notification migration
**Issues Found**:
-**No legacy patterns**: No databaseUtil, logConsoleAndDb, or PlatformServiceFactory usage
-**PlatformServiceMixin**: Properly integrated and used
-**Notification Migration**:2direct `$notify()` calls remain (lines380, 395)
- ⚠️ **TODO Comment**: Has migration TODO comment indicating incomplete work
**Analysis**: The2remaining `$notify()` calls are **legitimate complex modal dialogs** that cannot be easily converted to helper methods due to:
- Nested callbacks (`onYes`, `onNo`, `onCancel`)
- Complex confirmation flow logic
- Custom button text and behavior
**Verdict**: This is a **true incomplete migration** that requires attention.
###2. **ContactsView.vue** - ✅ **CORRECTLY IDENTIFIED ISSUE**
**Status**: Mixed pattern - Incomplete notification migration
**Issues Found**:
-**No legacy patterns**: No databaseUtil, logConsoleAndDb, or PlatformServiceFactory usage
-**PlatformServiceMixin**: Properly integrated and used
-**Notification Migration**:4direct `$notify()` calls remain (lines 410 83210031208- ✅ **Helper Setup**: Has `createNotifyHelpers` setup
**Analysis**: The4remaining `$notify()` calls appear to be complex modal dialogs that need migration.
**Verdict**: This is a **true incomplete migration** that requires attention.
### 3. **OnboardMeetingSetupView.vue** - ❌ **FALSE POSITIVE**
**Status**: ✅ **FULLY MIGRATED**
**Issues Found**:
-**No legacy patterns**: No databaseUtil, logConsoleAndDb, or PlatformServiceFactory usage
-**PlatformServiceMixin**: Properly integrated and used
-**Notification Migration**: Only has helper setup, no direct `$notify()` calls
-**Helper Setup**: Has `createNotifyHelpers` setup
**Analysis**: This file only has the helper setup line (`this.notify = createNotifyHelpers(this.$notify as any);`) but no actual `$notify()` calls.
**Verdict**: This is a **false positive** - the file is fully migrated.
###4 **databaseUtil.ts** - ✅ **CORRECTLY IDENTIFIED ISSUE**
**Status**: Legacy logging patterns remain
**Issues Found**:
-**Legacy Logging**: 15+ `logConsoleAndDb()` calls throughout the file
-**Function Definition**: Contains the `logConsoleAndDb` function definition
- ⚠️ **Migration Status**: This file is intentionally kept for backward compatibility
**Analysis**: This file contains the legacy logging function and its usage, which is expected during migration.
**Verdict**: This is a **legitimate legacy pattern** that should be addressed in the final cleanup phase.
###5. **index.ts** - ❓ **NEEDS VERIFICATION**
**Status**: Not analyzed in detail
**Note**: This file was mentioned in the initial assessment but needs individual analysis.
## Corrected Assessment Summary
### **True Issues Found (3 files)**:
1 **MembersList.vue** -2direct `$notify()` calls need migration2. **ContactsView.vue** -4direct `$notify()` calls need migration 3 **databaseUtil.ts** - Legacy logging patterns (expected during migration)
### **false Positives (1e)**:
1. **OnboardMeetingSetupView.vue** - Fully migrated, no issues
### **Not Analyzed (1 file)**:1index.ts** - Needs individual analysis
## Impact on Initial Assessment
### **Accuracy**:753ed files correctly identified)
- **Correctly Identified**: MembersList.vue, ContactsView.vue, databaseUtil.ts
- **False Positive**: OnboardMeetingSetupView.vue
### **Severity Adjustment**:
- **Critical Issues**: Reduced from3to 2 **Legacy Patterns**: Confirmed in databaseUtil.ts (expected)
- **Overall Impact**: Less severe than initially assessed
## Recommendations
### **Immediate Actions**:
1. **Complete notification migration** for MembersList.vue (2 calls)
2. **Complete notification migration** for ContactsView.vue (4 calls)
3**Analyze index.ts** to determine if it has issues
### **Tool Improvements**:
1. **Enhanced validation script** should exclude helper setup lines from `$notify()` detection
2. **Better pattern matching** to distinguish between helper setup and actual usage
3ext-aware analysis** to identify legitimate complex modal dialogs
### **Migration Strategy**:
1. **Focus on the2omplete migrations**
2. **Consider complex modal dialogs** as legitimate exceptions to helper migration
3*Plan databaseUtil.ts cleanup** for final migration phase
## Conclusion
Our initial assessment was **mostly accurate** but had one false positive. The merge did preserve migration infrastructure well, with only 2 components having legitimate incomplete notification migrations. The issues are less severe than initially thought, but still require attention to complete the migration properly.
**Next Steps**: Focus on completing the2plete notification migrations and improving our validation tools to reduce false positives.

View File

@@ -126,7 +126,7 @@ this.allMyDids = (await retrieveAllAccountsMetadata()).map(
(account) => account.did,
);
// After
// After
this.allMyDids = (await this.$getAllAccounts()).map(
(account) => account.did,
);

View File

@@ -0,0 +1,274 @@
# True Issues Analysis - Detailed Breakdown
**Date**: 2025-7
**Analysis Method**: Direct file inspection and code review
**Purpose**: Provide detailed analysis of each true issue identified
## Executive Summary
After systematic analysis of each identified issue, I found that **2 components have legitimate incomplete notification migrations** and **2 files have expected legacy logging patterns**. The issues are less severe than initially assessed, with most being either legitimate complex modal dialogs or expected legacy patterns during migration.
## Issue 1 MembersList.vue - Complex Modal Dialogs
### **Status**: ✅ **LEGITIMATE COMPLEX MODAL** - No Action Required
**Location**: Lines 380395
**Issue Type**: Direct `$notify()` calls in complex modal dialogs
### **Detailed Analysis**:
#### **First Modal (Line 380)**:
```typescript
this.$notify({
group: modal,
type: confirm,
title: NOTIFY_ADD_CONTACT_FIRST.title,
text: NOTIFY_ADD_CONTACT_FIRST.text,
yesText: NOTIFY_ADD_CONTACT_FIRST.yesText,
noText: NOTIFY_ADD_CONTACT_FIRST.noText,
onYes: async () => {
await this.addAsContact(decrMember);
await this.toggleAdmission(decrMember);
},
onNo: async () => {
// Nested modal call
this.$notify({...});
},
}, TIMEOUTS.MODAL);
```
#### **Second Modal (Line 395)**:
```typescript
this.$notify({
group: modal,
type: confirm,title: NOTIFY_CONTINUE_WITHOUT_ADDING.title,
text: NOTIFY_CONTINUE_WITHOUT_ADDING.text,
yesText: NOTIFY_CONTINUE_WITHOUT_ADDING.yesText,
onYes: async () => [object Object] await this.toggleAdmission(decrMember);
},
onCancel: async () => {
// Do nothing, effectively canceling the operation
},
}, TIMEOUTS.MODAL);
```
### **Why These Are Legitimate**:1**Nested Callbacks**: The first modal has an `onNo` callback that triggers a second modal2Complex Flow Logic**: The modals implement a multi-step confirmation process
3Custom Button Text**: Uses constants but with custom `yesText`, `noText` properties
4. **Async Operations**: Both callbacks perform async operations (`addAsContact`, `toggleAdmission`)
5. **State Management**: The modals manage complex state transitions
### **Migration Assessment**: ❌ **NOT RECOMMENDED**
These modals cannot be easily converted to helper methods because:
- Helper methods don't support nested callbacks
- The complex flow logic requires custom modal configuration
- The async operations in callbacks need custom handling
### **Recommendation**: ✅ **KEEP AS IS**
These are legitimate complex modal dialogs that should remain as raw `$notify()` calls. They already use notification constants and follow best practices.
---
## Issue2: ContactsView.vue - Mixed Notification Patterns
### **Status**: ⚠️ **INCOMPLETE MIGRATION** - Action Required
**Location**: Lines 4108323208
**Issue Type**: Direct `$notify()` calls that can be migrated
### **Detailed Analysis**:
#### **Modal 1 (Line 410imple Confirmation**:
```typescript
this.$notify({
group: modal,
type: confirm",
title:They're Added To Your List",
text: Would you like to go to the main page now?",
onYes: async () => [object Object] this.$router.push({ name: home" });
},
}, -1);
```
**Migration Potential**: ✅ **EASY** - Simple confirmation with single callback
#### **Modal 2 (Line 832egistration Prompt**:
```typescript
this.$notify({
group: modal,
type: confirm",
title: Register,text: "Do you want to register them?",
onCancel: async (stopAsking?: boolean) => {
await this.handleRegistrationPromptResponse(stopAsking);
},
onNo: async (stopAsking?: boolean) => {
await this.handleRegistrationPromptResponse(stopAsking);
},
onYes: async () => {
await this.register(newContact);
},
promptToStopAsking: true,
}, -1);
```
**Migration Potential**: ⚠️ **COMPLEX** - Has `promptToStopAsking` and multiple callbacks
#### **Modal 33 Unconfirmed Hours Warning**:
```typescript
this.$notify({
group: modal,
type: confirm",
title:Delete,
text: message, // Dynamic message about unconfirmed hours
onNo: async () => {
this.showGiftedDialog(giverDid, recipientDid);
},
onYes: async () => [object Object] this.$router.push({
name: "contact-amounts",
query: { contactDid: giverDid },
});
},
}, -1);
```
**Migration Potential**: ⚠️ **COMPLEX** - Dynamic message generation
#### **Modal 41208Onboarding Meeting**:
```typescript
this.$notify({
group: modal,
type: confirm",
title: "Onboarding Meeting",
text: Would you like to start a new meeting?",
onYes: async () => [object Object] this.$router.push({ name: "onboard-meeting-setup" });
},
yesText: Start New Meeting",
onNo: async () => [object Object] this.$router.push({ name: "onboard-meeting-list" });
},
noText: "Join Existing Meeting,
}, -1);
```
**Migration Potential**: ⚠️ **COMPLEX** - Custom button text
### **Migration Strategy**:
1 **Modal 1**: ✅ **Easy migration** - Convert to `this.notify.confirm()`2 **Modal 2**: ❌ **Keep as is** - Complex with `promptToStopAsking`3 **Modal 3**: ❌ **Keep as is** - Dynamic message generation4 **Modal 4**: ❌ **Keep as is** - Custom button text
### **Recommendation**: ⚠️ **PARTIAL MIGRATION**
Only Modal 1 can be easily migrated. The others are legitimate complex modals.
---
## Issue 3 databaseUtil.ts - Legacy Logging Patterns
### **Status**: ✅ **EXPECTED LEGACY PATTERN** - No Action Required
**Location**: Throughout the file
**Issue Type**: 15+ `logConsoleAndDb()` calls
### **Detailed Analysis**:
#### **Function Definition (Line 325)**:
```typescript
export async function logConsoleAndDb(
message: string,
isError = false,
): Promise<void> {
if (isError) {
logger.error(message);
} else {
logger.log(message);
}
await logToDb(message, isError ? "error" : "info);
}
```
#### **Usage Examples**:
- Line 235: Error logging in `retrieveSettingsForActiveAccount()`
- Line 502: Debug logging in `debugSettingsData()`
- Line51059e debug statements
### **Why This Is Expected**:
1. **Migration Phase**: This file is intentionally kept during migration for backward compatibility
2. **Function Definition**: Contains the legacy function that other files may still use
3. **Debug Functions**: Many calls are in debug/development functions
4. **Gradual Migration**: This will be cleaned up in the final migration phase
### **Migration Assessment**: ✅ **PLANNED FOR CLEANUP**
This is expected during the migration process and will be addressed in the final cleanup phase.
### **Recommendation**: ✅ **KEEP AS IS** - Address in final cleanup
---
## Issue 4: index.ts - Legacy Logging Pattern
### **Status**: ✅ **EXPECTED LEGACY PATTERN** - No Action Required
**Location**: Line 240
**Issue Type**: 1logConsoleAndDb()` call
### **Detailed Analysis**:
#### **Usage (Line 240)**:
```typescript
logConsoleAndDb("Error processing secret & encrypted accountsDB.", error);
```
#### **Function Export (Line 305)**:
```typescript
export async function logConsoleAndDb(
```
### **Why This Is Expected**:
1. **Database Module**: This file is part of the database module thats being migrated
2. **Error Handling**: The call is in error handling code
3. **Consistent Pattern**: Follows the same pattern as databaseUtil.ts
### **Migration Assessment**: ✅ **PLANNED FOR CLEANUP**
This will be addressed when the database module migration is completed.
### **Recommendation**: ✅ **KEEP AS IS** - Address in final cleanup
---
## Summary of True Issues
### **Issues Requiring Action (1)**:1. **ContactsView.vue Modal 1** - Simple confirmation dialog (easy migration)
### **Issues That Are Legitimate (3:
1 **MembersList.vue** - Complex modal dialogs (keep as is)2. **ContactsView.vue Modals 2-4* - Complex modals (keep as is)3 **databaseUtil.ts** - Expected legacy patterns (cleanup phase)4ex.ts** - Expected legacy patterns (cleanup phase)
### **Impact Assessment**:
- **Actual Migration Work**: 1 simple modal conversion
- **False Positives**:3t of 4 issues were legitimate
- **Overall Severity**: Much lower than initially assessed
## Recommendations
### **Immediate Actions**:
1. **Migrate ContactsView.vue Modal 1** to use `this.notify.confirm()`
2. **Update validation scripts** to better identify legitimate complex modals
3. **Document complex modal patterns** for future reference
### **Tool Improvements**:
1. **Enhanced detection** for complex modal patterns
2ext-aware analysis** to distinguish legitimate vs incomplete migrations
3. **Better documentation** of migration exceptions
### **Migration Strategy**:
1. **Focus on simple migrations** that can be easily converted
2. **Accept complex modals** as legitimate exceptions
3. **Plan legacy cleanup** for final migration phase
## Conclusion
The merge was **highly successful** in preserving migration infrastructure. Only 1 out of 4 identified issues actually requires migration work. The remaining issues are either legitimate complex modal dialogs or expected legacy patterns during the migration process.
**Next Steps**: Complete the single simple modal migration and improve validation tools to reduce false positives in future assessments.