Skip to content

feat(lvt): redesign gen auth for LiveTemplate v0.5.1#5

Merged
adnaan merged 1 commit intomainfrom
feat/lvt-gen-auth-v0.5.1
Nov 30, 2025
Merged

feat(lvt): redesign gen auth for LiveTemplate v0.5.1#5
adnaan merged 1 commit intomainfrom
feat/lvt-gen-auth-v0.5.1

Conversation

@adnaan
Copy link
Copy Markdown
Contributor

@adnaan adnaan commented Nov 30, 2025

Summary

Migrate lvt gen auth from v0.4.x workaround patterns to new v0.5.1 ActionContext HTTP APIs. Password auth is now enabled by default and uses modern, clean API patterns.

Changes

1. Auth Handler Template (handler.go.tmpl)

  • ✅ Remove manual ResponseWriter/Request extraction from state struct
  • ✅ Use ctx.SetCookie() instead of http.SetCookie(s.httpWriter, ...)
  • ✅ Use ctx.Redirect() instead of http.Redirect(s.httpWriter, s.httpRequest, ...)
  • ✅ Remove httpWriter and httpRequest fields from AuthState

2. Re-enable Password Auth (auth.go)

  • ✅ Remove outdated v0.4.x compatibility warning (lines 65-75)
  • ✅ Password authentication enabled by default
  • ✅ No more forced disabling with confusing warning

3. Documentation (SKILL.md)

  • ✅ Add comprehensive "LiveTemplate v0.5.1+ HTTP APIs" section
  • ✅ Document all ActionContext HTTP methods:
    • SetCookie(), GetCookie(), DeleteCookie()
    • Redirect(), SetHeader(), GetHeader(), IsHTTP()
  • ✅ Add security best practices for cookies and redirects
  • ✅ Add error handling examples

4. Tests (auth_test.go)

  • ✅ Update comment from "password.go is NOT generated" to "Password auth is enabled by default in v0.5.1+"
  • ✅ Add internal/shared/password/password.go to expected generated files
  • ✅ All tests passing

Benefits

Modern API Usage: Generated auth code uses clean ActionContext HTTP methods instead of workarounds

🔒 Security: Built-in redirect validation (prevents open redirects) and proper cookie security flags

🎯 Developer Experience: Password auth works out-of-the-box, no more confusing warnings

📚 Documentation: Clear examples of all v0.5.1 HTTP capabilities

Test Results

All auth-related tests passing:

=== RUN   TestAuth_Flags
--- PASS: TestAuth_Flags (0.00s)
=== RUN   TestAuthCommand_Integration
--- PASS: TestAuthCommand_Integration (0.01s)
=== RUN   TestAuthCommand_CustomNames
--- PASS: TestAuthCommand_CustomNames (0.01s)
PASS
ok  	github.com/livetemplate/lvt/commands	0.450s

