Changeset 0.28.0.4 (#176)
This commit is contained in:
@@ -5,15 +5,19 @@ Cross-cutting admin operations that don't belong to a specific domain.
|
|||||||
### User Management
|
### User Management
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /admin/users → { "users": [...] }
|
GET /admin/users → { "users": [...], "total": N }
|
||||||
POST /admin/users ← { "username", "password", "email", "role" }
|
POST /admin/users ← { "username", "password", "email", "role" }
|
||||||
PUT /admin/users/:id/role ← { "role": "admin|user" }
|
PUT /admin/users/:id/role ← { "role": "admin|user" }
|
||||||
PUT /admin/users/:id/active ← { "active": false }
|
PUT /admin/users/:id/active ← { "is_active": false }
|
||||||
DELETE /admin/users/:id
|
DELETE /admin/users/:id
|
||||||
POST /admin/users/:id/reset-password ← { "new_password": "..." }
|
POST /admin/users/:id/reset-password ← { "password": "..." }
|
||||||
POST /admin/users/:id/vault/reset → destroys user's UEK (BYOK keys lost)
|
POST /admin/users/:id/vault/reset → destroys user's UEK (BYOK keys lost)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`PUT /admin/users/:id/role` refuses to demote the last remaining admin
|
||||||
|
(returns 409). `DELETE /admin/users/:id` also refuses if the target is
|
||||||
|
the last admin, and destroys the user's vault before deleting the row.
|
||||||
|
|
||||||
### Global Settings & Policies
|
### Global Settings & Policies
|
||||||
|
|
||||||
Settings are key-value pairs in `global_settings`. Policies are
|
Settings are key-value pairs in `global_settings`. Policies are
|
||||||
@@ -45,11 +49,14 @@ GET /settings/public
|
|||||||
"policies": {
|
"policies": {
|
||||||
"allow_registration": "true",
|
"allow_registration": "true",
|
||||||
"allow_user_byok": "true",
|
"allow_user_byok": "true",
|
||||||
"allow_user_personas": "true"
|
"allow_user_personas": "true",
|
||||||
|
"channel_retention_mode": "flexible"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Note: policy values are strings (`"true"` / `"false"`), not booleans.
|
||||||
|
|
||||||
### Banner Configuration
|
### Banner Configuration
|
||||||
|
|
||||||
The environment banner is stored as a single `global_config` entry
|
The environment banner is stored as a single `global_config` entry
|
||||||
@@ -104,20 +111,33 @@ GET /admin/vault/status → { "encryption_key_set", "user_vaults_co
|
|||||||
### Audit Log
|
### Audit Log
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /admin/audit?page=1&per_page=50&action=user.create&actor_id=uuid
|
GET /admin/audit?page=1&per_page=50&action=user.create&actor_id=uuid&resource_type=...
|
||||||
GET /admin/audit/actions → { "actions": ["user.create", "policy.update", ...] }
|
GET /admin/audit/actions → { "actions": ["user.create", "policy.update", ...] }
|
||||||
```
|
```
|
||||||
|
|
||||||
Audit entry:
|
The list endpoint returns a paginated envelope:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [...],
|
||||||
|
"total": 128,
|
||||||
|
"page": 1,
|
||||||
|
"per_page": 50
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Audit entry shape:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"id": "uuid",
|
"id": "uuid",
|
||||||
"actor_id": "uuid",
|
"actor_id": "uuid",
|
||||||
|
"actor_name": "admin",
|
||||||
"action": "user.create",
|
"action": "user.create",
|
||||||
"resource_type": "user",
|
"resource_type": "user",
|
||||||
"resource_id": "uuid",
|
"resource_id": "uuid",
|
||||||
"metadata": {},
|
"metadata": "{}",
|
||||||
|
"ip_address": "10.0.0.1",
|
||||||
"created_at": "..."
|
"created_at": "..."
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -126,13 +146,31 @@ Audit entry:
|
|||||||
|
|
||||||
```
|
```
|
||||||
GET /admin/usage → { "totals", "results" }
|
GET /admin/usage → { "totals", "results" }
|
||||||
GET /admin/usage/teams/:id → team-specific usage
|
GET /admin/usage/teams/:id → { "results": [...] }
|
||||||
GET /admin/usage/users/:id → user-specific usage
|
GET /admin/usage/users/:id → { "results": [...] }
|
||||||
GET /admin/pricing → { "data": [...] }
|
GET /admin/pricing → [ ... ]
|
||||||
PUT /admin/pricing ← { "provider", "model", "input_per_m", "output_per_m" }
|
PUT /admin/pricing ← { "provider_config_id", "model_id", "input_per_m", "output_per_m" }
|
||||||
DELETE /admin/pricing/:provider/:model
|
DELETE /admin/pricing/:provider_config_id/:model_id
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`GET /admin/pricing` returns a bare array (no envelope).
|
||||||
|
|
||||||
|
`PUT /admin/pricing` accepts the full `PricingEntry` shape:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"provider_config_id": "uuid",
|
||||||
|
"model_id": "gpt-4o",
|
||||||
|
"input_per_m": 2.50,
|
||||||
|
"output_per_m": 10.00,
|
||||||
|
"cache_create_per_m": 1.25,
|
||||||
|
"cache_read_per_m": 0.50,
|
||||||
|
"currency": "USD"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Pricing cannot be set for personal BYOK providers (403).
|
||||||
|
|
||||||
**Personal usage** (non-admin):
|
**Personal usage** (non-admin):
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -156,22 +194,22 @@ POST /admin/roles/:role/test ← test role permissions
|
|||||||
POST /admin/notifications/test-email
|
POST /admin/notifications/test-email
|
||||||
```
|
```
|
||||||
|
|
||||||
```json
|
No request body required. Sends a test email to the authenticated
|
||||||
{ "to": "admin@example.com" }
|
admin's own email address using the configured SMTP settings.
|
||||||
```
|
|
||||||
|
|
||||||
Sends a test email using the configured SMTP settings.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Archived Channels
|
### Archived Channels
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /admin/channels/archived → { "data": [...] }
|
GET /admin/channels/archived → { "channels": [...], "total", "page", "per_page", "retention_mode" }
|
||||||
DELETE /admin/channels/:id/purge → permanent delete (ignores retention)
|
DELETE /admin/channels/:id/purge → permanent delete (ignores retention)
|
||||||
```
|
```
|
||||||
|
|
||||||
**Auth:** Platform admin.
|
Both endpoints require platform admin auth. `GET` accepts
|
||||||
|
`?page=1&per_page=50` query parameters (max 100 per page).
|
||||||
|
`DELETE` verifies the channel is archived before purging and cleans
|
||||||
|
up associated file storage blobs.
|
||||||
|
|
||||||
### Surfaces Admin
|
### Surfaces Admin
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -17,6 +16,7 @@ import (
|
|||||||
"git.gobha.me/xcaliber/chat-switchboard/database"
|
"git.gobha.me/xcaliber/chat-switchboard/database"
|
||||||
"git.gobha.me/xcaliber/chat-switchboard/models"
|
"git.gobha.me/xcaliber/chat-switchboard/models"
|
||||||
"git.gobha.me/xcaliber/chat-switchboard/providers"
|
"git.gobha.me/xcaliber/chat-switchboard/providers"
|
||||||
|
"git.gobha.me/xcaliber/chat-switchboard/storage"
|
||||||
"git.gobha.me/xcaliber/chat-switchboard/store"
|
"git.gobha.me/xcaliber/chat-switchboard/store"
|
||||||
"git.gobha.me/xcaliber/chat-switchboard/tools/search"
|
"git.gobha.me/xcaliber/chat-switchboard/tools/search"
|
||||||
)
|
)
|
||||||
@@ -25,10 +25,11 @@ type AdminHandler struct {
|
|||||||
stores store.Stores
|
stores store.Stores
|
||||||
vault *crypto.KeyResolver
|
vault *crypto.KeyResolver
|
||||||
uekCache *crypto.UEKCache
|
uekCache *crypto.UEKCache
|
||||||
|
objStore storage.ObjectStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAdminHandler(s store.Stores, vault *crypto.KeyResolver, uekCache *crypto.UEKCache) *AdminHandler {
|
func NewAdminHandler(s store.Stores, vault *crypto.KeyResolver, uekCache *crypto.UEKCache, objStore storage.ObjectStore) *AdminHandler {
|
||||||
return &AdminHandler{stores: s, vault: vault, uekCache: uekCache}
|
return &AdminHandler{stores: s, vault: vault, uekCache: uekCache, objStore: objStore}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── User Management ─────────────────────────
|
// ── User Management ─────────────────────────
|
||||||
@@ -87,6 +88,10 @@ func (h *AdminHandler) CreateUser(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := h.stores.Users.Create(c.Request.Context(), user); err != nil {
|
if err := h.stores.Users.Create(c.Request.Context(), user); err != nil {
|
||||||
|
if database.IsUniqueViolation(err) {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "username or email already exists"})
|
||||||
|
return
|
||||||
|
}
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -105,6 +110,25 @@ func (h *AdminHandler) UpdateUserRole(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Guard: prevent demoting the last admin
|
||||||
|
if req.Role != models.UserRoleAdmin {
|
||||||
|
user, err := h.stores.Users.GetByID(c.Request.Context(), id)
|
||||||
|
if err != nil || user == nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.Role == models.UserRoleAdmin {
|
||||||
|
var adminCount int
|
||||||
|
database.DB.QueryRowContext(c.Request.Context(),
|
||||||
|
database.Q(`SELECT COUNT(*) FROM users WHERE role = $1`),
|
||||||
|
models.UserRoleAdmin).Scan(&adminCount)
|
||||||
|
if adminCount <= 1 {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "cannot demote the last admin"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := h.stores.Users.Update(c.Request.Context(), id, map[string]interface{}{"role": req.Role}); err != nil {
|
if err := h.stores.Users.Update(c.Request.Context(), id, map[string]interface{}{"role": req.Role}); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update role"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update role"})
|
||||||
return
|
return
|
||||||
@@ -215,6 +239,27 @@ func (h *AdminHandler) ResetVault(c *gin.Context) {
|
|||||||
|
|
||||||
func (h *AdminHandler) DeleteUser(c *gin.Context) {
|
func (h *AdminHandler) DeleteUser(c *gin.Context) {
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
|
// Guard: prevent deleting the last admin
|
||||||
|
user, err := h.stores.Users.GetByID(c.Request.Context(), id)
|
||||||
|
if err != nil || user == nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.Role == models.UserRoleAdmin {
|
||||||
|
var adminCount int
|
||||||
|
database.DB.QueryRowContext(c.Request.Context(),
|
||||||
|
database.Q(`SELECT COUNT(*) FROM users WHERE role = $1`),
|
||||||
|
models.UserRoleAdmin).Scan(&adminCount)
|
||||||
|
if adminCount <= 1 {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "cannot delete the last admin"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Destroy vault and personal BYOK keys before deleting the user row
|
||||||
|
h.destroyVault(c, id)
|
||||||
|
|
||||||
if err := h.stores.Users.Delete(c.Request.Context(), id); err != nil {
|
if err := h.stores.Users.Delete(c.Request.Context(), id); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete user"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete user"})
|
||||||
return
|
return
|
||||||
@@ -238,6 +283,17 @@ func (h *AdminHandler) ListGlobalSettings(c *gin.Context) {
|
|||||||
|
|
||||||
func (h *AdminHandler) GetGlobalSetting(c *gin.Context) {
|
func (h *AdminHandler) GetGlobalSetting(c *gin.Context) {
|
||||||
key := c.Param("key")
|
key := c.Param("key")
|
||||||
|
|
||||||
|
// If the key is a known policy, read from the policies table first
|
||||||
|
if _, ok := models.PolicyDefaults[key]; ok {
|
||||||
|
val, err := h.stores.Policies.Get(c.Request.Context(), key)
|
||||||
|
if err == nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{"key": key, "value": val})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Fall through to global_config if not found in policies
|
||||||
|
}
|
||||||
|
|
||||||
val, err := h.stores.GlobalConfig.Get(c.Request.Context(), key)
|
val, err := h.stores.GlobalConfig.Get(c.Request.Context(), key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "setting not found"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "setting not found"})
|
||||||
@@ -639,8 +695,7 @@ func (h *AdminHandler) fetchModelsForProvider(c *gin.Context, cfg *models.Provid
|
|||||||
func (h *AdminHandler) UpdateModelConfig(c *gin.Context) {
|
func (h *AdminHandler) UpdateModelConfig(c *gin.Context) {
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
var req struct {
|
var req struct {
|
||||||
Visibility *string `json:"visibility"`
|
Visibility *string `json:"visibility"`
|
||||||
DisplayName *string `json:"display_name"`
|
|
||||||
}
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
@@ -712,67 +767,28 @@ func (h *AdminHandler) GetStats(c *gin.Context) {
|
|||||||
// NOTE: ListAuditLog and ListAuditActions are in audit.go
|
// NOTE: ListAuditLog and ListAuditActions are in audit.go
|
||||||
|
|
||||||
func (h *AdminHandler) auditLog(c *gin.Context, action, resourceType, resourceID string, metadata interface{}) {
|
func (h *AdminHandler) auditLog(c *gin.Context, action, resourceType, resourceID string, metadata interface{}) {
|
||||||
userID, _ := c.Get("user_id")
|
// Convert interface{} metadata to map[string]interface{} for the shared helper
|
||||||
uid, _ := userID.(string)
|
var meta map[string]interface{}
|
||||||
|
|
||||||
var meta models.JSONMap
|
|
||||||
if metadata != nil {
|
if metadata != nil {
|
||||||
b, _ := json.Marshal(metadata)
|
b, _ := json.Marshal(metadata)
|
||||||
json.Unmarshal(b, &meta)
|
json.Unmarshal(b, &meta)
|
||||||
}
|
}
|
||||||
|
AuditLog(h.stores.Audit, c, action, resourceType, resourceID, meta)
|
||||||
entry := &models.AuditEntry{
|
|
||||||
ActorID: &uid,
|
|
||||||
Action: action,
|
|
||||||
ResourceType: resourceType,
|
|
||||||
ResourceID: resourceID,
|
|
||||||
Metadata: meta,
|
|
||||||
IPAddress: c.ClientIP(),
|
|
||||||
UserAgent: c.GetHeader("User-Agent"),
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.stores.Audit.Log(context.Background(), entry); err != nil {
|
|
||||||
log.Printf("audit log error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Archived Channels (v0.23.2) ──────────────
|
// ── Archived Channels (v0.23.2) ──────────────
|
||||||
|
|
||||||
func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
|
func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
|
||||||
rows, err := database.DB.QueryContext(c.Request.Context(), database.Q(`
|
page, perPage, offset := parsePagination(c)
|
||||||
SELECT c.id, c.title, c.type, c.user_id,
|
|
||||||
COALESCE(u.username, '') AS owner_name,
|
channels, total, err := h.stores.Channels.ListArchived(c.Request.Context(), store.ListOptions{
|
||||||
c.updated_at,
|
Limit: perPage,
|
||||||
(SELECT COUNT(*) FROM messages WHERE channel_id = c.id) AS message_count
|
Offset: offset,
|
||||||
FROM channels c
|
})
|
||||||
LEFT JOIN users u ON u.id = c.user_id
|
|
||||||
WHERE c.is_archived = true
|
|
||||||
ORDER BY c.updated_at DESC
|
|
||||||
LIMIT 100
|
|
||||||
`))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
type archivedChannel struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
OwnerName string `json:"owner_name"`
|
|
||||||
UpdatedAt string `json:"updated_at"`
|
|
||||||
MessageCount int `json:"message_count"`
|
|
||||||
}
|
|
||||||
|
|
||||||
channels := []archivedChannel{}
|
|
||||||
for rows.Next() {
|
|
||||||
var ch archivedChannel
|
|
||||||
var userID string
|
|
||||||
if rows.Scan(&ch.ID, &ch.Title, &ch.Type, &userID, &ch.OwnerName, &ch.UpdatedAt, &ch.MessageCount) == nil {
|
|
||||||
channels = append(channels, ch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retention config
|
// Retention config
|
||||||
retentionMode := "flexible"
|
retentionMode := "flexible"
|
||||||
@@ -784,6 +800,9 @@ func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
|
|||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"channels": channels,
|
"channels": channels,
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"per_page": perPage,
|
||||||
"retention_mode": retentionMode,
|
"retention_mode": retentionMode,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -791,32 +810,27 @@ func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
|
|||||||
func (h *AdminHandler) PurgeChannel(c *gin.Context) {
|
func (h *AdminHandler) PurgeChannel(c *gin.Context) {
|
||||||
channelID := c.Param("id")
|
channelID := c.Param("id")
|
||||||
|
|
||||||
// Verify the channel is actually archived
|
// Clean up file storage blobs before CASCADE deletes the DB references
|
||||||
var isArchived bool
|
if h.objStore != nil {
|
||||||
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
|
prefix := fmt.Sprintf("files/%s", channelID)
|
||||||
SELECT is_archived FROM channels WHERE id = $1
|
if err := h.objStore.DeletePrefix(c.Request.Context(), prefix); err != nil {
|
||||||
`), channelID).Scan(&isArchived)
|
log.Printf("⚠️ storage cleanup for purged channel %s failed: %v", channelID, err)
|
||||||
if err != nil {
|
}
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
if !isArchived {
|
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "channel must be archived before purging"})
|
if err := h.stores.Channels.Purge(c.Request.Context(), channelID); err != nil {
|
||||||
|
msg := err.Error()
|
||||||
|
switch {
|
||||||
|
case msg == "channel not found":
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": msg})
|
||||||
|
case msg == "channel must be archived before purging":
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": msg})
|
||||||
|
default:
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "purge failed"})
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hard delete (CASCADE removes messages, participants, models)
|
h.auditLog(c, "channel.purged", "channel", channelID, nil)
|
||||||
_, err = database.DB.ExecContext(c.Request.Context(), database.Q(`
|
|
||||||
DELETE FROM channels WHERE id = $1
|
|
||||||
`), channelID)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "purge failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Audit log
|
|
||||||
uid := getUserID(c)
|
|
||||||
h.auditLog(c, uid, "channel.purged", "channel", channelID)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"git.gobha.me/xcaliber/chat-switchboard/database"
|
"git.gobha.me/xcaliber/chat-switchboard/models"
|
||||||
|
"git.gobha.me/xcaliber/chat-switchboard/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AuditLog inserts an audit entry. Called from mutating handlers.
|
// AuditLog writes an audit entry via the store interface.
|
||||||
// Non-blocking: errors are logged but don't break the caller.
|
// Non-blocking: errors are logged but don't break the caller.
|
||||||
func AuditLog(c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
|
func AuditLog(auditStore store.AuditStore, c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
|
||||||
if database.DB == nil {
|
if auditStore == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,165 +24,51 @@ func AuditLog(c *gin.Context, action, resourceType, resourceID string, metadata
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := c.ClientIP()
|
var meta models.JSONMap
|
||||||
ua := c.GetHeader("User-Agent")
|
|
||||||
|
|
||||||
metaJSON := "{}"
|
|
||||||
if metadata != nil {
|
if metadata != nil {
|
||||||
if b, err := json.Marshal(metadata); err == nil {
|
b, _ := json.Marshal(metadata)
|
||||||
metaJSON = string(b)
|
json.Unmarshal(b, &meta)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if database.IsSQLite() {
|
entry := &models.AuditEntry{
|
||||||
_, _ = database.DB.Exec(`
|
ActorID: &actorID,
|
||||||
INSERT INTO audit_log (id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
|
Action: action,
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
ResourceType: resourceType,
|
||||||
`, uuid.New().String(), actorID, action, resourceType, resourceID, metaJSON, ip, ua)
|
ResourceID: resourceID,
|
||||||
} else {
|
Metadata: meta,
|
||||||
_, _ = database.DB.Exec(`
|
IPAddress: c.ClientIP(),
|
||||||
INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
|
UserAgent: c.GetHeader("User-Agent"),
|
||||||
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
|
|
||||||
`, actorID, action, resourceType, resourceID, metaJSON, ip, ua)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuditLogAnon inserts an audit entry without a gin context (e.g. system actions).
|
|
||||||
func AuditLogAnon(action, resourceType, resourceID string, metadata map[string]interface{}) {
|
|
||||||
if database.DB == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
metaJSON := "{}"
|
|
||||||
if metadata != nil {
|
|
||||||
if b, err := json.Marshal(metadata); err == nil {
|
|
||||||
metaJSON = string(b)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if database.IsSQLite() {
|
if err := auditStore.Log(context.Background(), entry); err != nil {
|
||||||
_, _ = database.DB.Exec(`
|
log.Printf("audit log error: %v", err)
|
||||||
INSERT INTO audit_log (id, action, resource_type, resource_id, metadata)
|
|
||||||
VALUES (?, ?, ?, ?, ?)
|
|
||||||
`, uuid.New().String(), action, resourceType, resourceID, metaJSON)
|
|
||||||
} else {
|
|
||||||
_, _ = database.DB.Exec(`
|
|
||||||
INSERT INTO audit_log (action, resource_type, resource_id, metadata)
|
|
||||||
VALUES ($1, $2, $3, $4::jsonb)
|
|
||||||
`, action, resourceType, resourceID, metaJSON)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuditLogWithActor inserts an audit entry with an explicit actor ID (e.g. pre-auth flows).
|
|
||||||
func AuditLogWithActor(actorID string, c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
|
|
||||||
if database.DB == nil || actorID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ip := c.ClientIP()
|
|
||||||
ua := c.GetHeader("User-Agent")
|
|
||||||
metaJSON := "{}"
|
|
||||||
if metadata != nil {
|
|
||||||
if b, err := json.Marshal(metadata); err == nil {
|
|
||||||
metaJSON = string(b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if database.IsSQLite() {
|
|
||||||
_, _ = database.DB.Exec(`
|
|
||||||
INSERT INTO audit_log (id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
||||||
`, uuid.New().String(), actorID, action, resourceType, resourceID, metaJSON, ip, ua)
|
|
||||||
} else {
|
|
||||||
_, _ = database.DB.Exec(`
|
|
||||||
INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
|
|
||||||
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
|
|
||||||
`, actorID, action, resourceType, resourceID, metaJSON, ip, ua)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Admin Audit Viewer ──────────────────────
|
// ── Admin Audit Viewer ──────────────────────
|
||||||
|
|
||||||
type auditEntry struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
ActorID *string `json:"actor_id"`
|
|
||||||
ActorName *string `json:"actor_name"`
|
|
||||||
Action string `json:"action"`
|
|
||||||
ResourceType string `json:"resource_type"`
|
|
||||||
ResourceID *string `json:"resource_id"`
|
|
||||||
Metadata string `json:"metadata"`
|
|
||||||
IPAddress *string `json:"ip_address"`
|
|
||||||
CreatedAt string `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListAuditLog returns paginated audit entries with optional filters.
|
// ListAuditLog returns paginated audit entries with optional filters.
|
||||||
// GET /api/v1/admin/audit?page=1&per_page=50&action=user.create&actor_id=...&resource_type=...
|
// GET /api/v1/admin/audit?page=1&per_page=50&action=user.create&actor_id=...&resource_type=...
|
||||||
func (h *AdminHandler) ListAuditLog(c *gin.Context) {
|
func (h *AdminHandler) ListAuditLog(c *gin.Context) {
|
||||||
page, perPage, offset := parsePagination(c)
|
page, perPage, offset := parsePagination(c)
|
||||||
|
|
||||||
// Build filter clauses with ? placeholders, convert for Postgres later
|
opts := store.AuditListOptions{
|
||||||
where := "WHERE 1=1"
|
ListOptions: store.ListOptions{
|
||||||
args := []interface{}{}
|
Limit: perPage,
|
||||||
|
Offset: offset,
|
||||||
if action := c.Query("action"); action != "" {
|
},
|
||||||
where += " AND al.action = ?"
|
Action: c.Query("action"),
|
||||||
args = append(args, action)
|
ActorID: c.Query("actor_id"),
|
||||||
}
|
ResourceType: c.Query("resource_type"),
|
||||||
if actorID := c.Query("actor_id"); actorID != "" {
|
|
||||||
where += " AND al.actor_id = ?"
|
|
||||||
args = append(args, actorID)
|
|
||||||
}
|
|
||||||
if rt := c.Query("resource_type"); rt != "" {
|
|
||||||
where += " AND al.resource_type = ?"
|
|
||||||
args = append(args, rt)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count
|
entries, total, err := h.stores.Audit.List(c.Request.Context(), opts)
|
||||||
var total int
|
|
||||||
countArgs := make([]interface{}, len(args))
|
|
||||||
copy(countArgs, args)
|
|
||||||
countQ := convertPlaceholders(`SELECT COUNT(*) FROM audit_log al ` + where)
|
|
||||||
err := database.DB.QueryRow(countQ, countArgs...).Scan(&total)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "count failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Query — metadata column needs ::text on Postgres only
|
|
||||||
metadataCol := "COALESCE(al.metadata::text, '{}')"
|
|
||||||
if database.IsSQLite() {
|
|
||||||
metadataCol = "COALESCE(al.metadata, '{}')"
|
|
||||||
}
|
|
||||||
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
SELECT al.id, al.actor_id, COALESCE(u.username, '') as actor_name,
|
|
||||||
al.action, al.resource_type, al.resource_id,
|
|
||||||
%s, al.ip_address, al.created_at
|
|
||||||
FROM audit_log al
|
|
||||||
LEFT JOIN users u ON al.actor_id = u.id
|
|
||||||
%s
|
|
||||||
ORDER BY al.created_at DESC
|
|
||||||
LIMIT ? OFFSET ?`, metadataCol, where)
|
|
||||||
args = append(args, perPage, offset)
|
|
||||||
|
|
||||||
query = convertPlaceholders(query)
|
|
||||||
rows, err := database.DB.Query(query, args...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
if entries == nil {
|
||||||
|
entries = []models.AuditEntry{}
|
||||||
entries := make([]auditEntry, 0)
|
|
||||||
for rows.Next() {
|
|
||||||
var e auditEntry
|
|
||||||
var actorName sql.NullString
|
|
||||||
if err := rows.Scan(&e.ID, &e.ActorID, &actorName, &e.Action,
|
|
||||||
&e.ResourceType, &e.ResourceID, &e.Metadata, &e.IPAddress, &e.CreatedAt); err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if actorName.Valid {
|
|
||||||
e.ActorName = &actorName.String
|
|
||||||
}
|
|
||||||
entries = append(entries, e)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
@@ -196,24 +82,10 @@ func (h *AdminHandler) ListAuditLog(c *gin.Context) {
|
|||||||
// ListAuditActions returns distinct action names for filter dropdowns.
|
// ListAuditActions returns distinct action names for filter dropdowns.
|
||||||
// GET /api/v1/admin/audit/actions
|
// GET /api/v1/admin/audit/actions
|
||||||
func (h *AdminHandler) ListAuditActions(c *gin.Context) {
|
func (h *AdminHandler) ListAuditActions(c *gin.Context) {
|
||||||
rows, err := database.DB.Query(`
|
actions, err := h.stores.Audit.ListActions(c.Request.Context())
|
||||||
SELECT DISTINCT action FROM audit_log ORDER BY action ASC
|
|
||||||
`)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusOK, gin.H{"actions": []string{}})
|
c.JSON(http.StatusOK, gin.H{"actions": []string{}})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var actions []string
|
|
||||||
for rows.Next() {
|
|
||||||
var a string
|
|
||||||
if rows.Scan(&a) == nil {
|
|
||||||
actions = append(actions, a)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if actions == nil {
|
|
||||||
actions = []string{}
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"actions": actions})
|
c.JSON(http.StatusOK, gin.H{"actions": actions})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ func (h *GroupHandler) CreateGroup(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, g)
|
c.JSON(http.StatusCreated, g)
|
||||||
AuditLog(c, "group.create", "group", g.ID, map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "group.create", "group", g.ID, map[string]interface{}{
|
||||||
"name": g.Name, "scope": g.Scope,
|
"name": g.Name, "scope": g.Scope,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -183,7 +183,7 @@ func (h *GroupHandler) UpdateGroup(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "group.update", "group", id, nil)
|
AuditLog(h.stores.Audit, c, "group.update", "group", id, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Admin: Delete Group ─────────────────────
|
// ── Admin: Delete Group ─────────────────────
|
||||||
@@ -206,7 +206,7 @@ func (h *GroupHandler) DeleteGroup(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "group.delete", "group", id, nil)
|
AuditLog(h.stores.Audit, c, "group.delete", "group", id, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Members: List ───────────────────────────
|
// ── Members: List ───────────────────────────
|
||||||
@@ -259,7 +259,7 @@ func (h *GroupHandler) AddMember(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "group.member.add", "group", groupID, map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "group.member.add", "group", groupID, map[string]interface{}{
|
||||||
"user_id": req.UserID,
|
"user_id": req.UserID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -289,7 +289,7 @@ func (h *GroupHandler) RemoveMember(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "group.member.remove", "group", groupID, map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "group.member.remove", "group", groupID, map[string]interface{}{
|
||||||
"user_id": userID,
|
"user_id": userID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -375,7 +375,7 @@ func (h *GroupHandler) SetResourceGrant(c *gin.Context) {
|
|||||||
if req.GrantScope == models.GrantScopeTeamOnly {
|
if req.GrantScope == models.GrantScopeTeamOnly {
|
||||||
_ = h.stores.ResourceGrants.Delete(c.Request.Context(), resourceType, resourceID)
|
_ = h.stores.ResourceGrants.Delete(c.Request.Context(), resourceType, resourceID)
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "grant.revoke", resourceType, resourceID, nil)
|
AuditLog(h.stores.Audit, c, "grant.revoke", resourceType, resourceID, nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,7 +393,7 @@ func (h *GroupHandler) SetResourceGrant(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, grant)
|
c.JSON(http.StatusOK, grant)
|
||||||
AuditLog(c, "grant.set", resourceType, resourceID, map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "grant.set", resourceType, resourceID, map[string]interface{}{
|
||||||
"grant_scope": req.GrantScope,
|
"grant_scope": req.GrantScope,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -415,7 +415,7 @@ func (h *GroupHandler) DeleteResourceGrant(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "grant.delete", resourceType, resourceID, nil)
|
AuditLog(h.stores.Audit, c, "grant.delete", resourceType, resourceID, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListPermissions returns all valid permission strings.
|
// ListPermissions returns all valid permission strings.
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ func setupHarness(t *testing.T) *testHarness {
|
|||||||
authGroup.POST("/login", auth.Login)
|
authGroup.POST("/login", auth.Login)
|
||||||
|
|
||||||
// Public settings
|
// Public settings
|
||||||
adm := NewAdminHandler(stores, nil, nil)
|
adm := NewAdminHandler(stores, nil, nil, nil)
|
||||||
api.GET("/settings/public", adm.PublicSettings)
|
api.GET("/settings/public", adm.PublicSettings)
|
||||||
|
|
||||||
// Protected routes
|
// Protected routes
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ func (h *TeamHandler) CreateTeam(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, gin.H{"id": team.ID, "name": team.Name})
|
c.JSON(http.StatusCreated, gin.H{"id": team.ID, "name": team.Name})
|
||||||
AuditLog(c, "team.create", "team", team.ID, map[string]interface{}{"name": team.Name})
|
AuditLog(h.stores.Audit, c, "team.create", "team", team.ID, map[string]interface{}{"name": team.Name})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Admin: Get Team ─────────────────────────
|
// ── Admin: Get Team ─────────────────────────
|
||||||
@@ -217,7 +217,7 @@ func (h *TeamHandler) UpdateTeam(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "team.update", "team", teamID, nil)
|
AuditLog(h.stores.Audit, c, "team.update", "team", teamID, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Admin: Delete Team ──────────────────────
|
// ── Admin: Delete Team ──────────────────────
|
||||||
@@ -242,7 +242,7 @@ func (h *TeamHandler) DeleteTeam(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "team.delete", "team", teamID, nil)
|
AuditLog(h.stores.Audit, c, "team.delete", "team", teamID, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Members: List ───────────────────────────
|
// ── Members: List ───────────────────────────
|
||||||
@@ -303,7 +303,7 @@ func (h *TeamHandler) AddMember(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, gin.H{"id": id})
|
c.JSON(http.StatusCreated, gin.H{"id": id})
|
||||||
AuditLog(c, "team.add_member", "team", getTeamID(c), map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "team.add_member", "team", getTeamID(c), map[string]interface{}{
|
||||||
"user_id": req.UserID, "role": req.Role,
|
"user_id": req.UserID, "role": req.Role,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -333,7 +333,7 @@ func (h *TeamHandler) UpdateMember(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "team.update_member", "team", getTeamID(c), map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "team.update_member", "team", getTeamID(c), map[string]interface{}{
|
||||||
"member_id": memberID, "role": req.Role,
|
"member_id": memberID, "role": req.Role,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -355,7 +355,7 @@ func (h *TeamHandler) RemoveMember(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
AuditLog(c, "team.remove_member", "team", getTeamID(c), map[string]interface{}{
|
AuditLog(h.stores.Audit, c, "team.remove_member", "team", getTeamID(c), map[string]interface{}{
|
||||||
"member_id": memberID,
|
"member_id": memberID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -141,6 +141,9 @@ func (h *UsageHandler) ListPricing(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list pricing"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list pricing"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if entries == nil {
|
||||||
|
entries = []models.PricingEntry{}
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, entries)
|
c.JSON(http.StatusOK, entries)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -929,7 +929,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Public global settings (non-admin users can read safe subset)
|
// Public global settings (non-admin users can read safe subset)
|
||||||
adm := handlers.NewAdminHandler(stores, keyResolver, uekCache)
|
adm := handlers.NewAdminHandler(stores, keyResolver, uekCache, objStore)
|
||||||
protected.GET("/settings/public", adm.PublicSettings)
|
protected.GET("/settings/public", adm.PublicSettings)
|
||||||
|
|
||||||
// Extensions (user-facing)
|
// Extensions (user-facing)
|
||||||
@@ -944,7 +944,7 @@ func main() {
|
|||||||
admin.Use(middleware.Auth(cfg))
|
admin.Use(middleware.Auth(cfg))
|
||||||
admin.Use(middleware.RequireAdmin())
|
admin.Use(middleware.RequireAdmin())
|
||||||
{
|
{
|
||||||
adm := handlers.NewAdminHandler(stores, keyResolver, uekCache)
|
adm := handlers.NewAdminHandler(stores, keyResolver, uekCache, objStore)
|
||||||
|
|
||||||
// User management
|
// User management
|
||||||
admin.GET("/users", adm.ListUsers)
|
admin.GET("/users", adm.ListUsers)
|
||||||
|
|||||||
@@ -642,6 +642,7 @@ type File struct {
|
|||||||
type AuditEntry struct {
|
type AuditEntry struct {
|
||||||
ID string `json:"id" db:"id"`
|
ID string `json:"id" db:"id"`
|
||||||
ActorID *string `json:"actor_id,omitempty" db:"actor_id"`
|
ActorID *string `json:"actor_id,omitempty" db:"actor_id"`
|
||||||
|
ActorName *string `json:"actor_name,omitempty" db:"-"` // resolved via JOIN, not a column
|
||||||
Action string `json:"action" db:"action"`
|
Action string `json:"action" db:"action"`
|
||||||
ResourceType string `json:"resource_type" db:"resource_type"`
|
ResourceType string `json:"resource_type" db:"resource_type"`
|
||||||
ResourceID string `json:"resource_id,omitempty" db:"resource_id"`
|
ResourceID string `json:"resource_id,omitempty" db:"resource_id"`
|
||||||
|
|||||||
@@ -257,6 +257,20 @@ type ChannelStore interface {
|
|||||||
|
|
||||||
// Workspace resolution: channel workspace_id > project workspace_id
|
// Workspace resolution: channel workspace_id > project workspace_id
|
||||||
ResolveWorkspaceID(ctx context.Context, channelID string) (string, error)
|
ResolveWorkspaceID(ctx context.Context, channelID string) (string, error)
|
||||||
|
|
||||||
|
// Admin: archived channel management (v0.23.2)
|
||||||
|
ListArchived(ctx context.Context, opts ListOptions) ([]ArchivedChannel, int, error)
|
||||||
|
Purge(ctx context.Context, id string) error // hard-delete; channel must be archived
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArchivedChannel is a view model for the admin archived channels list.
|
||||||
|
type ArchivedChannel struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
OwnerName string `json:"owner_name"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
|
MessageCount int `json:"message_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================
|
// =========================================
|
||||||
@@ -287,6 +301,7 @@ type MessageStore interface {
|
|||||||
type AuditStore interface {
|
type AuditStore interface {
|
||||||
Log(ctx context.Context, entry *models.AuditEntry) error
|
Log(ctx context.Context, entry *models.AuditEntry) error
|
||||||
List(ctx context.Context, opts AuditListOptions) ([]models.AuditEntry, int, error)
|
List(ctx context.Context, opts AuditListOptions) ([]models.AuditEntry, int, error)
|
||||||
|
ListActions(ctx context.Context) ([]string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditListOptions struct {
|
type AuditListOptions struct {
|
||||||
|
|||||||
@@ -25,25 +25,28 @@ func (s *AuditStore) Log(ctx context.Context, entry *models.AuditEntry) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
|
func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
|
||||||
b := NewSelect("id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent, created_at", "audit_log")
|
b := NewSelect(`al.id, al.actor_id, COALESCE(u.username, '') AS actor_name,
|
||||||
|
al.action, al.resource_type, al.resource_id, al.metadata,
|
||||||
|
al.ip_address, al.user_agent, al.created_at`, "audit_log al")
|
||||||
|
b.Join("LEFT JOIN users u ON al.actor_id = u.id")
|
||||||
|
|
||||||
if opts.ActorID != "" {
|
if opts.ActorID != "" {
|
||||||
b.Where("actor_id = ?", opts.ActorID)
|
b.Where("al.actor_id = ?", opts.ActorID)
|
||||||
}
|
}
|
||||||
if opts.Action != "" {
|
if opts.Action != "" {
|
||||||
b.Where("action = ?", opts.Action)
|
b.Where("al.action = ?", opts.Action)
|
||||||
}
|
}
|
||||||
if opts.ResourceType != "" {
|
if opts.ResourceType != "" {
|
||||||
b.Where("resource_type = ?", opts.ResourceType)
|
b.Where("al.resource_type = ?", opts.ResourceType)
|
||||||
}
|
}
|
||||||
if opts.ResourceID != "" {
|
if opts.ResourceID != "" {
|
||||||
b.Where("resource_id = ?", opts.ResourceID)
|
b.Where("al.resource_id = ?", opts.ResourceID)
|
||||||
}
|
}
|
||||||
if opts.Since != nil {
|
if opts.Since != nil {
|
||||||
b.Where("created_at >= ?", *opts.Since)
|
b.Where("al.created_at >= ?", *opts.Since)
|
||||||
}
|
}
|
||||||
if opts.Until != nil {
|
if opts.Until != nil {
|
||||||
b.Where("created_at <= ?", *opts.Until)
|
b.Where("al.created_at <= ?", *opts.Until)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count
|
// Count
|
||||||
@@ -53,7 +56,7 @@ func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]m
|
|||||||
|
|
||||||
// Results
|
// Results
|
||||||
if opts.Sort == "" {
|
if opts.Sort == "" {
|
||||||
b.OrderBy("created_at", "DESC")
|
b.OrderBy("al.created_at", "DESC")
|
||||||
}
|
}
|
||||||
b.Paginate(opts.ListOptions)
|
b.Paginate(opts.ListOptions)
|
||||||
|
|
||||||
@@ -67,16 +70,40 @@ func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]m
|
|||||||
var result []models.AuditEntry
|
var result []models.AuditEntry
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var e models.AuditEntry
|
var e models.AuditEntry
|
||||||
var actorID sql.NullString
|
var actorID, actorName sql.NullString
|
||||||
var metadataJSON []byte
|
var metadataJSON []byte
|
||||||
err := rows.Scan(&e.ID, &actorID, &e.Action, &e.ResourceType, &e.ResourceID,
|
err := rows.Scan(&e.ID, &actorID, &actorName, &e.Action, &e.ResourceType, &e.ResourceID,
|
||||||
&metadataJSON, &e.IPAddress, &e.UserAgent, &e.CreatedAt)
|
&metadataJSON, &e.IPAddress, &e.UserAgent, &e.CreatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
e.ActorID = NullableStringPtr(actorID)
|
e.ActorID = NullableStringPtr(actorID)
|
||||||
|
if actorName.Valid && actorName.String != "" {
|
||||||
|
e.ActorName = &actorName.String
|
||||||
|
}
|
||||||
json.Unmarshal(metadataJSON, &e.Metadata)
|
json.Unmarshal(metadataJSON, &e.Metadata)
|
||||||
result = append(result, e)
|
result = append(result, e)
|
||||||
}
|
}
|
||||||
return result, total, rows.Err()
|
return result, total, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *AuditStore) ListActions(ctx context.Context) ([]string, error) {
|
||||||
|
rows, err := DB.QueryContext(ctx,
|
||||||
|
`SELECT DISTINCT action FROM audit_log ORDER BY action ASC`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var actions []string
|
||||||
|
for rows.Next() {
|
||||||
|
var a string
|
||||||
|
if rows.Scan(&a) == nil {
|
||||||
|
actions = append(actions, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if actions == nil {
|
||||||
|
actions = []string{}
|
||||||
|
}
|
||||||
|
return actions, rows.Err()
|
||||||
|
}
|
||||||
|
|||||||
@@ -414,3 +414,55 @@ func (s *ChannelStore) DeleteModelByPersona(ctx context.Context, channelID, pers
|
|||||||
channelID, personaID)
|
channelID, personaID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Admin: Archived Channel Management ──────
|
||||||
|
|
||||||
|
func (s *ChannelStore) ListArchived(ctx context.Context, opts store.ListOptions) ([]store.ArchivedChannel, int, error) {
|
||||||
|
// Count
|
||||||
|
var total int
|
||||||
|
DB.QueryRowContext(ctx,
|
||||||
|
`SELECT COUNT(*) FROM channels WHERE is_archived = true`).Scan(&total)
|
||||||
|
|
||||||
|
rows, err := DB.QueryContext(ctx, `
|
||||||
|
SELECT c.id, c.title, c.type, COALESCE(u.username, '') AS owner_name,
|
||||||
|
c.updated_at,
|
||||||
|
(SELECT COUNT(*) FROM messages WHERE channel_id = c.id) AS message_count
|
||||||
|
FROM channels c
|
||||||
|
LEFT JOIN users u ON u.id = c.user_id
|
||||||
|
WHERE c.is_archived = true
|
||||||
|
ORDER BY c.updated_at DESC
|
||||||
|
LIMIT $1 OFFSET $2`, opts.Limit, opts.Offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var channels []store.ArchivedChannel
|
||||||
|
for rows.Next() {
|
||||||
|
var ch store.ArchivedChannel
|
||||||
|
if rows.Scan(&ch.ID, &ch.Title, &ch.Type, &ch.OwnerName, &ch.UpdatedAt, &ch.MessageCount) == nil {
|
||||||
|
channels = append(channels, ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if channels == nil {
|
||||||
|
channels = []store.ArchivedChannel{}
|
||||||
|
}
|
||||||
|
return channels, total, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChannelStore) Purge(ctx context.Context, id string) error {
|
||||||
|
// Verify the channel is actually archived
|
||||||
|
var isArchived bool
|
||||||
|
err := DB.QueryRowContext(ctx,
|
||||||
|
`SELECT is_archived FROM channels WHERE id = $1`, id).Scan(&isArchived)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("channel not found")
|
||||||
|
}
|
||||||
|
if !isArchived {
|
||||||
|
return fmt.Errorf("channel must be archived before purging")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hard delete (CASCADE removes messages, participants, models)
|
||||||
|
_, err = DB.ExecContext(ctx, `DELETE FROM channels WHERE id = $1`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,25 +29,28 @@ func (s *AuditStore) Log(ctx context.Context, entry *models.AuditEntry) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
|
func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
|
||||||
b := NewSelect("id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent, created_at", "audit_log")
|
b := NewSelect(`al.id, al.actor_id, COALESCE(u.username, '') AS actor_name,
|
||||||
|
al.action, al.resource_type, al.resource_id, al.metadata,
|
||||||
|
al.ip_address, al.user_agent, al.created_at`, "audit_log al")
|
||||||
|
b.Join("LEFT JOIN users u ON al.actor_id = u.id")
|
||||||
|
|
||||||
if opts.ActorID != "" {
|
if opts.ActorID != "" {
|
||||||
b.Where("actor_id = ?", opts.ActorID)
|
b.Where("al.actor_id = ?", opts.ActorID)
|
||||||
}
|
}
|
||||||
if opts.Action != "" {
|
if opts.Action != "" {
|
||||||
b.Where("action = ?", opts.Action)
|
b.Where("al.action = ?", opts.Action)
|
||||||
}
|
}
|
||||||
if opts.ResourceType != "" {
|
if opts.ResourceType != "" {
|
||||||
b.Where("resource_type = ?", opts.ResourceType)
|
b.Where("al.resource_type = ?", opts.ResourceType)
|
||||||
}
|
}
|
||||||
if opts.ResourceID != "" {
|
if opts.ResourceID != "" {
|
||||||
b.Where("resource_id = ?", opts.ResourceID)
|
b.Where("al.resource_id = ?", opts.ResourceID)
|
||||||
}
|
}
|
||||||
if opts.Since != nil {
|
if opts.Since != nil {
|
||||||
b.Where("created_at >= ?", *opts.Since)
|
b.Where("al.created_at >= ?", *opts.Since)
|
||||||
}
|
}
|
||||||
if opts.Until != nil {
|
if opts.Until != nil {
|
||||||
b.Where("created_at <= ?", *opts.Until)
|
b.Where("al.created_at <= ?", *opts.Until)
|
||||||
}
|
}
|
||||||
|
|
||||||
countQ, countArgs := b.CountBuild()
|
countQ, countArgs := b.CountBuild()
|
||||||
@@ -55,7 +58,7 @@ func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]m
|
|||||||
DB.QueryRowContext(ctx, countQ, countArgs...).Scan(&total)
|
DB.QueryRowContext(ctx, countQ, countArgs...).Scan(&total)
|
||||||
|
|
||||||
if opts.Sort == "" {
|
if opts.Sort == "" {
|
||||||
b.OrderBy("created_at", "DESC")
|
b.OrderBy("al.created_at", "DESC")
|
||||||
}
|
}
|
||||||
b.Paginate(opts.ListOptions)
|
b.Paginate(opts.ListOptions)
|
||||||
|
|
||||||
@@ -69,16 +72,40 @@ func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]m
|
|||||||
var result []models.AuditEntry
|
var result []models.AuditEntry
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var e models.AuditEntry
|
var e models.AuditEntry
|
||||||
var actorID sql.NullString
|
var actorID, actorName sql.NullString
|
||||||
var metadataJSON string
|
var metadataJSON string
|
||||||
err := rows.Scan(&e.ID, &actorID, &e.Action, &e.ResourceType, &e.ResourceID,
|
err := rows.Scan(&e.ID, &actorID, &actorName, &e.Action, &e.ResourceType, &e.ResourceID,
|
||||||
&metadataJSON, &e.IPAddress, &e.UserAgent, st(&e.CreatedAt))
|
&metadataJSON, &e.IPAddress, &e.UserAgent, st(&e.CreatedAt))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
e.ActorID = NullableStringPtr(actorID)
|
e.ActorID = NullableStringPtr(actorID)
|
||||||
|
if actorName.Valid && actorName.String != "" {
|
||||||
|
e.ActorName = &actorName.String
|
||||||
|
}
|
||||||
json.Unmarshal([]byte(metadataJSON), &e.Metadata)
|
json.Unmarshal([]byte(metadataJSON), &e.Metadata)
|
||||||
result = append(result, e)
|
result = append(result, e)
|
||||||
}
|
}
|
||||||
return result, total, rows.Err()
|
return result, total, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *AuditStore) ListActions(ctx context.Context) ([]string, error) {
|
||||||
|
rows, err := DB.QueryContext(ctx,
|
||||||
|
`SELECT DISTINCT action FROM audit_log ORDER BY action ASC`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var actions []string
|
||||||
|
for rows.Next() {
|
||||||
|
var a string
|
||||||
|
if rows.Scan(&a) == nil {
|
||||||
|
actions = append(actions, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if actions == nil {
|
||||||
|
actions = []string{}
|
||||||
|
}
|
||||||
|
return actions, rows.Err()
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -419,3 +420,55 @@ func (s *ChannelStore) DeleteModelByPersona(ctx context.Context, channelID, pers
|
|||||||
channelID, personaID)
|
channelID, personaID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Admin: Archived Channel Management ──────
|
||||||
|
|
||||||
|
func (s *ChannelStore) ListArchived(ctx context.Context, opts store.ListOptions) ([]store.ArchivedChannel, int, error) {
|
||||||
|
// Count
|
||||||
|
var total int
|
||||||
|
DB.QueryRowContext(ctx,
|
||||||
|
`SELECT COUNT(*) FROM channels WHERE is_archived = 1`).Scan(&total)
|
||||||
|
|
||||||
|
rows, err := DB.QueryContext(ctx, `
|
||||||
|
SELECT c.id, c.title, c.type, COALESCE(u.username, '') AS owner_name,
|
||||||
|
c.updated_at,
|
||||||
|
(SELECT COUNT(*) FROM messages WHERE channel_id = c.id) AS message_count
|
||||||
|
FROM channels c
|
||||||
|
LEFT JOIN users u ON u.id = c.user_id
|
||||||
|
WHERE c.is_archived = 1
|
||||||
|
ORDER BY c.updated_at DESC
|
||||||
|
LIMIT ? OFFSET ?`, opts.Limit, opts.Offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var channels []store.ArchivedChannel
|
||||||
|
for rows.Next() {
|
||||||
|
var ch store.ArchivedChannel
|
||||||
|
if rows.Scan(&ch.ID, &ch.Title, &ch.Type, &ch.OwnerName, &ch.UpdatedAt, &ch.MessageCount) == nil {
|
||||||
|
channels = append(channels, ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if channels == nil {
|
||||||
|
channels = []store.ArchivedChannel{}
|
||||||
|
}
|
||||||
|
return channels, total, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChannelStore) Purge(ctx context.Context, id string) error {
|
||||||
|
// Verify the channel is actually archived
|
||||||
|
var isArchived int
|
||||||
|
err := DB.QueryRowContext(ctx,
|
||||||
|
`SELECT is_archived FROM channels WHERE id = ?`, id).Scan(&isArchived)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("channel not found")
|
||||||
|
}
|
||||||
|
if isArchived == 0 {
|
||||||
|
return fmt.Errorf("channel must be archived before purging")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hard delete (CASCADE removes messages, participants, models)
|
||||||
|
_, err = DB.ExecContext(ctx, `DELETE FROM channels WHERE id = ?`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ func NewStores(db *sql.DB) store.Stores {
|
|||||||
CapOverrides: NewCapOverrideStore(),
|
CapOverrides: NewCapOverrideStore(),
|
||||||
RoutingPolicies: NewRoutingPolicyStore(),
|
RoutingPolicies: NewRoutingPolicyStore(),
|
||||||
Sessions: NewSessionStore(),
|
Sessions: NewSessionStore(),
|
||||||
|
Surfaces: NewSurfaceRegistryStore(),
|
||||||
Workflows: NewWorkflowStore(),
|
Workflows: NewWorkflowStore(),
|
||||||
Tasks: NewTaskStore(),
|
Tasks: NewTaskStore(),
|
||||||
}
|
}
|
||||||
|
|||||||
125
server/store/sqlite/surface_registry.go
Normal file
125
server/store/sqlite/surface_registry.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package sqlite
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"git.gobha.me/xcaliber/chat-switchboard/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SurfaceRegistryStore struct{}
|
||||||
|
|
||||||
|
func NewSurfaceRegistryStore() *SurfaceRegistryStore { return &SurfaceRegistryStore{} }
|
||||||
|
|
||||||
|
// Seed upserts a core surface. Called at startup by the page engine
|
||||||
|
// to ensure core surfaces exist in the registry. Does NOT overwrite
|
||||||
|
// the enabled state if the row already exists (admin toggle survives restart).
|
||||||
|
func (s *SurfaceRegistryStore) Seed(ctx context.Context, id, title, source string, manifest map[string]any) error {
|
||||||
|
manifestJSON := ToJSON(manifest)
|
||||||
|
_, err := DB.ExecContext(ctx, `
|
||||||
|
INSERT INTO surface_registry (id, title, source, manifest, enabled, installed_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, 1, datetime('now'), datetime('now'))
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
title = excluded.title,
|
||||||
|
manifest = excluded.manifest,
|
||||||
|
source = excluded.source,
|
||||||
|
updated_at = datetime('now')`,
|
||||||
|
// Note: ON CONFLICT does NOT update 'enabled' — preserves admin toggle
|
||||||
|
id, title, source, manifestJSON)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SurfaceRegistryStore) List(ctx context.Context) ([]store.SurfaceRegistration, error) {
|
||||||
|
rows, err := DB.QueryContext(ctx,
|
||||||
|
`SELECT id, title, manifest, enabled, source, installed_at, updated_at
|
||||||
|
FROM surface_registry ORDER BY source, title`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var surfaces []store.SurfaceRegistration
|
||||||
|
for rows.Next() {
|
||||||
|
var sr store.SurfaceRegistration
|
||||||
|
var manifestJSON string
|
||||||
|
var enabledInt int
|
||||||
|
if err := rows.Scan(&sr.ID, &sr.Title, &manifestJSON, &enabledInt, &sr.Source, &sr.InstalledAt, &sr.UpdatedAt); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sr.Enabled = enabledInt != 0
|
||||||
|
json.Unmarshal([]byte(manifestJSON), &sr.Manifest)
|
||||||
|
surfaces = append(surfaces, sr)
|
||||||
|
}
|
||||||
|
return surfaces, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SurfaceRegistryStore) Get(ctx context.Context, id string) (*store.SurfaceRegistration, error) {
|
||||||
|
var sr store.SurfaceRegistration
|
||||||
|
var manifestJSON string
|
||||||
|
var enabledInt int
|
||||||
|
err := DB.QueryRowContext(ctx,
|
||||||
|
`SELECT id, title, manifest, enabled, source, installed_at, updated_at
|
||||||
|
FROM surface_registry WHERE id = ?`, id).
|
||||||
|
Scan(&sr.ID, &sr.Title, &manifestJSON, &enabledInt, &sr.Source, &sr.InstalledAt, &sr.UpdatedAt)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sr.Enabled = enabledInt != 0
|
||||||
|
json.Unmarshal([]byte(manifestJSON), &sr.Manifest)
|
||||||
|
return &sr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SurfaceRegistryStore) SetEnabled(ctx context.Context, id string, enabled bool) error {
|
||||||
|
enabledInt := 0
|
||||||
|
if enabled {
|
||||||
|
enabledInt = 1
|
||||||
|
}
|
||||||
|
result, err := DB.ExecContext(ctx,
|
||||||
|
`UPDATE surface_registry SET enabled = ?, updated_at = datetime('now') WHERE id = ?`,
|
||||||
|
enabledInt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
affected, _ := result.RowsAffected()
|
||||||
|
if affected == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SurfaceRegistryStore) Delete(ctx context.Context, id string) error {
|
||||||
|
// Only allow deleting extension surfaces, not core
|
||||||
|
result, err := DB.ExecContext(ctx,
|
||||||
|
`DELETE FROM surface_registry WHERE id = ? AND source = 'extension'`, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
affected, _ := result.RowsAffected()
|
||||||
|
if affected == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SurfaceRegistryStore) ListEnabled(ctx context.Context) ([]string, error) {
|
||||||
|
rows, err := DB.QueryContext(ctx,
|
||||||
|
`SELECT id FROM surface_registry WHERE enabled = 1 ORDER BY title`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var ids []string
|
||||||
|
for rows.Next() {
|
||||||
|
var id string
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
return ids, rows.Err()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user