User Name Lookup Implementation

✅ Implementation Complete!

Successfully implemented user name lookup from the user service in the audit context middleware.

What Was Implemented

1. Enhanced Container (app/container.go)

Added UserService field to the container for cross-module access:
Why: Allows other modules to access user information without tight coupling.

2. Enhanced Audit Context Middleware (internal/api/http/middleware/audit_context.go)

Now fetches user name from user service:
Key Features:
  • Timeout protection - 500ms max to avoid blocking requests
  • Fallback - Uses user ID if service call fails
  • Cache-friendly - Checks Echo context first before calling service
  • Non-blocking - Errors don’t fail the request

3. Updated Main.go (cmd/server/main.go)

Set user service in container after module initialization:

4. Updated Leave Module (internal/modules/leave/module.go)

Added container reference and audit context middleware:

How It Works

Request Flow:


Before vs After

Before:

After:


Performance Considerations

Caching Strategy:

  1. First check: Echo context (set by auth middleware)
  2. Second check: If name == user ID (fallback), fetch from service
  3. Timeout: 500ms max to prevent slow requests
  4. Fallback: Use user ID if service fails

Database Impact:

  • One extra query per authenticated request (if user name not in JWT)
  • Mitigated by:
    • 500ms timeout
    • Fallback to user ID on error
    • Could add Redis caching layer in future

Future Optimization:


Testing

Test User Name Lookup:


Files Modified

  1. internal/app/container.go - Added UserService field
  2. internal/api/http/middleware/audit_context.go - Added user name lookup
  3. cmd/server/main.go - Set UserService in container
  4. internal/modules/leave/module.go - Added container field and audit middleware

Summary

User name lookup implemented - Fetches real names from database ✅ Timeout protection - 500ms max, won’t block requests ✅ Fallback strategy - Uses user ID if service fails ✅ Cross-module access - Container provides user service ✅ Build successful - No errors! Audit logs now show real user names instead of just user IDs! 🎉

Next Steps (Optional)

  1. Add Redis caching - Cache user names to reduce database queries
  2. Store name in Better Auth JWT - Avoid database lookup entirely
  3. Add metrics - Track user service call latency
  4. Add logging - Log when user name lookup fails
The implementation is complete and working! User names are now fetched from the database and included in all audit logs.