87 lines
2.2 KiB
Go
87 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
// GET /api/cookies -> {"cookies": {"name":"value",...}}
|
|
// POST /api/cookies -> accepts either {"cookies": {...}} or a plain JSON object {...}
|
|
// DELETE /api/cookies -> clears stored cookies
|
|
func cookiesHandler(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
s := getSettings()
|
|
cookies, err := decryptCookieMap(s.EncryptedCookies)
|
|
if err != nil {
|
|
http.Error(w, "could not decrypt cookies: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"cookies": cookies})
|
|
return
|
|
|
|
case http.MethodPost:
|
|
// body can be {"cookies": {...}} or just {...}
|
|
b, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "could not read body: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
type payload struct {
|
|
Cookies map[string]string `json:"cookies"`
|
|
}
|
|
var p payload
|
|
if err := json.Unmarshal(b, &p); err != nil {
|
|
http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
cookies := p.Cookies
|
|
if cookies == nil {
|
|
// fallback: plain object
|
|
var m map[string]string
|
|
if err := json.Unmarshal(b, &m); err == nil {
|
|
cookies = m
|
|
}
|
|
}
|
|
if cookies == nil {
|
|
http.Error(w, "invalid json: expected {\"cookies\":{...}} or {...}", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
blob, err := encryptCookieMap(cookies)
|
|
if err != nil {
|
|
http.Error(w, "could not encrypt cookies: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
settingsMu.Lock()
|
|
s := settings
|
|
s.EncryptedCookies = blob
|
|
settings = s
|
|
settingsMu.Unlock()
|
|
saveSettingsToDisk()
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "count": len(normalizeCookieMap(cookies))})
|
|
return
|
|
|
|
case http.MethodDelete:
|
|
settingsMu.Lock()
|
|
s := settings
|
|
s.EncryptedCookies = ""
|
|
settings = s
|
|
settingsMu.Unlock()
|
|
saveSettingsToDisk()
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
|
|
default:
|
|
http.Error(w, "Nur GET/POST/DELETE erlaubt", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
}
|