351 lines
8.1 KiB
Go
351 lines
8.1 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 (
|
|
"crypto/subtle"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"oneblog/internal/config"
|
|
"oneblog/internal/httpx"
|
|
"oneblog/internal/model"
|
|
"oneblog/internal/store"
|
|
)
|
|
|
|
type API struct {
|
|
Store *store.Store
|
|
Cfg *config.Config
|
|
Sessions *Sessions
|
|
}
|
|
|
|
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/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/settings", a.guard(a.settings))
|
|
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
|
|
}
|
|
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 {
|
|
httpx.Unauthorized(w)
|
|
return
|
|
}
|
|
token, exp := a.Sessions.Issue(a.Cfg.AdminUser)
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: cookieName,
|
|
Value: token,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
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,
|
|
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"),
|
|
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 = 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 normalizeStatus(s string) string {
|
|
switch strings.ToLower(strings.TrimSpace(s)) {
|
|
case model.StatusDraft, model.StatusPublished:
|
|
return strings.ToLower(strings.TrimSpace(s))
|
|
default:
|
|
return model.StatusDraft
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
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 = 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/"), "/")
|
|
id, err := parseInt(rest)
|
|
if err != nil {
|
|
httpx.BadRequest(w, "bad tag id")
|
|
return
|
|
}
|
|
switch r.Method {
|
|
case http.MethodPut, http.MethodPatch:
|
|
var in struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if err := httpx.Decode(r, &in); err != nil {
|
|
httpx.BadRequest(w, "invalid body")
|
|
return
|
|
}
|
|
t, err := a.Store.RenameTag(id, in.Name)
|
|
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 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)
|
|
}
|
|
|
|
// ---------- 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
|
|
}
|