70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
|
|
package handlers
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"prompt-generator/internal/auth"
|
||
|
|
"prompt-generator/internal/config"
|
||
|
|
"prompt-generator/internal/models"
|
||
|
|
)
|
||
|
|
|
||
|
|
var cfg *config.Config
|
||
|
|
|
||
|
|
func Init(c *config.Config) {
|
||
|
|
cfg = c
|
||
|
|
}
|
||
|
|
|
||
|
|
func writeJSON(w http.ResponseWriter, code int, resp models.APIResponse) {
|
||
|
|
w.Header().Set("Content-Type", "application/json")
|
||
|
|
w.WriteHeader(code)
|
||
|
|
json.NewEncoder(w).Encode(resp)
|
||
|
|
}
|
||
|
|
|
||
|
|
func success(w http.ResponseWriter, data interface{}) {
|
||
|
|
writeJSON(w, http.StatusOK, models.APIResponse{Code: 0, Message: "success", Data: data})
|
||
|
|
}
|
||
|
|
|
||
|
|
func fail(w http.ResponseWriter, httpCode int, msg string) {
|
||
|
|
writeJSON(w, httpCode, models.APIResponse{Code: httpCode, Message: msg})
|
||
|
|
}
|
||
|
|
|
||
|
|
func Login(w http.ResponseWriter, r *http.Request) {
|
||
|
|
var req struct {
|
||
|
|
Password string `json:"password"`
|
||
|
|
}
|
||
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||
|
|
fail(w, 400, "请求格式错误")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
if req.Password != cfg.AuthPassword {
|
||
|
|
fail(w, 401, "密码错误")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
session, _ := auth.Store.Get(r, "session")
|
||
|
|
session.Values["authenticated"] = true
|
||
|
|
session.Save(r, w)
|
||
|
|
|
||
|
|
success(w, nil)
|
||
|
|
}
|
||
|
|
|
||
|
|
func Logout(w http.ResponseWriter, r *http.Request) {
|
||
|
|
session, _ := auth.Store.Get(r, "session")
|
||
|
|
session.Values["authenticated"] = false
|
||
|
|
session.Options.MaxAge = -1
|
||
|
|
session.Save(r, w)
|
||
|
|
success(w, nil)
|
||
|
|
}
|
||
|
|
|
||
|
|
func AuthCheck(w http.ResponseWriter, r *http.Request) {
|
||
|
|
session, _ := auth.Store.Get(r, "session")
|
||
|
|
authed, ok := session.Values["authenticated"].(bool)
|
||
|
|
if !ok || !authed {
|
||
|
|
fail(w, 401, "未登录")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
success(w, map[string]bool{"authenticated": true})
|
||
|
|
}
|