新增 Web 浏览端(Go+Vue 报表系统)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
fish
2026-05-03 14:34:50 +08:00
parent bf8f578761
commit 750584e619
47 changed files with 2557 additions and 18 deletions

View File

@@ -0,0 +1,90 @@
package handlers
import (
"encoding/json"
"net/http"
"strings"
"trade/web/internal/auth"
"trade/web/internal/middleware"
"trade/web/internal/store"
)
type loginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
type loginResp struct {
Token string `json:"token"`
User publicUserView `json:"user"`
}
type publicUserView struct {
ID int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
}
func (d *Deps) Login(w http.ResponseWriter, r *http.Request) {
var req loginReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid json")
return
}
req.Username = strings.TrimSpace(req.Username)
if req.Username == "" || req.Password == "" {
writeErr(w, http.StatusBadRequest, "用户名和密码不能为空")
return
}
u, err := d.Auth.GetByUsername(req.Username)
if err != nil || u.Disabled {
// 禁用账户与不存在账户返回同样的错误,避免账户枚举
writeErr(w, http.StatusUnauthorized, "用户名或密码错误")
return
}
if !auth.CheckPassword(u.PasswordHash, req.Password) {
writeErr(w, http.StatusUnauthorized, "用户名或密码错误")
return
}
token, _, err := d.JWT.Issue(u.ID, u.Username, u.Role)
if err != nil {
writeErr(w, http.StatusInternalServerError, "issue token failed")
return
}
writeJSON(w, http.StatusOK, loginResp{
Token: token,
User: publicUserView{ID: u.ID, Username: u.Username, Role: u.Role},
})
}
func (d *Deps) Logout(w http.ResponseWriter, r *http.Request) {
// JWT 是无状态的,服务端 logout 仅形式化;前端丢弃 token 即可。
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (d *Deps) Me(w http.ResponseWriter, r *http.Request) {
u, ok := middleware.FromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "no user in context")
return
}
full, err := d.Auth.GetByID(u.ID)
if err != nil {
writeErr(w, http.StatusUnauthorized, "user not found")
return
}
writeJSON(w, http.StatusOK, sanitize(full))
}
// sanitize 把内部 User 转成对外视图,剥掉 password_hash。
func sanitize(u *store.User) map[string]any {
return map[string]any{
"id": u.ID,
"username": u.Username,
"role": u.Role,
"disabled": u.Disabled,
"created_at": u.CreatedAt,
"updated_at": u.UpdatedAt,
}
}