136 lines
6.0 KiB
Go
136 lines
6.0 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
type IntegrationKey struct {
|
|
ID uint64 `json:"id"`
|
|
AdministratorID uint64 `json:"administratorId"`
|
|
Name string `json:"name"`
|
|
Prefix string `json:"prefix"`
|
|
Scopes []string `json:"scopes"`
|
|
ExpiresAt time.Time `json:"expiresAt"`
|
|
RevokedAt *time.Time `json:"revokedAt"`
|
|
LastUsedAt *time.Time `json:"lastUsedAt"`
|
|
WebhookURL string `json:"webhookURL"`
|
|
WebhookSecret []byte `json:"-"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
}
|
|
|
|
const integrationFields = "k.id,k.administrator_id,k.name,k.token_prefix,k.scopes_json,k.expires_at,k.revoked_at,k.last_used_at,k.webhook_url,k.webhook_secret_cipher,k.created_at"
|
|
|
|
func scanIntegrationKey(row rowScanner) (IntegrationKey, error) {
|
|
var v IntegrationKey
|
|
var raw []byte
|
|
e := row.Scan(&v.ID, &v.AdministratorID, &v.Name, &v.Prefix, &raw, &v.ExpiresAt, &v.RevokedAt, &v.LastUsedAt, &v.WebhookURL, &v.WebhookSecret, &v.CreatedAt)
|
|
if e == nil {
|
|
e = json.Unmarshal(raw, &v.Scopes)
|
|
}
|
|
return v, e
|
|
}
|
|
func (s *Store) IntegrationKeys(ctx context.Context) ([]IntegrationKey, error) {
|
|
rows, e := s.db.QueryContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k ORDER BY k.id DESC LIMIT 100")
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer rows.Close()
|
|
out := []IntegrationKey{}
|
|
for rows.Next() {
|
|
v, e := scanIntegrationKey(rows)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
out = append(out, v)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (s *Store) IntegrationKeyByToken(ctx context.Context, hash string) (IntegrationKey, error) {
|
|
return scanIntegrationKey(s.db.QueryRowContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.token_hash=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.role='admin' AND u.status='active'", hash))
|
|
}
|
|
func (s *Store) IntegrationKeyActive(ctx context.Context, id uint64) bool {
|
|
var v bool
|
|
e := s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.id=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin')", id).Scan(&v)
|
|
return e == nil && v
|
|
}
|
|
func (s *Store) CreateIntegrationKey(ctx context.Context, v IntegrationKey, hash string) (uint64, error) {
|
|
raw, _ := json.Marshal(v.Scopes)
|
|
r, e := s.db.ExecContext(ctx, "INSERT INTO integration_keys(administrator_id,name,token_hash,token_prefix,scopes_json,expires_at,webhook_url,webhook_secret_cipher) VALUES(?,?,?,?,?,?,?,?)", v.AdministratorID, v.Name, hash, v.Prefix, raw, v.ExpiresAt, v.WebhookURL, v.WebhookSecret)
|
|
if e != nil {
|
|
return 0, e
|
|
}
|
|
id, _ := r.LastInsertId()
|
|
return uint64(id), nil
|
|
}
|
|
func (s *Store) RevokeIntegrationKey(ctx context.Context, id uint64) error {
|
|
_, e := s.db.ExecContext(ctx, "UPDATE integration_keys SET revoked_at=COALESCE(revoked_at,UTC_TIMESTAMP()) WHERE id=?", id)
|
|
return e
|
|
}
|
|
func (s *Store) TouchIntegrationKey(ctx context.Context, id uint64) {
|
|
_, _ = s.db.ExecContext(ctx, "UPDATE integration_keys SET last_used_at=UTC_TIMESTAMP() WHERE id=?", id)
|
|
}
|
|
func (s *Store) BatchIntegrationKey(ctx context.Context, batch uint64) (uint64, error) {
|
|
var id uint64
|
|
e := s.db.QueryRowContext(ctx, "SELECT COALESCE(integration_key_id,0) FROM admin_batches WHERE id=?", batch).Scan(&id)
|
|
return id, e
|
|
}
|
|
|
|
type IntegrationWebhook struct {
|
|
ID uint64 `json:"id"`
|
|
EventID string `json:"eventId"`
|
|
KeyID uint64 `json:"keyId"`
|
|
BatchID uint64 `json:"batchId"`
|
|
State string `json:"state"`
|
|
Attempts int `json:"attempts"`
|
|
NextAttempt time.Time `json:"nextAttempt"`
|
|
Status int `json:"status"`
|
|
LastError string `json:"lastError"`
|
|
URL string `json:"-"`
|
|
Secret []byte `json:"-"`
|
|
Prefix string `json:"-"`
|
|
}
|
|
|
|
func (s *Store) QueueIntegrationWebhooks(ctx context.Context) error {
|
|
_, e := s.db.ExecContext(ctx, `INSERT IGNORE INTO integration_webhooks(event_id,key_id,batch_id,next_attempt_at) SELECT LOWER(REPLACE(UUID(),'-','')),k.id,b.id,UTC_TIMESTAMP() FROM admin_batches b JOIN integration_keys k ON k.id=b.integration_key_id WHERE b.state IN ('completed','partial') AND k.webhook_url<>'' AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP()`)
|
|
return e
|
|
}
|
|
func (s *Store) IntegrationWebhooks(ctx context.Context, due bool) ([]IntegrationWebhook, error) {
|
|
query := `SELECT w.id,w.event_id,w.key_id,w.batch_id,w.state,w.attempts,w.next_attempt_at,w.last_status,w.last_error,k.webhook_url,k.webhook_secret_cipher,k.token_prefix FROM integration_webhooks w JOIN integration_keys k ON k.id=w.key_id`
|
|
if due {
|
|
query += ` JOIN users u ON u.id=k.administrator_id WHERE w.state='pending' AND w.attempts<8 AND w.next_attempt_at<=UTC_TIMESTAMP() AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin' ORDER BY w.id LIMIT 10`
|
|
} else {
|
|
query += " ORDER BY w.id DESC LIMIT 100"
|
|
}
|
|
rows, e := s.db.QueryContext(ctx, query)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer rows.Close()
|
|
out := []IntegrationWebhook{}
|
|
for rows.Next() {
|
|
var v IntegrationWebhook
|
|
if e = rows.Scan(&v.ID, &v.EventID, &v.KeyID, &v.BatchID, &v.State, &v.Attempts, &v.NextAttempt, &v.Status, &v.LastError, &v.URL, &v.Secret, &v.Prefix); e != nil {
|
|
return nil, e
|
|
}
|
|
out = append(out, v)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (s *Store) FinishIntegrationWebhook(ctx context.Context, v IntegrationWebhook, delivered bool, status int) error {
|
|
state := "pending"
|
|
if delivered {
|
|
state = "delivered"
|
|
} else if v.Attempts+1 >= 8 {
|
|
state = "failed"
|
|
}
|
|
delay := time.Duration(1<<uint(v.Attempts)) * time.Minute
|
|
message := ""
|
|
if !delivered {
|
|
message = "回调请求失败或未返回 2xx"
|
|
}
|
|
_, e := s.db.ExecContext(ctx, "UPDATE integration_webhooks SET state=?,attempts=attempts+1,last_status=?,last_error=?,next_attempt_at=?,delivered_at=IF(?,UTC_TIMESTAMP(),NULL) WHERE id=? AND attempts=?", state, status, message, time.Now().UTC().Add(delay), delivered, v.ID, v.Attempts)
|
|
return e
|
|
}
|