Generated Files Verified

  • internal/app/auth/auth.go (with v0.5.1 APIs)
  • internal/shared/password/password.go (now generated by default)
  • internal/shared/email/email.go
  • internal/database/migrations/*_create_auth_tables.sql
  • ✅ E2E test file included

Breaking Changes

None - this is backward compatible. Apps using the generated code will automatically benefit from the new APIs when they upgrade to livetemplate v0.5.1+.

Related

  • Requires livetemplate v0.5.1+ (ActionContext HTTP APIs)
  • Examples repo will be updated separately to reference v0.5.1

Migrate `lvt gen auth` from v0.4.x workaround patterns to new v0.5.1
ActionContext HTTP APIs. Password auth is now enabled by default.

**Changes:**

1. **Auth Handler Template** (handler.go.tmpl)
   - Remove manual ResponseWriter/Request extraction
   - Use ctx.SetCookie() instead of http.SetCookie(s.httpWriter, ...)
   - Use ctx.Redirect() instead of http.Redirect(s.httpWriter, s.httpRequest, ...)
   - Remove httpWriter and httpRequest fields from AuthState

2. **Re-enable Password Auth** (auth.go)
   - Remove outdated v0.4.x compatibility warning
   - Password authentication enabled by default

3. **Documentation** (SKILL.md)
   - Add comprehensive LiveTemplate v0.5.1+ HTTP APIs section
   - Document SetCookie, GetCookie, DeleteCookie, Redirect APIs
   - Add security best practices and error handling examples

4. **Tests** (auth_test.go)
   - Update comment about password.go generation
   - Add password.go to expected generated files

**Benefits:**
- Modern, clean ActionContext API usage
- Built-in redirect validation and cookie security
- Better developer experience with password auth working out-of-box
- Clear documentation of v0.5.1 capabilities

All auth tests passing ✅

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link
Copy Markdown

claude bot commented Nov 30, 2025

Pull Request Review: Migrate lvt gen auth to LiveTemplate v0.5.1

Summary

This PR successfully migrates the auth generation from v0.4.x workarounds to the new v0.5.1 ActionContext HTTP APIs. The changes are well-structured and the migration is clean. Overall, this is a solid improvement that modernizes the codebase. ✅


Code Quality & Best Practices

✅ Strengths

  1. Clean API Migration: The removal of manual httpWriter and httpRequest extraction in favor of ctx.SetCookie() and ctx.Redirect() is a significant improvement in code clarity
  2. Consistent Error Handling: Good use of error checking after SetCookie() and Redirect() calls (handler.go.tmpl:245-265)
  3. Good Documentation: The new SKILL.md section comprehensively documents the v0.5.1 APIs with clear examples
  4. Test Coverage: Tests properly verify that password.go is now generated (auth_test.go:76-78)
  5. Minimal Scope: The PR focuses on one specific improvement without unnecessary changes

⚠️ Areas for Improvement

1. Cookie Security Flag Issue (Security - High Priority)

Location: internal/kits/system/multi/templates/auth/handler.go.tmpl:252

Secure:   true,

Issue: The Secure: true flag is hardcoded, which will break local development over HTTP. This cookie won't be sent in local dev (http://localhost), making authentication fail.

Recommendation:

// Option 1: Make it configurable via baseURL
Secure:   strings.HasPrefix(s.baseURL, "https://"),

// Option 2: Add environment-based configuration
Secure:   os.Getenv("ENV") == "production",

// Option 3: Add a field to the state struct
Secure:   s.secureCookies, // Set in New{{.StructName}}State

Impact: Without this fix, developers will be confused when auth doesn't work locally. This affects lines 252, 370, and 580.


Potential Bugs & Issues

1. Version Mismatch (Medium Priority)

Location: go.mod:5

require github.com/livetemplate/livetemplate v0.4.1

Issue: The PR migrates to v0.5.1 APIs but go.mod still references v0.4.1. This will cause runtime errors when ctx.SetCookie() and ctx.Redirect() are called.

Questions:

  • Is there a v0.5.1 release of livetemplate that includes these APIs?
  • Should this PR update the dependency version, or does that come separately?
  • Are the new APIs backward compatible with v0.4.1?

Recommendation: Either update the dependency version in this PR or add a note in the PR description about version requirements.


2. Error Handling Pattern (Low Priority)

Location: handler.go.tmpl:254-257

if err := ctx.SetCookie(...); err != nil {
    s.Error = "Login failed"
    log.Printf("Set cookie error: %v", err)
    return nil  // Returns nil instead of err
}

Issue: Errors are logged and swallowed rather than returned. While this may be intentional for user experience (showing generic error messages), it could make debugging harder.

Recommendation: Consider adding debug logging or metrics to track these failures in production. The current pattern is acceptable but ensure monitoring is in place.


3. Missing Context Cancellation (Low Priority)

Location: handler.go.tmpl:140, 220, etc.

user, err := s.queries.Get{{.StructName}}ByEmail(context.Background(), input.Email)

Issue: Uses context.Background() instead of request-scoped context. If requests are cancelled, database queries will continue running.

Recommendation:

// Extract request context from ActionContext if available
user, err := s.queries.Get{{.StructName}}ByEmail(ctx.Context(), input.Email)

Check if livetemplate.ActionContext provides access to the request context.


Performance Considerations

✅ Good Practices

  1. Efficient Redirect: Using http.StatusSeeOther (303) is correct for POST-redirect-GET pattern
  2. Proper Cookie Settings: HttpOnly: true and SameSite: http.SameSiteStrictMode are security-focused but don't impact performance

📝 Observations

  • No obvious performance issues
  • Database queries are straightforward and not N+1 prone
  • Token generation uses crypto/rand which is appropriately secure

Security Concerns

✅ Security Strengths

  1. HttpOnly Cookies: ✅ Prevents XSS attacks (line 251)
  2. SameSite Strict: ✅ Prevents CSRF attacks (line 253)
  3. Bcrypt Password Hashing: ✅ Already in place from previous implementation
  4. Redirect Validation: ✅ Documentation mentions validation of redirect URLs (SKILL.md:480-482)
  5. Token Expiration: ✅ 30-day session timeout is reasonable (line 250)

⚠️ Security Issues

1. Secure Cookie Flag (Already mentioned above)

Severity: High for production, but fixable
Current: Always true
Risk: Breaks local dev; may lead developers to disable it entirely

2. Cookie Path is Root (Low)

Location: handler.go.tmpl:249

Path:     "/",

Issue: Cookie is sent with all requests to the site. If auth is only on /auth, this is unnecessarily broad.
Recommendation: Consider Path: "/auth" or make it configurable. Current approach is acceptable for most use cases.

3. No Rate Limiting Mentioned (Low)

Observation: No rate limiting on login attempts in the generated code. This is typically handled at middleware level, but should be documented.
Recommendation: Add a note in SKILL.md about implementing rate limiting for auth endpoints.


Test Coverage

✅ Good Coverage

  1. Integration Test: Verifies password.go is generated (auth_test.go:76-78) ✅
  2. Custom Names Test: Validates table/struct naming (auth_test.go:134-257) ✅
  3. Flag Validation: Tests mutual exclusivity of auth methods (auth_test.go:10-42) ✅

📝 Missing Tests

  1. No runtime tests: Tests verify file generation but don't test the actual HTTP cookie/redirect functionality
  2. No API version check: No test verifying that v0.5.1 APIs are actually available
  3. No error path tests: What happens when SetCookie() fails? When Redirect() fails?

Recommendation: Consider adding:

// Example test structure
func TestAuthHandlerCookies(t *testing.T) {
    // Test that SetCookie is called with correct parameters
    // Test that Redirect works correctly
    // Test error cases (if APIs are not available)
}

Documentation Quality

✅ Excellent Documentation

  1. Comprehensive SKILL.md Section: The new v0.5.1 API documentation is thorough and well-structured
  2. Clear Examples: Code examples show all major use cases
  3. Security Best Practices: Dedicated section on cookie security and redirect validation
  4. Error Handling Examples: Documents expected errors

📝 Suggestions

  1. Version Requirements: Add a note at the top of SKILL.md stating "Requires livetemplate v0.5.1+"
  2. Migration Guide: Consider adding a section on upgrading from v0.4.x patterns
  3. Local Development: Document the cookie security issue and how to handle local vs production

Recommendations Summary

🔴 Must Fix Before Merge

  1. Secure Cookie Flag: Make configurable for local development
  2. Version Dependency: Clarify/update livetemplate version requirement

🟡 Should Consider

  1. Context Cancellation: Use request context instead of Background()
  2. Documentation: Add version requirement note to SKILL.md
  3. Rate Limiting: Document need for rate limiting on auth endpoints

🟢 Nice to Have

  1. Runtime Tests: Add tests for actual HTTP functionality
  2. Cookie Path: Consider making configurable
  3. Migration Guide: Help v0.4.x users upgrade

Verdict

This is a well-executed migration that successfully modernizes the auth generation code. The changes are focused, well-tested at the generation level, and properly documented.

Recommendation: ✅ Approve with minor changes

The cookie security flag issue should be addressed before merging to prevent local development problems. The version dependency question should also be clarified. Once those are resolved, this is ready to merge.

Great work on the clean API migration and comprehensive documentation! 🎉


Reviewed by: Claude Code Assistant
Review Date: 2025-11-30

@adnaan adnaan merged commit d5105fb into main Nov 30, 2025
7 checks passed
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR migrates the lvt gen auth command from v0.4.x workaround patterns to LiveTemplate v0.5.1's native ActionContext HTTP APIs. The changes enable password authentication by default and modernize the generated auth code to use clean, built-in methods for cookies and redirects instead of manual ResponseWriter/Request extraction.

Key changes:

  • Auth handler template now uses ctx.SetCookie() and ctx.Redirect() instead of manual HTTP operations
  • Password authentication re-enabled by default (removed temporary v0.4.x compatibility warning)
  • Comprehensive documentation added for all v0.5.1 HTTP APIs with security best practices

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
internal/kits/system/multi/templates/auth/handler.go.tmpl Migrated handleLogin to use ActionContext HTTP APIs; removed httpWriter/httpRequest state fields
commands/auth.go Removed v0.4.x compatibility warning and forced password auth disabling
commands/auth_test.go Updated test expectations to include password.go in generated files
commands/claude_resources/skills/gen-auth/SKILL.md Added comprehensive documentation for v0.5.1 HTTP APIs with security best practices and error handling examples

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