package store import ( "context" "time" "atlas9.dev/c/core" "atlas9.dev/c/core/dbi" "atlas9.dev/c/demo/bots" "atlas9.dev/c/demo/lib" ) type SqliteBotKeyStore struct { db dbi.DBI guard lib.Guard } var _ bots.KeyStore = (*SqliteBotKeyStore)(nil) func NewSqliteBotKeyStore(db dbi.DBI, guard lib.Guard) *SqliteBotKeyStore { return &SqliteBotKeyStore{db: db, guard: guard} } func (s *SqliteBotKeyStore) Create(ctx context.Context, key *bots.Key) error { if err := s.guard.Check(ctx, bots.Cap_BotKeys_Write, key.Tenant, ""); err != nil { return err } _, err := s.db.Exec(ctx, ` INSERT INTO bot_keys (id, tenant, bot, secret, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6) `, key.ID, key.Tenant, key.Bot, key.Secret, key.CreatedAt.Unix(), key.ExpiresAt.Unix()) return err } func (s *SqliteBotKeyStore) Get(ctx context.Context, tenant core.ID, keyID core.ID, out *bots.Key) error { if err := s.guard.Check(ctx, bots.Cap_BotKeys_Read, tenant, ""); err != nil { return err } var createdAt, expiresAt int64 err := dbi.Get(ctx, s.db, out, ` SELECT id, tenant, bot, secret, created_at, expires_at FROM bot_keys WHERE id = $1 `, keyID) if err != nil { return err } out.CreatedAt = time.Unix(createdAt, 0).UTC() out.ExpiresAt = time.Unix(expiresAt, 0).UTC() return nil } func (s *SqliteBotKeyStore) List(ctx context.Context, tenant core.ID, out *core.Page[bots.Key]) error { if err := s.guard.Check(ctx, bots.Cap_BotKeys_Read, tenant, ""); err != nil { return err } return dbi.Paginate(ctx, s.db, core.PageReq{}, out, func(k bots.Key) string { return k.ID.String() }, `SELECT id, tenant, bot, secret, created_at, expires_at FROM bot_keys WHERE tenant = $1 AND id > $cursor ORDER BY id LIMIT $limit`, tenant) } func (s *SqliteBotKeyStore) SetExpiration(ctx context.Context, tenant core.ID, keyID core.ID, expiration time.Time) error { if err := s.guard.Check(ctx, bots.Cap_BotKeys_Write, tenant, ""); err != nil { return err } _, err := s.db.Exec(ctx, `UPDATE bot_keys SET expires_at = $1 WHERE id = $2`, expiration.Unix(), keyID) return err }