Files
yhy-mager/backend/internal/httpapi/business.go
xiewenjun 09910db251
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: localize license states and restore revoked licenses
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-12 16:11:09 +08:00

382 lines
13 KiB
Go

package httpapi
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
type BusinessAPI struct {
db *sql.DB
signingPrivateKeyPEM string
keyring *Keyring
credentialEncryptionKey []byte
}
func secureSessionCookie(c *gin.Context) bool {
return c.Request.TLS != nil || os.Getenv("SESSION_COOKIE_SECURE") == "true"
}
func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string) {
if db == nil {
return
}
a := &BusinessAPI{db: db}
if len(signingPrivateKeyPEM) > 0 {
a.signingPrivateKeyPEM = signingPrivateKeyPEM[0]
}
registerBusinessRoutes(r, a)
}
func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring, credentialKey ...[]byte) {
if db == nil {
return
}
a := &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring}
if len(credentialKey) > 0 {
a.credentialEncryptionKey = credentialKey[0]
}
registerBusinessRoutes(r, a)
}
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
api := r.Group("/api/v1")
api.POST("/auth/login", a.login)
api.POST("/portal/snapshot", a.portalSnapshot)
api.POST("/activation/instances/:instance_id", a.activateInstance)
api.GET("/activation/public-key", a.activationPublicKey)
api.GET("/activation/keyring", func(c *gin.Context) {
if a.keyring == nil {
apiError(c, 404, "not_found", "Keyring unavailable")
return
}
c.JSON(200, gin.H{"data": a.keyring})
})
api.POST("/instances/:instance_id/heartbeat", a.heartbeat)
api.POST("/auth/logout", a.authenticated, a.logout)
secured := api.Group("", a.authenticated)
secured.GET("/me", a.me)
secured.GET("/admins", a.listAdmins)
secured.POST("/admins", a.createAdmin)
secured.POST("/admins/:id/active", a.setAdminActive)
secured.POST("/admins/:id/reset-password", a.resetAdminPassword)
secured.GET("/dashboard/summary", a.dashboardSummary)
secured.GET("/audit-events", a.listAuditEvents)
secured.GET("/settings", a.getSettings)
secured.PUT("/settings", a.updateSettings)
secured.POST("/settings/password", a.changePassword)
secured.GET("/integration-trust", a.integrationTrust)
secured.GET("/integration-kit", a.integrationKit)
secured.GET("/integration-kit/download", a.downloadIntegrationKit)
secured.GET("/integration-kit/archive", a.downloadIntegrationArchive)
secured.GET("/customers", a.listCustomers)
secured.POST("/customers", a.createCustomer)
secured.PUT("/customers/:id", a.updateCustomer)
secured.DELETE("/customers/:id", a.deleteCustomer)
secured.GET("/products", a.listProducts)
secured.POST("/products", a.createProduct)
secured.PUT("/products/:id", a.updateProduct)
secured.DELETE("/products/:id", a.deleteProduct)
secured.GET("/orders", a.listOrders)
secured.GET("/orders/:id", a.getOrder)
secured.POST("/orders", func(c *gin.Context) { a.writeOrder(c, "create") })
secured.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") })
secured.POST("/orders/:id/issue", func(c *gin.Context) { a.writeOrder(c, "issue") })
secured.GET("/licenses", a.listLicenses)
secured.GET("/licenses/:id", a.getLicense)
secured.GET("/licenses/:id/instances", a.listInstances)
secured.POST("/licenses/:id/instances", a.provisionInstance)
secured.GET("/licenses/:id/instance-credentials", a.instanceCredentials)
secured.DELETE("/licenses/:id", a.deleteLicense)
secured.POST("/products/:id/releases", a.createRelease)
secured.GET("/products/:id/releases", a.listReleases)
api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease)
secured.POST("/instances/:instance_id/freeze", a.freezeInstance)
secured.POST("/licenses", a.issueLicense)
secured.POST("/licenses/:id/revoke", func(c *gin.Context) { a.operateLicense(c, "revoke") })
secured.POST("/licenses/:id/restore", func(c *gin.Context) { a.operateLicense(c, "restore") })
secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") })
}
func (a *BusinessAPI) login(c *gin.Context) {
var in struct {
Username string `json:"username"`
Password string `json:"password"`
}
if c.ShouldBindJSON(&in) != nil {
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
return
}
username := strings.ToLower(strings.TrimSpace(in.Username))
if username == "" || in.Password == "" {
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
return
}
var id uint64
var hash string
var role string
var email string
err := a.db.QueryRowContext(c, "SELECT id,email,password_hash,role FROM admins WHERE username=? AND active=1", username).Scan(&id, &email, &hash, &role)
if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) != nil {
apiError(c, http.StatusUnauthorized, "invalid_credentials", "用户名或密码错误")
return
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
expires := time.Now().UTC().Add(8 * time.Hour)
sum := sha256.Sum256(raw)
if _, err = a.db.ExecContext(c, "INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", id, sum[:], expires); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.SetSameSite(http.SameSiteStrictMode)
secure := secureSessionCookie(c)
c.SetCookie("lp_session", hex.EncodeToString(raw), 8*3600, "/", "", secure, true)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"username": username, "email": email, "role": role, "expires_at": expires}})
}
func (a *BusinessAPI) authenticated(c *gin.Context) {
raw, err := c.Cookie("lp_session")
if err != nil || len(raw) != 64 {
apiError(c, 401, "unauthorized", "请先登录")
c.Abort()
return
}
decoded, err := hex.DecodeString(raw)
if err != nil {
apiError(c, 401, "unauthorized", "请先登录")
c.Abort()
return
}
sum := sha256.Sum256(decoded)
var id uint64
var username, email, role string
err = a.db.QueryRowContext(c, "SELECT a.id,a.username,a.email,a.role FROM sessions s JOIN admins a ON a.id=s.admin_id WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>? AND a.active=1", sum[:], time.Now().UTC()).Scan(&id, &username, &email, &role)
if err != nil {
apiError(c, 401, "unauthorized", "会话已失效")
c.Abort()
return
}
if role != "admin" {
apiError(c, http.StatusForbidden, "forbidden", "无权访问管理接口")
c.Abort()
return
}
c.Set("admin_id", id)
c.Set("admin_username", username)
c.Set("admin_email", email)
c.Set("admin_role", role)
c.Next()
}
func (a *BusinessAPI) logout(c *gin.Context) {
if raw, err := c.Cookie("lp_session"); err == nil {
if b, e := hex.DecodeString(raw); e == nil {
sum := sha256.Sum256(b)
_, _ = a.db.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC(), sum[:])
}
}
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie("lp_session", "", -1, "/", "", secureSessionCookie(c), true)
c.Status(http.StatusNoContent)
}
func (a *BusinessAPI) me(c *gin.Context) {
c.JSON(200, gin.H{"data": gin.H{"username": c.GetString("admin_username"), "email": c.GetString("admin_email"), "role": c.GetString("admin_role")}})
}
type customer struct {
ID uint64 `json:"id"`
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type product struct {
ID uint64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func page(c *gin.Context) (int, int) {
p, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if p < 1 {
p = 1
}
if size < 1 || size > 100 {
size = 20
}
return p, size
}
func (a *BusinessAPI) listCustomers(c *gin.Context) {
p, size := page(c)
q := strings.TrimSpace(c.Query("q"))
like := "%" + q + "%"
var total int
if err := a.db.QueryRowContext(c, "SELECT COUNT(*) FROM customers WHERE name LIKE ? OR contact_email LIKE ?", like, like).Scan(&total); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
rows, err := a.db.QueryContext(c, "SELECT id,name,contact_email,status,created_at,updated_at FROM customers WHERE name LIKE ? OR contact_email LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?", like, like, size, (p-1)*size)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer rows.Close()
out := []customer{}
for rows.Next() {
var x customer
if err := rows.Scan(&x.ID, &x.Name, &x.ContactEmail, &x.Status, &x.CreatedAt, &x.UpdatedAt); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out = append(out, x)
}
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
}
func (a *BusinessAPI) createCustomer(c *gin.Context) {
var in struct {
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
}
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
apiError(c, 400, "invalid_request", "客户名称和邮箱格式不正确")
return
}
res, err := a.db.ExecContext(c, "INSERT INTO customers(name,contact_email) VALUES(?,?)", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)))
if err != nil {
apiError(c, 409, "customer_conflict", "客户创建失败")
return
}
id, _ := res.LastInsertId()
c.JSON(201, gin.H{"data": gin.H{"id": id}})
}
func (a *BusinessAPI) updateCustomer(c *gin.Context) {
id := c.Param("id")
var in struct {
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
Status string `json:"status"`
}
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
apiError(c, 400, "invalid_request", "客户字段不正确")
return
}
res, err := a.db.ExecContext(c, "UPDATE customers SET name=?,contact_email=?,status=? WHERE id=?", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)), in.Status, id)
if err != nil || func() bool { n, _ := res.RowsAffected(); return n == 0 }() {
apiError(c, 404, "not_found", "客户不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) deleteCustomer(c *gin.Context) {
res, err := a.db.ExecContext(c, "DELETE FROM customers WHERE id=?", c.Param("id"))
if err != nil {
apiError(c, 500, "internal_error", "删除失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "客户不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) listProducts(c *gin.Context) {
rows, err := a.db.QueryContext(c, "SELECT id,code,name,description,active,created_at,updated_at FROM products ORDER BY id DESC")
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer rows.Close()
out := []product{}
for rows.Next() {
var x product
if rows.Scan(&x.ID, &x.Code, &x.Name, &x.Description, &x.Active, &x.CreatedAt, &x.UpdatedAt) != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out = append(out, x)
}
c.JSON(200, gin.H{"data": out})
}
func (a *BusinessAPI) createProduct(c *gin.Context) {
var in struct {
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
}
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
apiError(c, 400, "invalid_request", "产品编码和名称不能为空")
return
}
res, err := a.db.ExecContext(c, "INSERT INTO products(code,name,description) VALUES(?,?,?)", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description)
if err != nil {
apiError(c, 409, "product_conflict", "产品编码已存在")
return
}
id, _ := res.LastInsertId()
c.JSON(201, gin.H{"data": gin.H{"id": id}})
}
func (a *BusinessAPI) updateProduct(c *gin.Context) {
var in struct {
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
Active *bool `json:"active"`
}
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
apiError(c, 400, "invalid_request", "产品字段不正确")
return
}
active := true
if in.Active != nil {
active = *in.Active
}
res, err := a.db.ExecContext(c, "UPDATE products SET code=?,name=?,description=?,active=? WHERE id=?", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description, active, c.Param("id"))
if err != nil {
apiError(c, 409, "product_conflict", "产品更新失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "产品不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) deleteProduct(c *gin.Context) {
res, err := a.db.ExecContext(c, "DELETE FROM products WHERE id=?", c.Param("id"))
if err != nil {
apiError(c, 500, "internal_error", "删除失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "产品不存在")
return
}
c.Status(204)
}
func apiError(c *gin.Context, status int, code, message string) {
if status >= 500 {
message = "Service unavailable"
}
c.Set("error_code", code)
c.JSON(status, gin.H{"error": gin.H{"code": code, "message": message, "request_id": c.GetString("request_id")}})
}