feat(user): wire audit recorder into login/logout

This commit is contained in:
2026-04-28 23:02:09 +08:00
parent f42b88e57d
commit 62cf9ffa0c
3 changed files with 86 additions and 18 deletions
+38 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/yan1h/agent-coding-workflow/internal/audit"
"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
)
@@ -79,7 +80,7 @@ func newServiceWithUser(t *testing.T, email, password string) (*service, *User)
require.NoError(t, err)
u := &User{ID: uuid.New(), Email: email, DisplayName: "Test", PasswordHash: hash}
repo.users[email] = u
svc := NewService(repo).(*service)
svc := NewService(repo, nil).(*service)
return svc, u
}
@@ -130,3 +131,39 @@ func TestLogout_RemovesSession(t *testing.T) {
require.NoError(t, err)
require.False(t, ok)
}
type spyAudit struct{ entries []audit.Entry }
func (s *spyAudit) Record(_ context.Context, e audit.Entry) error {
s.entries = append(s.entries, e)
return nil
}
func TestLogin_RecordsAudit(t *testing.T) {
repo := newFakeRepo()
hash, err := HashPassword("password123")
require.NoError(t, err)
repo.users["a@b.c"] = &User{ID: uuid.New(), Email: "a@b.c", DisplayName: "T", PasswordHash: hash}
spy := &spyAudit{}
svc := NewService(repo, spy)
_, _, err = svc.Login(context.Background(), "a@b.c", "password123", "127.0.0.1")
require.NoError(t, err)
require.Len(t, spy.entries, 1)
require.Equal(t, "user.login", spy.entries[0].Action)
require.Equal(t, "127.0.0.1", spy.entries[0].IP)
require.NotNil(t, spy.entries[0].UserID)
}
func TestLogout_RecordsAudit(t *testing.T) {
svc, _ := newServiceWithUser(t, "a@b.c", "password123")
// 先用 nil audit 走一遍 Login
tok, _, err := svc.Login(context.Background(), "a@b.c", "password123", "127.0.0.1")
require.NoError(t, err)
// 替换 audit recorder 注入 spy 后 Logout
spy := &spyAudit{}
svc.audit = spy
require.NoError(t, svc.Logout(context.Background(), tok))
require.Len(t, spy.entries, 1)
require.Equal(t, "user.logout", spy.entries[0].Action)
}