- 新增 /uploads/thumb/{key}?w=:首访从存储端读一次原图,标准库盒均值缩放后
落盘 data/.thumbnail_cache(按内容哈希命名,天然失效);失败写 .failed 冷却
一小时,非图片/超大一律 302 回原图,前端无感。原图路由改用 ServeContent,
补上视频拖动进度条所需的 Range 支持
- 前端 thumbURL/thumbifyHtml 接入两套 UI 的时间线配图、长文封面与短文正文,
并补 loading=lazy;详情页与灯箱仍用原图。/api/site 改为
{settings, uploads_public_base},让前端识别哪些直链属于自家存储
- 后台登录的滑动窗口限速器抽成 internal/ratelimit 共享包(调用面不变),
新增:读者登录失败按 IP 20 次/10 分钟、评论写入按读者 5 条/分钟
(站主豁免,且只计成功写入)
894 lines
23 KiB
Go
894 lines
23 KiB
Go
// Package admin serves the authenticated surface at /api/admin/*.
|
|
// It is mounted separately from the public API so the two never share a
|
|
// handler chain.
|
|
package admin
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"oneblog/internal/config"
|
|
"oneblog/internal/httpx"
|
|
"oneblog/internal/model"
|
|
"oneblog/internal/storage"
|
|
"oneblog/internal/store"
|
|
)
|
|
|
|
type API struct {
|
|
Store *store.Store
|
|
Cfg *config.Config
|
|
Sessions *Sessions
|
|
// 文件上传的存储后端与公开域名(main.go 装配,两个 API 共享同一实例)
|
|
Blobs storage.BlobStore
|
|
PublicBase string
|
|
|
|
loginOnce sync.Once
|
|
logins *loginLimiter
|
|
}
|
|
|
|
func NewAPI(st *store.Store, cfg *config.Config, sessions *Sessions) *API {
|
|
a := &API{Store: st, Cfg: cfg, Sessions: sessions}
|
|
a.limiter()
|
|
return a
|
|
}
|
|
|
|
// limiter 惰性初始化,兼容测试里的 &API{...} 零值构造。
|
|
func (a *API) limiter() *loginLimiter {
|
|
a.loginOnce.Do(func() {
|
|
if a.logins == nil {
|
|
a.logins = newLoginLimiter()
|
|
}
|
|
})
|
|
return a.logins
|
|
}
|
|
|
|
const cookieName = "one_session"
|
|
|
|
func (a *API) Routes() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/api/admin/login", a.login)
|
|
mux.HandleFunc("/api/admin/logout", a.logout)
|
|
mux.HandleFunc("/api/admin/me", a.guard(a.me))
|
|
|
|
mux.HandleFunc("/api/admin/dashboard", a.guard(a.dashboard))
|
|
mux.HandleFunc("/api/admin/posts", a.guard(a.listPosts))
|
|
mux.HandleFunc("/api/admin/posts/", a.guard(a.postByID))
|
|
mux.HandleFunc("/api/admin/tags", a.guard(a.listTags))
|
|
mux.HandleFunc("/api/admin/tags/", a.guard(a.tagByID))
|
|
mux.HandleFunc("/api/admin/projects", a.guard(a.listProjects))
|
|
mux.HandleFunc("/api/admin/projects/", a.guard(a.projectByID))
|
|
mux.HandleFunc("/api/admin/files", a.guard(a.files))
|
|
mux.HandleFunc("/api/admin/files/", a.guard(a.fileByID))
|
|
mux.HandleFunc("/api/admin/settings", a.guard(a.settings))
|
|
mux.HandleFunc("/api/admin/comments", a.guard(a.adminComments))
|
|
mux.HandleFunc("/api/admin/comments/", a.guard(a.adminCommentByID))
|
|
mux.HandleFunc("/api/admin/readers", a.guard(a.adminReaders))
|
|
mux.HandleFunc("/api/admin/readers/", a.guard(func(w http.ResponseWriter, r *http.Request) {
|
|
// 路径形如 /api/admin/readers/{id}/ban
|
|
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/readers/"), "/")
|
|
parts := strings.Split(rest, "/")
|
|
if len(parts) != 2 || parts[1] != "ban" {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
id, err := strconv.ParseInt(parts[0], 10, 64)
|
|
if err != nil || id <= 0 {
|
|
httpx.BadRequest(w, "bad reader id")
|
|
return
|
|
}
|
|
a.adminReaderBan(w, r, id)
|
|
}))
|
|
return mux
|
|
}
|
|
|
|
// guard requires a valid session; the token may arrive as a cookie (browser)
|
|
// or as a Bearer token (CLI / API client).
|
|
func (a *API) guard(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
token := bearer(r)
|
|
if token == "" {
|
|
if c, err := r.Cookie(cookieName); err == nil {
|
|
token = c.Value
|
|
}
|
|
}
|
|
if token == "" || !a.valid(token) {
|
|
httpx.Unauthorized(w)
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func bearer(r *http.Request) string {
|
|
h := r.Header.Get("Authorization")
|
|
if strings.HasPrefix(strings.ToLower(h), "bearer ") {
|
|
return strings.TrimSpace(h[7:])
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (a *API) valid(token string) bool {
|
|
_, err := a.Sessions.Verify(token)
|
|
return err == nil
|
|
}
|
|
|
|
// ---------- auth ----------
|
|
|
|
type loginRequest struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
func (a *API) login(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "POST required")
|
|
return
|
|
}
|
|
key := sourceKey(r)
|
|
if a.limiter().Blocked(key) {
|
|
httpx.Error(w, http.StatusTooManyRequests, "失败次数过多,请 10 分钟后再试")
|
|
return
|
|
}
|
|
var in loginRequest
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
userOK := subtle.ConstantTimeCompare([]byte(in.Username), []byte(a.Cfg.AdminUser)) == 1
|
|
passOK := subtle.ConstantTimeCompare([]byte(in.Password), []byte(a.Cfg.AdminPass)) == 1
|
|
if !userOK || !passOK {
|
|
a.limiter().Add(key)
|
|
httpx.Unauthorized(w)
|
|
return
|
|
}
|
|
a.limiter().Reset(key)
|
|
token, exp := a.Sessions.Issue(a.Cfg.AdminUser)
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: cookieName,
|
|
Value: token,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: isTLS(r),
|
|
SameSite: http.SameSiteLaxMode,
|
|
Expires: exp,
|
|
MaxAge: a.Sessions.TTL(),
|
|
})
|
|
httpx.OK(w, map[string]any{"token": token, "expires_at": exp.UTC().Format(rfc3339)})
|
|
}
|
|
|
|
const rfc3339 = "2006-01-02T15:04:05Z07:00"
|
|
|
|
func (a *API) logout(w http.ResponseWriter, r *http.Request) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: cookieName,
|
|
Value: "",
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: isTLS(r),
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: -1,
|
|
})
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
}
|
|
|
|
func (a *API) me(w http.ResponseWriter, r *http.Request) {
|
|
httpx.OK(w, map[string]any{"user": a.Cfg.AdminUser})
|
|
}
|
|
|
|
// ---------- posts ----------
|
|
|
|
func (a *API) listPosts(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
o := store.ListOptions{
|
|
Kind: httpx.QueryString(r, "kind"),
|
|
Tag: httpx.QueryString(r, "tag"),
|
|
Query: httpx.QueryString(r, "q"),
|
|
Status: httpx.QueryString(r, "status"),
|
|
OrderBy: httpx.QueryString(r, "order"),
|
|
Page: httpx.QueryInt(r, "page", 1),
|
|
Size: httpx.QueryInt(r, "size", 20),
|
|
}
|
|
if o.Status == "" {
|
|
o.Status = "any"
|
|
}
|
|
page, err := a.Store.List(o)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, page)
|
|
case http.MethodPost:
|
|
var in model.PostInput
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
in.Status = store.NormalizeStatus(in.Status)
|
|
p, err := a.Store.Create(in)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.Created(w, p)
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/POST required")
|
|
}
|
|
}
|
|
|
|
func (a *API) postByID(w http.ResponseWriter, r *http.Request) {
|
|
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/posts/"), "/")
|
|
if rest == "" {
|
|
a.listPosts(w, r)
|
|
return
|
|
}
|
|
if rest == "bulk" {
|
|
a.bulkPosts(w, r)
|
|
return
|
|
}
|
|
id, err := parseInt(rest)
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad post id")
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
p, err := a.Store.Get(id)
|
|
writeOne(w, p, err)
|
|
case http.MethodPut, http.MethodPatch:
|
|
var in model.PostInput
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if in.Status != "" {
|
|
in.Status = store.NormalizeStatus(in.Status)
|
|
}
|
|
p, err := a.Store.Update(id, in)
|
|
writeOne(w, p, err)
|
|
case http.MethodDelete:
|
|
if err := a.Store.Delete(id); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/PUT/DELETE required")
|
|
}
|
|
}
|
|
|
|
func writeOne(w http.ResponseWriter, p model.Post, err error) {
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, p)
|
|
}
|
|
|
|
// ---------- tags ----------
|
|
|
|
func (a *API) listTags(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
tags, err := a.Store.ListTags()
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
if tags == nil {
|
|
tags = []model.Tag{}
|
|
}
|
|
httpx.OK(w, map[string]any{"tags": tags})
|
|
case http.MethodPost:
|
|
var in struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
name := strings.TrimSpace(in.Name)
|
|
if name == "" {
|
|
httpx.BadRequest(w, "name required")
|
|
return
|
|
}
|
|
t, err := a.Store.CreateTag(name)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.Created(w, t)
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/POST required")
|
|
}
|
|
}
|
|
|
|
func (a *API) tagByID(w http.ResponseWriter, r *http.Request) {
|
|
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/tags/"), "/")
|
|
parts := strings.SplitN(rest, "/", 2)
|
|
id, err := parseInt(parts[0])
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad tag id")
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "merge" {
|
|
a.mergeTag(w, r, id)
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodPut, http.MethodPatch:
|
|
var in struct {
|
|
Name string `json:"name"`
|
|
Color string `json:"color"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
t, err := a.Store.UpdateTag(id, in.Name, in.Color)
|
|
writeTag(w, t, err)
|
|
case http.MethodDelete:
|
|
if err := a.Store.DeleteTag(id); err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "PUT/DELETE required")
|
|
}
|
|
}
|
|
|
|
func (a *API) mergeTag(w http.ResponseWriter, r *http.Request, fromID int64) {
|
|
if r.Method != http.MethodPost {
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "POST required")
|
|
return
|
|
}
|
|
var in struct {
|
|
ToID int64 `json:"to_id"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if in.ToID == 0 {
|
|
httpx.BadRequest(w, "to_id required")
|
|
return
|
|
}
|
|
t, err := a.Store.MergeTags(fromID, in.ToID)
|
|
writeTag(w, t, err)
|
|
}
|
|
|
|
func writeTag(w http.ResponseWriter, t model.Tag, err error) {
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.Error(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
httpx.OK(w, t)
|
|
}
|
|
|
|
// ---------- projects ----------
|
|
|
|
func (a *API) listProjects(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
status := httpx.QueryString(r, "status")
|
|
projects, err := a.Store.ListProjects(status)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
if projects == nil {
|
|
projects = []model.Project{}
|
|
}
|
|
httpx.OK(w, map[string]any{"projects": projects})
|
|
case http.MethodPost:
|
|
var in model.ProjectInput
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if strings.TrimSpace(in.Title) == "" {
|
|
httpx.BadRequest(w, "title required")
|
|
return
|
|
}
|
|
p, err := a.Store.CreateProject(in)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.Created(w, p)
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/POST required")
|
|
}
|
|
}
|
|
|
|
func (a *API) projectByID(w http.ResponseWriter, r *http.Request) {
|
|
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/projects/"), "/")
|
|
if rest == "" {
|
|
a.listProjects(w, r)
|
|
return
|
|
}
|
|
id, err := parseInt(rest)
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad project id")
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
p, err := a.Store.GetProject(id)
|
|
writeProject(w, p, err)
|
|
case http.MethodPut, http.MethodPatch:
|
|
var in model.ProjectInput
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
p, err := a.Store.UpdateProject(id, in)
|
|
writeProject(w, p, err)
|
|
case http.MethodDelete:
|
|
if err := a.Store.DeleteProject(id); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/PUT/DELETE required")
|
|
}
|
|
}
|
|
|
|
func writeProject(w http.ResponseWriter, p model.Project, err error) {
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, p)
|
|
}
|
|
|
|
// ---------- settings ----------
|
|
|
|
func (a *API) settings(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
st, err := a.Store.GetSettings()
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, st)
|
|
case http.MethodPut, http.MethodPost:
|
|
var in model.Settings
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if err := a.Store.UpdateSettings(in); err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
st, err := a.Store.GetSettings()
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, st)
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/PUT required")
|
|
}
|
|
}
|
|
|
|
func parseInt(s string) (int64, error) {
|
|
if s == "" {
|
|
return 0, errors.New("empty")
|
|
}
|
|
var n int64
|
|
for _, c := range s {
|
|
if c < '0' || c > '9' {
|
|
return 0, errors.New("not a number")
|
|
}
|
|
n = n*10 + int64(c-'0')
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// ---------- dashboard ----------
|
|
|
|
func (a *API) dashboard(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET required")
|
|
return
|
|
}
|
|
d, err := a.Store.Dashboard()
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, d)
|
|
}
|
|
|
|
// ---------- bulk posts ----------
|
|
|
|
type bulkPostsRequest struct {
|
|
IDs []int64 `json:"ids"`
|
|
Action string `json:"action"` // "publish" | "draft" | "delete"
|
|
}
|
|
|
|
func (a *API) bulkPosts(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "POST required")
|
|
return
|
|
}
|
|
var in bulkPostsRequest
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if len(in.IDs) == 0 {
|
|
httpx.BadRequest(w, "ids required")
|
|
return
|
|
}
|
|
switch in.Action {
|
|
case "publish", "draft":
|
|
n, err := a.Store.BulkUpdateStatus(in.IDs, store.NormalizeStatus(in.Action))
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true, "updated": n})
|
|
case "delete":
|
|
var failed int
|
|
for _, id := range in.IDs {
|
|
if err := a.Store.Delete(id); err != nil {
|
|
failed++
|
|
}
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true, "deleted": len(in.IDs) - failed, "failed": failed})
|
|
default:
|
|
httpx.BadRequest(w, "action must be one of publish|draft|delete")
|
|
}
|
|
}
|
|
|
|
// ---------- files(上传与文件管理) ----------
|
|
|
|
// 单文件上限与类型白名单。SVG 拒绝:同源内联可执行脚本。
|
|
const (
|
|
maxFileUpload = 50 << 20
|
|
)
|
|
|
|
var allowFileExt = map[string]string{
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".png": "image/png",
|
|
".webp": "image/webp",
|
|
".gif": "image/gif",
|
|
".avif": "image/avif",
|
|
".pdf": "application/pdf",
|
|
".zip": "application/zip",
|
|
".txt": "text/plain",
|
|
}
|
|
|
|
func (a *API) files(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
fp, err := a.Store.ListFiles(httpx.QueryInt(r, "page", 1), httpx.QueryInt(r, "size", 20), httpx.QueryString(r, "q"))
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
for i := range fp.Items {
|
|
fp.Items[i].URL = storage.FileURL(fp.Items[i].Store, fp.Items[i].Key, a.Cfg.UploadsPublicBase)
|
|
}
|
|
httpx.OK(w, fp)
|
|
case http.MethodPost:
|
|
a.uploadFiles(w, r)
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/POST required")
|
|
}
|
|
}
|
|
|
|
func (a *API) uploadFiles(w http.ResponseWriter, r *http.Request) {
|
|
// 64MB = 50MB 文件 + multipart 编码开销
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxFileUpload+(8<<20))
|
|
if err := r.ParseMultipartForm(8 << 20); err != nil {
|
|
httpx.BadRequest(w, "上传失败:请求体超过上限(单文件 50MB)")
|
|
return
|
|
}
|
|
if r.MultipartForm != nil {
|
|
defer r.MultipartForm.RemoveAll()
|
|
}
|
|
fhs := r.MultipartForm.File["file"]
|
|
if len(fhs) == 0 {
|
|
httpx.BadRequest(w, "没有收到文件")
|
|
return
|
|
}
|
|
out := make([]model.File, 0, len(fhs))
|
|
for _, fh := range fhs {
|
|
f, err := a.storeOne(r.Context(), fh)
|
|
if err != nil {
|
|
if bu, ok := err.(badUpload); ok {
|
|
httpx.BadRequest(w, string(bu))
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
out = append(out, f)
|
|
}
|
|
// URL 统一在这里解析:storeOne 的「去重复用已有行」路径也不例外
|
|
for i := range out {
|
|
out[i].URL = storage.FileURL(out[i].Store, out[i].Key, a.Cfg.UploadsPublicBase)
|
|
}
|
|
httpx.Created(w, out)
|
|
}
|
|
|
|
// badUpload 区分「文件本身的问题」(类型 / 大小 → 400 直接告诉站主)与
|
|
// 服务器故障(500,已入库的部分保留)。
|
|
type badUpload string
|
|
|
|
func (e badUpload) Error() string { return string(e) }
|
|
|
|
// storeOne 校验、哈希、落盘单个文件。内容哈希做 key(同年月分目录),
|
|
// 同内容重复上传直接复用已有行,不产生孤儿对象。
|
|
func (a *API) storeOne(ctx context.Context, fh *multipart.FileHeader) (model.File, error) {
|
|
if fh.Size > maxFileUpload {
|
|
return model.File{}, badUpload(fmt.Sprintf("%s:超过单文件 50MB 上限", fh.Filename))
|
|
}
|
|
ext := strings.ToLower(filepath.Ext(fh.Filename))
|
|
mime, ok := allowFileExt[ext]
|
|
if !ok {
|
|
return model.File{}, badUpload(fmt.Sprintf("%s:不支持的类型 %q", fh.Filename, ext))
|
|
}
|
|
src, err := fh.Open()
|
|
if err != nil {
|
|
return model.File{}, err
|
|
}
|
|
defer src.Close()
|
|
|
|
// 头 512 字节给 http.DetectContentType 嗅探真实类型,全文流过 sha256,
|
|
// 同时落到临时文件(S3 PutObject 需要确定的 ContentLength)。
|
|
tmp, err := os.CreateTemp("", "one-upload-*")
|
|
if err != nil {
|
|
return model.File{}, err
|
|
}
|
|
defer os.Remove(tmp.Name())
|
|
hasher := sha256.New()
|
|
head := make([]byte, 512)
|
|
hn, _ := io.ReadFull(src, head)
|
|
head = head[:hn]
|
|
for _, w := range []io.Writer{tmp, hasher} {
|
|
if _, err := w.Write(head); err != nil {
|
|
tmp.Close()
|
|
return model.File{}, err
|
|
}
|
|
}
|
|
copied, err := io.Copy(io.MultiWriter(tmp, hasher), src)
|
|
if err != nil {
|
|
tmp.Close()
|
|
return model.File{}, err
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
return model.File{}, err
|
|
}
|
|
size := int64(hn) + copied
|
|
|
|
// 嗅探结果必须与扩展名声明的类型完全一致(防改后缀绕过白名单)。
|
|
// 不给 octet-stream 留口子:一张「image/png」嗅探出 octet-stream
|
|
// 就绝不是 PNG——随机字节改名上传就是这么溜进来的。
|
|
detected := strings.SplitN(http.DetectContentType(head), ";", 2)[0]
|
|
if detected != mime {
|
|
return model.File{}, badUpload(fmt.Sprintf("%s:文件内容与扩展名不符", fh.Filename))
|
|
}
|
|
|
|
sum := hex.EncodeToString(hasher.Sum(nil))
|
|
key := fmt.Sprintf("%s/%s%s", time.Now().UTC().Format("2006/01"), sum[:12], ext)
|
|
// S3Api 端点带路径段时(如 .../oss),该段会折进对象 key——
|
|
// 数据库必须记录同样的完整 key,直链才不会 404
|
|
if p := storage.EndpointKeyPrefix(a.Cfg.S3Endpoint); p != "" {
|
|
key = p + "/" + key
|
|
}
|
|
|
|
// 内容去重:同一份内容只存一份,复用已有行
|
|
if exist, err := a.Store.GetFileByKey(key); err == nil {
|
|
return exist, nil
|
|
}
|
|
|
|
f, err := os.Open(tmp.Name())
|
|
if err != nil {
|
|
return model.File{}, err
|
|
}
|
|
defer f.Close()
|
|
if err := a.Blobs.Put(ctx, key, f, size, mime); err != nil {
|
|
return model.File{}, err
|
|
}
|
|
|
|
created, err := a.Store.CreateFile(model.File{
|
|
Key: key,
|
|
Name: fh.Filename,
|
|
Mime: mime,
|
|
Size: size,
|
|
SHA256: sum,
|
|
Store: a.Cfg.StorageDriver,
|
|
})
|
|
if err != nil {
|
|
return model.File{}, err
|
|
}
|
|
created.URL = storage.FileURL(created.Store, created.Key, a.Cfg.UploadsPublicBase)
|
|
return created, nil
|
|
}
|
|
|
|
func (a *API) fileByID(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseInt(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/files/"), "/"))
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad file id")
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
f, err := a.Store.GetFile(id)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
f.URL = storage.FileURL(f.Store, f.Key, a.Cfg.UploadsPublicBase)
|
|
httpx.OK(w, f)
|
|
case http.MethodDelete:
|
|
f, err := a.Store.GetFile(id)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
// 先删对象存储再删行:存储端失败时行保留,可以重试
|
|
if err := a.Blobs.Delete(r.Context(), f.Key); err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
if _, err := a.Store.DeleteFile(id); err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET/DELETE required")
|
|
}
|
|
}
|
|
|
|
// ---------- comments(评论审核与管理) ----------
|
|
|
|
func (a *API) adminComments(w http.ResponseWriter, r *http.Request) {
|
|
status := httpx.QueryString(r, "status")
|
|
page := httpx.QueryInt(r, "page", 1)
|
|
size := httpx.QueryInt(r, "size", 20)
|
|
fp, err := a.Store.ListCommentsAdmin(status, page, size)
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, fp)
|
|
}
|
|
|
|
func (a *API) adminCommentByID(w http.ResponseWriter, r *http.Request) {
|
|
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/admin/comments/"), "/")
|
|
id, err := parseInt(rest)
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad comment id")
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodPut:
|
|
// 审核动作:{"status": "visible" | "pending"}
|
|
var in struct {
|
|
Status string `json:"status"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
if in.Status != "visible" && in.Status != "pending" {
|
|
httpx.BadRequest(w, "status 只支持 visible / pending")
|
|
return
|
|
}
|
|
if err := a.Store.SetCommentStatus(id, in.Status); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
case http.MethodDelete:
|
|
// 后台删除同样走软删(墓碑保楼层)
|
|
if err := a.Store.DeleteComment(id); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "PUT/DELETE required")
|
|
}
|
|
}
|
|
|
|
// ---------- readers(评论用户与禁言) ----------
|
|
|
|
func (a *API) adminReaders(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
readers, err := a.Store.ListReaders()
|
|
if err != nil {
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"readers": readers})
|
|
default:
|
|
httpx.Error(w, http.StatusMethodNotAllowed, "GET required")
|
|
}
|
|
}
|
|
|
|
func (a *API) adminReaderBan(w http.ResponseWriter, r *http.Request, id int64) {
|
|
var in struct {
|
|
Banned bool `json:"banned"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
// 站主身份(管理员会话映射出来的读者)不允许禁言
|
|
if rd, err := a.Store.GetReader(id); err == nil && rd.Provider == "admin" {
|
|
httpx.BadRequest(w, "不能禁言站主身份")
|
|
return
|
|
}
|
|
if err := a.Store.SetReaderBanned(id, in.Banned); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
httpx.NotFound(w)
|
|
return
|
|
}
|
|
httpx.ServerError(w, err)
|
|
return
|
|
}
|
|
httpx.OK(w, map[string]any{"ok": true, "banned": in.Banned})
|
|
}
|