35 lines
1.0 KiB
Go
35 lines
1.0 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
|
|
"chat-agent-system/internal/controlcenter/store"
|
|
)
|
|
|
|
// AgentAuthenticator resolves bearer tokens against cc_agents.token_hash,
|
|
// with a small in-memory cache populated lazily.
|
|
type AgentAuthenticator struct {
|
|
st *store.Store
|
|
}
|
|
|
|
// Authenticate returns the agent name when the token is valid.
|
|
func (a *AgentAuthenticator) Authenticate(ctx context.Context, token string) (string, bool) {
|
|
var name string
|
|
err := a.st.Pool.QueryRow(ctx,
|
|
`SELECT name FROM cc_agents WHERE token_hash = $1`, TokenHash(token)).Scan(&name)
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
return name, true
|
|
}
|
|
|
|
// RegisterAgent creates (or rotates) an agent token; returns the plaintext
|
|
// token exactly once.
|
|
func RegisterAgent(ctx context.Context, st *store.Store, name, kind, token string) error {
|
|
_, err := st.Pool.Exec(ctx,
|
|
`INSERT INTO cc_agents (name, kind, token_hash) VALUES ($1,$2,$3)
|
|
ON CONFLICT (name) DO UPDATE SET kind = EXCLUDED.kind, token_hash = EXCLUDED.token_hash`,
|
|
name, kind, TokenHash(token))
|
|
return err
|
|
}
|