Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation. Co-Authored-By: Craft Agent <agents-noreply@craft.do>
256 lines
8.7 KiB
Go
256 lines
8.7 KiB
Go
package httpapi
|
||
|
||
import (
|
||
"crypto/sha256"
|
||
"database/sql"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"net/mail"
|
||
"strings"
|
||
"time"
|
||
"unicode/utf8"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"golang.org/x/crypto/bcrypt"
|
||
)
|
||
|
||
type platformSettings struct {
|
||
SiteName string `json:"site_name"`
|
||
SupportEmail string `json:"support_email"`
|
||
Announcement string `json:"announcement"`
|
||
UpdatedAt *time.Time `json:"updated_at"`
|
||
}
|
||
|
||
func validateSettings(s *platformSettings) bool {
|
||
s.SiteName = strings.TrimSpace(s.SiteName)
|
||
s.SupportEmail = strings.TrimSpace(s.SupportEmail)
|
||
if s.SiteName == "" || utf8.RuneCountInString(s.SiteName) > 100 || len(s.SupportEmail) > 254 || utf8.RuneCountInString(s.Announcement) > 2000 {
|
||
return false
|
||
}
|
||
if s.SupportEmail != "" {
|
||
a, err := mail.ParseAddress(s.SupportEmail)
|
||
if err != nil || a.Address != s.SupportEmail {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
func (a *BusinessAPI) getSettings(c *gin.Context) {
|
||
var s platformSettings
|
||
if err := a.db.QueryRowContext(c, "SELECT site_name,support_email,announcement,updated_at FROM system_settings WHERE id=1").Scan(&s.SiteName, &s.SupportEmail, &s.Announcement, &s.UpdatedAt); err != nil {
|
||
apiError(c, 500, "internal_error", "设置加载失败")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": s})
|
||
}
|
||
func (a *BusinessAPI) updateSettings(c *gin.Context) {
|
||
var s platformSettings
|
||
if c.ShouldBindJSON(&s) != nil || !validateSettings(&s) {
|
||
apiError(c, 400, "invalid_request", "平台名称为1至100字,联系邮箱必须有效,公告最多2000字")
|
||
return
|
||
}
|
||
now := time.Now().UTC()
|
||
s.UpdatedAt = &now
|
||
tx, err := a.db.BeginTx(c, nil)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "设置保存失败")
|
||
return
|
||
}
|
||
defer tx.Rollback()
|
||
// Lock the singleton so concurrent saves are serialized with their audit record.
|
||
var id int
|
||
if err = tx.QueryRowContext(c, "SELECT id FROM system_settings WHERE id=1 FOR UPDATE").Scan(&id); err == nil {
|
||
_, err = tx.ExecContext(c, "UPDATE system_settings SET site_name=?,support_email=?,announcement=?,updated_at=? WHERE id=1", s.SiteName, s.SupportEmail, s.Announcement, now)
|
||
}
|
||
if err == nil {
|
||
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'settings.updated','system_settings',1,?)", c.GetUint64("admin_id"), `{"fields":["site_name","support_email","announcement"]}`)
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "设置保存失败")
|
||
return
|
||
}
|
||
if tx.Commit() != nil {
|
||
apiError(c, 500, "internal_error", "设置保存结果未确认,请刷新检查")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": s})
|
||
}
|
||
func (a *BusinessAPI) changePassword(c *gin.Context) {
|
||
var in struct {
|
||
Current string `json:"current_password"`
|
||
New string `json:"new_password"`
|
||
}
|
||
if c.ShouldBindJSON(&in) != nil || in.Current == "" || in.New == "" || len(in.New) > 72 {
|
||
apiError(c, 400, "invalid_request", "当前密码和新密码不能为空,新密码最多72字节")
|
||
return
|
||
}
|
||
// Hash before acquiring the row lock to keep the write transaction short.
|
||
hash, err := bcrypt.GenerateFromPassword([]byte(in.New), bcrypt.DefaultCost)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码修改失败")
|
||
return
|
||
}
|
||
tx, err := a.db.BeginTx(c, nil)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码修改失败")
|
||
return
|
||
}
|
||
defer tx.Rollback()
|
||
var old string
|
||
id := c.GetUint64("admin_id")
|
||
err = tx.QueryRowContext(c, "SELECT password_hash FROM admins WHERE id=? AND active=1 FOR UPDATE", id).Scan(&old)
|
||
if err == sql.ErrNoRows {
|
||
apiError(c, 401, "unauthorized", "账号已失效")
|
||
return
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码修改失败")
|
||
return
|
||
}
|
||
if bcrypt.CompareHashAndPassword([]byte(old), []byte(in.Current)) != nil {
|
||
apiError(c, 400, "invalid_credentials", "当前密码错误")
|
||
return
|
||
}
|
||
raw, _ := c.Cookie("lp_session")
|
||
decoded, _ := hex.DecodeString(raw)
|
||
sum := sha256.Sum256(decoded)
|
||
if _, err = tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id); err == nil {
|
||
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND token_hash<>? AND revoked_at IS NULL", time.Now().UTC(), id, sum[:])
|
||
}
|
||
if err == nil {
|
||
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_changed','admin',?,?)", id, id, `{"other_sessions_revoked":true}`)
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码修改失败")
|
||
return
|
||
}
|
||
if tx.Commit() != nil {
|
||
apiError(c, 500, "internal_error", "密码修改结果未确认,请重新登录检查")
|
||
return
|
||
}
|
||
c.Status(204)
|
||
}
|
||
|
||
type auditRecord struct {
|
||
ID uint64 `json:"id"`
|
||
ActorID uint64 `json:"actor_admin_id"`
|
||
ActorEmail string `json:"actor_email"`
|
||
Action string `json:"action"`
|
||
ResourceType string `json:"resource_type"`
|
||
ResourceID uint64 `json:"resource_id"`
|
||
Details map[string]any `json:"details"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// Expose known business fields only. Future events cannot accidentally expose credentials.
|
||
func publicAuditDetails(raw []byte) map[string]any {
|
||
var input map[string]any
|
||
_ = json.Unmarshal(raw, &input)
|
||
out := map[string]any{}
|
||
for _, key := range []string{"client_actor", "customer_id", "product_id", "license_id", "order_id", "instance_id", "release_id", "starts_at", "expires_at", "operation", "amount_cents", "currency", "certificate_version", "state", "previous_state", "freeze_state", "lease_expires_at", "version", "sha256", "size_bytes", "fields", "other_sessions_revoked"} {
|
||
if v, ok := input[key]; ok {
|
||
switch v.(type) {
|
||
case string, float64, bool, nil:
|
||
out[key] = v
|
||
case []any:
|
||
if key == "fields" {
|
||
out[key] = []string{"site_name", "support_email", "announcement"}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
func auditFilter(c *gin.Context) (string, []any, bool) {
|
||
clauses := []string{"1=1"}
|
||
args := []any{}
|
||
for _, item := range []struct{ key, column string }{{"action", "e.action"}, {"resource_type", "e.resource_type"}} {
|
||
if v := strings.TrimSpace(c.Query(item.key)); v != "" {
|
||
if len(v) > 64 {
|
||
return "", nil, false
|
||
}
|
||
clauses = append(clauses, item.column+"=?")
|
||
args = append(args, v)
|
||
}
|
||
}
|
||
if q := strings.TrimSpace(c.Query("q")); q != "" {
|
||
if utf8.RuneCountInString(q) > 200 {
|
||
return "", nil, false
|
||
}
|
||
clauses = append(clauses, "(a.email LIKE ? OR e.action LIKE ? OR e.resource_type LIKE ?)")
|
||
for i := 0; i < 3; i++ {
|
||
args = append(args, "%"+q+"%")
|
||
}
|
||
}
|
||
var from, to time.Time
|
||
for _, key := range []string{"from", "to"} {
|
||
if v := c.Query(key); v != "" {
|
||
t, err := time.Parse(time.RFC3339, v)
|
||
if err != nil {
|
||
return "", nil, false
|
||
}
|
||
op := ">="
|
||
if key == "to" {
|
||
op = "<="
|
||
to = t
|
||
} else {
|
||
from = t
|
||
}
|
||
clauses = append(clauses, "e.created_at"+op+"?")
|
||
args = append(args, t.UTC())
|
||
}
|
||
}
|
||
if !from.IsZero() && !to.IsZero() && from.After(to) {
|
||
return "", nil, false
|
||
}
|
||
return strings.Join(clauses, " AND "), args, true
|
||
}
|
||
func (a *BusinessAPI) listAuditEvents(c *gin.Context) {
|
||
where, args, ok := auditFilter(c)
|
||
if !ok {
|
||
apiError(c, 400, "invalid_request", "审计筛选参数无效,时间请使用ISO格式")
|
||
return
|
||
}
|
||
p, size := page(c)
|
||
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
defer tx.Rollback()
|
||
base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE " + where
|
||
var total int64
|
||
if err = tx.QueryRowContext(c, "SELECT COUNT(*)"+base, args...).Scan(&total); err != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
pageArgs := append(append([]any{}, args...), size, (p-1)*size)
|
||
rows, err := tx.QueryContext(c, "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at"+base+" ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", pageArgs...)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
defer rows.Close()
|
||
out := []auditRecord{}
|
||
for rows.Next() {
|
||
var v auditRecord
|
||
var raw []byte
|
||
if err = rows.Scan(&v.ID, &v.ActorID, &v.ActorEmail, &v.Action, &v.ResourceType, &v.ResourceID, &raw, &v.CreatedAt); err != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
v.Details = publicAuditDetails(raw)
|
||
out = append(out, v)
|
||
}
|
||
if rows.Err() != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
rows.Close()
|
||
if tx.Commit() != nil {
|
||
apiError(c, 500, "internal_error", "日志加载失败")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||
}
|