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>
247 lines
7.9 KiB
Go
247 lines
7.9 KiB
Go
package httpapi
|
||
|
||
import (
|
||
"errors"
|
||
"net/http"
|
||
"net/mail"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/go-sql-driver/mysql"
|
||
"golang.org/x/crypto/bcrypt"
|
||
)
|
||
|
||
type adminAccount struct {
|
||
ID uint64 `json:"id"`
|
||
Username string `json:"username"`
|
||
Email string `json:"email"`
|
||
Active bool `json:"active"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
func normalizeAdminUsername(value string) string { return strings.ToLower(strings.TrimSpace(value)) }
|
||
func validAdminUsername(value string) bool {
|
||
if len(value) < 3 || len(value) > 32 {
|
||
return false
|
||
}
|
||
for _, r := range value {
|
||
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
func validAdminPassword(value string) bool { return value != "" && len(value) <= 72 }
|
||
|
||
func (a *BusinessAPI) listAdmins(c *gin.Context) {
|
||
rows, err := a.db.QueryContext(c, "SELECT id,username,email,active,created_at FROM admins ORDER BY id")
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||
return
|
||
}
|
||
defer rows.Close()
|
||
items := []adminAccount{}
|
||
for rows.Next() {
|
||
var item adminAccount
|
||
if err = rows.Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||
return
|
||
}
|
||
items = append(items, item)
|
||
}
|
||
if rows.Err() != nil {
|
||
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": items})
|
||
}
|
||
|
||
func (a *BusinessAPI) createAdmin(c *gin.Context) {
|
||
var in struct {
|
||
Username string `json:"username"`
|
||
Email string `json:"email"`
|
||
Password string `json:"password"`
|
||
}
|
||
if c.ShouldBindJSON(&in) != nil {
|
||
apiError(c, 400, "invalid_request", "用户名、邮箱和密码不能为空")
|
||
return
|
||
}
|
||
in.Username = normalizeAdminUsername(in.Username)
|
||
in.Email = strings.ToLower(strings.TrimSpace(in.Email))
|
||
address, emailErr := mail.ParseAddress(in.Email)
|
||
if !validAdminUsername(in.Username) || emailErr != nil || address.Address != in.Email || len(in.Email) > 190 || !validAdminPassword(in.Password) {
|
||
apiError(c, 400, "invalid_request", "用户名须为 3–32 位小写字母、数字、下划线或短横线;邮箱和密码必须有效")
|
||
return
|
||
}
|
||
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), 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()
|
||
result, err := tx.ExecContext(c, "INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", in.Username, in.Email, string(hash))
|
||
if err != nil {
|
||
var duplicate *mysql.MySQLError
|
||
if errors.As(err, &duplicate) && duplicate.Number == 1062 {
|
||
apiError(c, 409, "conflict", "用户名或邮箱已存在")
|
||
} else {
|
||
apiError(c, 500, "internal_error", "管理员创建失败")
|
||
}
|
||
return
|
||
}
|
||
id, _ := result.LastInsertId()
|
||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.created','admin',?,?)", c.GetUint64("admin_id"), id, `{"fields":["username","email"]}`); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员创建失败")
|
||
return
|
||
}
|
||
if err = tx.Commit(); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员创建结果未确认,请刷新检查")
|
||
return
|
||
}
|
||
var item adminAccount
|
||
if err = a.db.QueryRowContext(c, "SELECT id,username,email,active,created_at FROM admins WHERE id=?", id).Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员已创建,请刷新检查")
|
||
return
|
||
}
|
||
c.JSON(http.StatusCreated, gin.H{"data": item})
|
||
}
|
||
|
||
func (a *BusinessAPI) setAdminActive(c *gin.Context) {
|
||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||
if err != nil || id == 0 {
|
||
apiError(c, 400, "invalid_request", "管理员 ID 无效")
|
||
return
|
||
}
|
||
var in struct {
|
||
Active *bool `json:"active"`
|
||
}
|
||
if c.ShouldBindJSON(&in) != nil || in.Active == nil {
|
||
apiError(c, 400, "invalid_request", "必须指定 active")
|
||
return
|
||
}
|
||
if id == c.GetUint64("admin_id") && !*in.Active {
|
||
apiError(c, 400, "invalid_request", "不能停用当前登录的管理员")
|
||
return
|
||
}
|
||
tx, err := a.db.BeginTx(c, nil)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||
return
|
||
}
|
||
defer tx.Rollback()
|
||
// Lock accounts in a stable order to serialize simultaneous disable operations.
|
||
rows, err := tx.QueryContext(c, "SELECT id,active FROM admins ORDER BY id FOR UPDATE")
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||
return
|
||
}
|
||
found, current, actorActive := false, false, false
|
||
for rows.Next() {
|
||
var accountID uint64
|
||
var active bool
|
||
if err = rows.Scan(&accountID, &active); err != nil {
|
||
break
|
||
}
|
||
if accountID == id {
|
||
found, current = true, active
|
||
}
|
||
if accountID == c.GetUint64("admin_id") {
|
||
actorActive = active
|
||
}
|
||
}
|
||
if err == nil {
|
||
err = rows.Err()
|
||
}
|
||
rows.Close()
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||
return
|
||
}
|
||
if !actorActive {
|
||
apiError(c, 401, "unauthorized", "当前管理员已停用")
|
||
return
|
||
}
|
||
if !found {
|
||
apiError(c, 404, "not_found", "管理员不存在")
|
||
return
|
||
}
|
||
if current == *in.Active {
|
||
c.Status(http.StatusNoContent)
|
||
return
|
||
}
|
||
if _, err = tx.ExecContext(c, "UPDATE admins SET active=? WHERE id=?", *in.Active, id); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||
return
|
||
}
|
||
if !*in.Active {
|
||
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id)
|
||
}
|
||
if err == nil {
|
||
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.active_changed','admin',?,?)", c.GetUint64("admin_id"), id, `{"active":`+map[bool]string{true: "true", false: "false"}[*in.Active]+`}`)
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||
return
|
||
}
|
||
if err = tx.Commit(); err != nil {
|
||
apiError(c, 500, "internal_error", "管理员状态更新结果未确认,请刷新检查")
|
||
return
|
||
}
|
||
c.Status(http.StatusNoContent)
|
||
}
|
||
|
||
func (a *BusinessAPI) resetAdminPassword(c *gin.Context) {
|
||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||
if err != nil || id == 0 {
|
||
apiError(c, 400, "invalid_request", "管理员 ID 无效")
|
||
return
|
||
}
|
||
var in struct {
|
||
Password string `json:"password"`
|
||
}
|
||
if c.ShouldBindJSON(&in) != nil || !validAdminPassword(in.Password) {
|
||
apiError(c, 400, "invalid_request", "新密码不能为空,且最多 72 字节")
|
||
return
|
||
}
|
||
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), 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()
|
||
result, err := tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码重置失败")
|
||
return
|
||
}
|
||
affected, _ := result.RowsAffected()
|
||
if affected == 0 {
|
||
apiError(c, 404, "not_found", "管理员不存在")
|
||
return
|
||
}
|
||
if _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id); err == nil {
|
||
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_reset','admin',?,?)", c.GetUint64("admin_id"), id, `{"sessions_revoked":true}`)
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "密码重置失败")
|
||
return
|
||
}
|
||
if err = tx.Commit(); err != nil {
|
||
apiError(c, 500, "internal_error", "密码重置结果未确认,请刷新检查")
|
||
return
|
||
}
|
||
c.Status(http.StatusNoContent)
|
||
}
|