sky/internal/transport/http/auth_handlers.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

201 lines
5.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/yourorg/article-platform/internal/domain"
"github.com/yourorg/article-platform/internal/platform/auth"
"github.com/yourorg/article-platform/internal/platform/httpx"
"github.com/yourorg/article-platform/internal/platform/idgen"
"github.com/yourorg/article-platform/internal/platform/middleware"
"github.com/yourorg/article-platform/internal/platform/rbac"
)
type registerReq struct {
Account string `json:"account"`
Password string `json:"password"`
Nickname string `json:"nickname"`
Email string `json:"email,omitempty"`
}
func (d *Deps) register(w http.ResponseWriter, r *http.Request) {
var req registerReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
req.Account = strings.TrimSpace(req.Account)
req.Nickname = strings.TrimSpace(req.Nickname)
if len(req.Account) < 3 || len(req.Account) > 32 {
httpx.WriteError(w, httpx.InvalidParam("账号长度需在 3~32 之间"))
return
}
if len(req.Password) < 8 {
httpx.WriteError(w, httpx.InvalidParam("密码至少 8 位"))
return
}
if req.Nickname == "" {
req.Nickname = req.Account
}
if strings.ContainsRune(req.Nickname, '\uFFFD') {
httpx.WriteError(w, httpx.InvalidParam("昵称包含非法编码或乱码字符"))
return
}
// 先查重,给用户明确提示。真正的唯一性由数据库唯一索引保证,
// 并发注册会撞索引,下面再兜一次。
if _, err := d.Users.GetByAccount(r.Context(), d.Pool, req.Account); err == nil {
httpx.WriteError(w, httpx.Conflict("账号已存在"))
return
}
hash, err := auth.HashPassword(req.Password)
if err != nil {
d.Log.Error("密码哈希失败", "err", err)
httpx.WriteError(w, err)
return
}
u := &domain.User{
ID: idgen.NewUUIDv7(),
Account: req.Account,
Nickname: req.Nickname,
Role: string(rbac.RoleAuthor),
Status: "active",
}
if req.Email != "" {
e := req.Email
u.Email = &e
}
if err := d.Users.Insert(r.Context(), d.Pool, u, hash); err != nil {
if strings.Contains(err.Error(), "uq_users_account") {
httpx.WriteError(w, httpx.Conflict("账号已存在"))
return
}
d.Log.Error("创建用户失败", "err", err)
httpx.WriteError(w, err)
return
}
token, err := d.issueToken(r, u)
if err != nil {
httpx.WriteError(w, err)
return
}
httpx.WriteCreated(w, map[string]any{"token": token, "user": u})
}
type loginReq struct {
Account string `json:"account"`
Password string `json:"password"`
}
func (d *Deps) login(w http.ResponseWriter, r *http.Request) {
var req loginReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
u, err := d.Users.GetByAccount(r.Context(), d.Pool, req.Account)
if err != nil {
// 账号不存在时也执行一次同等开销的哈希校验,
// 使响应时间与「密码错误」无法区分,防账号枚举。
auth.BurnTime(req.Password)
httpx.WriteError(w, httpx.NewError(http.StatusUnauthorized,
httpx.CodeUnauthorized, "账号或密码不正确"))
return
}
hash, err := d.Users.GetPasswordHash(r.Context(), d.Pool, u.ID)
if err != nil {
httpx.WriteError(w, httpx.ErrUnauthorized)
return
}
if err := auth.VerifyPassword(hash, req.Password); err != nil {
httpx.WriteError(w, httpx.NewError(http.StatusUnauthorized,
httpx.CodeUnauthorized, "账号或密码不正确"))
return
}
if u.Status != "active" {
httpx.WriteError(w, httpx.NewError(http.StatusForbidden,
httpx.CodeForbidden, "账号已被封禁"))
return
}
d.Users.TouchLogin(r.Context(), d.Pool, u.ID)
token, err := d.issueToken(r, u)
if err != nil {
httpx.WriteError(w, err)
return
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"token": token, "user": u})
}
// issueToken 生成随机令牌并写入 Valkey 会话。
// 不用自包含 JWT:会话在服务端,支持主动登出与封禁即时生效。
func (d *Deps) issueToken(r *http.Request, u *domain.User) (string, error) {
token, err := auth.RandomToken(32)
if err != nil {
return "", err
}
if err := d.Cache.SetSession(r.Context(), auth.TokenHash(token), u.ID, d.Cfg.JWTTTL); err != nil {
d.Log.Error("写入会话失败", "err", err)
return "", err
}
return token, nil
}
func (d *Deps) logout(w http.ResponseWriter, r *http.Request) {
h := r.Header.Get("Authorization")
if strings.HasPrefix(h, "Bearer ") {
d.Cache.DelSession(r.Context(), auth.TokenHash(strings.TrimSpace(h[7:])))
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (d *Deps) me(w http.ResponseWriter, r *http.Request) {
u, err := d.Users.GetByID(r.Context(), d.Pool, middleware.UserID(r.Context()))
if err != nil {
httpx.WriteError(w, httpx.ErrUnauthorized)
return
}
httpx.WriteJSON(w, http.StatusOK, u)
}
func (d *Deps) getUserProfile(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "userID")
u, err := d.Users.GetByID(r.Context(), d.Pool, id)
if err != nil {
httpx.WriteError(w, httpx.NotFound("用户不存在"))
return
}
followers, _ := d.Interacts.FollowerCount(r.Context(), d.Pool, id)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"user": u, "follower_count": followers})
}
func (d *Deps) myFollowers(w http.ResponseWriter, r *http.Request) {
uid := middleware.UserID(r.Context())
n, err := d.Interacts.FollowerCount(r.Context(), d.Pool, uid)
if err != nil {
httpx.WriteError(w, err)
return
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"follower_count": n})
}
func (d *Deps) myQuota(w http.ResponseWriter, r *http.Request) {
n, _ := d.Articles.Count(r.Context(), d.Pool, "", "")
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"tier": "free",
"article_used": n,
"article_limit": 100,
"updated_at": time.Now().UTC(),
})
}