阶段十:完成 Go 基础包注释基线清零
This commit is contained in:
1 parent
ea1f2ec430
commit
d1a165f897
14 files changed
+135
-924
No files matched your search
@@ -25,6 +25,7 @@ const CookieMaxAge = 24 * 60 * 60
|
||||
// ctxKey 上下文键类型,避免冲突。
|
||||
type ctxKey int
|
||||
|
||||
// ctxKeyUser 保存ctxKey用户,供当前处理流程使用
|
||||
const (
|
||||
ctxKeyUser ctxKey = iota
|
||||
)
|
||||
@@ -45,6 +46,7 @@ type LoginResult struct {
|
||||
|
||||
// Login 用户名密码登录。成功时返回会话 ID(由调用方写入 Cookie)。
|
||||
func (s *Service) Login(ctx context.Context, username, password string) (string, *db.User, error) {
|
||||
// user、ok、err 保存user、ok、err,供当前处理流程使用
|
||||
user, ok, err := s.Store.Users.VerifyAndUpgrade(ctx, username, password)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -52,6 +54,7 @@ func (s *Service) Login(ctx context.Context, username, password string) (string,
|
||||
if !ok {
|
||||
return "", nil, nil // 密码错误或用户不存在/未激活
|
||||
}
|
||||
// sid、err 保存sid、err,供当前处理流程使用
|
||||
sid, err := s.Store.Sessions.Create(ctx, user)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -96,10 +99,12 @@ func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
|
||||
|
||||
// SessionFromRequest 从请求 Cookie 取会话。无效返回 nil。
|
||||
func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.Session, error) {
|
||||
// c、err 保存c、err,供当前处理流程使用
|
||||
c, err := r.Cookie(CookieName)
|
||||
if err != nil || c.Value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
// sess、err 保存sess、err,供当前处理流程使用
|
||||
sess, err := s.Store.Sessions.Get(ctx, c.Value)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
@@ -113,10 +118,12 @@ func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.
|
||||
// Middleware 解析会话并把 *db.Session 放入请求上下文。不强制登录(公开路由也可用)。
|
||||
func (s *Service) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess、err 保存sess、err,供当前处理流程使用
|
||||
sess, err := s.SessionFromRequest(r.Context(), r)
|
||||
if err != nil {
|
||||
s.Logger.Warn("读取会话失败", "err", err)
|
||||
}
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := WithSession(r.Context(), sess)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
@@ -136,6 +143,7 @@ func RequireAuth(next http.Handler) http.Handler {
|
||||
// RequireAdmin 要求管理员,否则 403(须在 RequireAuth 之后)。
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := SessionFromContext(r.Context())
|
||||
if sess == nil || !sess.IsAdmin {
|
||||
writeAuthError(w, r, http.StatusForbidden, "forbidden", "需要管理员权限")
|
||||
@@ -150,7 +158,9 @@ func WithSession(ctx context.Context, sess *db.Session) context.Context {
|
||||
return context.WithValue(ctx, ctxKeyUser, sess)
|
||||
}
|
||||
|
||||
// SessionFromContext 负责会话From上下文相关处理。
|
||||
func SessionFromContext(ctx context.Context) *db.Session {
|
||||
// v 保存v,供当前处理流程使用
|
||||
v, _ := ctx.Value(ctxKeyUser).(*db.Session)
|
||||
return v
|
||||
}
|
||||
@@ -158,12 +168,15 @@ func SessionFromContext(ctx context.Context) *db.Session {
|
||||
// InitAdmin 创建或重置 admin 管理员账号,是 cmd/server -init-admin 与
|
||||
// cmd/init-admin 共用的公共入口。返回 created=true 表示新建 admin,
|
||||
// false 表示重置已存在 admin 的密码。邮箱仅在新建时使用。
|
||||
// InitAdmin 负责InitAdmin相关处理。
|
||||
func InitAdmin(ctx context.Context, store *db.Store, email, password string) (created bool, err error) {
|
||||
// existing、err 保存existing、err,供当前处理流程使用
|
||||
existing, err := store.Users.GetAdmin(ctx)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
return false, fmt.Errorf("查询 admin 失败: %w", err)
|
||||
}
|
||||
if existing != nil {
|
||||
// ok、err 保存ok、err,供当前处理流程使用
|
||||
ok, err := store.Users.UpdatePassword(ctx, existing.Username, password)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -173,6 +186,7 @@ func InitAdmin(ctx context.Context, store *db.Store, email, password string) (cr
|
||||
}
|
||||
return false, store.Users.SetAdmin(ctx, existing.Username)
|
||||
}
|
||||
// ok、err 保存ok、err,供当前处理流程使用
|
||||
ok, err := store.Users.Create(ctx, "admin", email, password)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -11,28 +11,37 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// newAuth 负责newAuth相关处理。
|
||||
func newAuth(t *testing.T) (*Service, func()) {
|
||||
t.Helper()
|
||||
// dbPath 保存db路径,供当前处理流程使用
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// store 保存store,供当前处理流程使用
|
||||
store := db.NewStore(d, db.DialectSQLite)
|
||||
// 初始化 admin。
|
||||
if ok, _ := store.Users.Create(context.Background(), "admin", "[email protected]", "pw"); !ok {
|
||||
t.Fatal("create admin")
|
||||
}
|
||||
store.Users.SetAdmin(context.Background(), "admin")
|
||||
// svc 保存svc,供当前处理流程使用
|
||||
svc := &Service{Store: store, Logger: testLogger()}
|
||||
return svc, func() { d.Close() }
|
||||
}
|
||||
|
||||
// testLogger 负责testLogger相关处理。
|
||||
func testLogger() *slog.Logger { return slog.Default() }
|
||||
|
||||
// TestLoginAndMiddleware 负责Test登录AndMiddleware相关处理。
|
||||
func TestLoginAndMiddleware(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
|
||||
// 登录。
|
||||
@@ -48,6 +57,7 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
|
||||
// 中间件解析会话。
|
||||
chain := svc.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := SessionFromContext(r.Context())
|
||||
if sess == nil || !sess.IsAdmin {
|
||||
t.Errorf("中间件应解析出管理员会话,got=%v", sess)
|
||||
@@ -55,8 +65,10 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
|
||||
// req 保存req,供当前处理流程使用
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
chain.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
@@ -64,18 +76,24 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireAuthAndAdmin 负责TestRequireAuthAndAdmin相关处理。
|
||||
func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// sid 保存sid,供当前处理流程使用
|
||||
sid, _, _ := svc.Login(ctx, "admin", "pw")
|
||||
|
||||
// protected 保存protected,供当前处理流程使用
|
||||
protected := svc.Middleware(RequireAuth(RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(200)
|
||||
}))))
|
||||
|
||||
// 无 cookie → 401。
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
protected.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
@@ -85,6 +103,7 @@ func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
// 有 admin cookie → 200。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req2.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
|
||||
// rec2 保存rec2,供当前处理流程使用
|
||||
rec2 := httptest.NewRecorder()
|
||||
protected.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
@@ -92,12 +111,16 @@ func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetAndClearCookie 负责TestSetAndClear登录凭证相关处理。
|
||||
func TestSetAndClearCookie(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
svc.SetSessionCookie(rec, "sid123")
|
||||
// c 保存c,供当前处理流程使用
|
||||
c := rec.Result().Cookies()
|
||||
if len(c) != 1 || c[0].Name != CookieName || c[0].Value != "sid123" || !c[0].HttpOnly {
|
||||
t.Fatalf("SetSessionCookie 异常: %+v", c)
|
||||
@@ -106,8 +129,10 @@ func TestSetAndClearCookie(t *testing.T) {
|
||||
t.Fatalf("SameSite 应为 Lax,got %v", c[0].SameSite)
|
||||
}
|
||||
|
||||
// rec2 保存rec2,供当前处理流程使用
|
||||
rec2 := httptest.NewRecorder()
|
||||
svc.ClearSessionCookie(rec2)
|
||||
// cc 保存cc,供当前处理流程使用
|
||||
cc := rec2.Result().Cookies()
|
||||
if len(cc) != 1 || cc[0].MaxAge != -1 {
|
||||
t.Fatalf("ClearSessionCookie 应 MaxAge=-1: %+v", cc)
|
||||
@@ -117,7 +142,9 @@ func TestSetAndClearCookie(t *testing.T) {
|
||||
// newEmptyStore 构造未初始化 admin 的测试 store,供 InitAdmin 测试。
|
||||
func newEmptyStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
// dbPath 保存db路径,供当前处理流程使用
|
||||
dbPath := filepath.Join(t.TempDir(), "init.db")
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
@@ -127,8 +154,10 @@ func newEmptyStore(t *testing.T) (*db.Store, func()) {
|
||||
|
||||
// TestInitAdmin_CreateThenReset 全新库创建 admin,二次调用走重置路径。
|
||||
func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newEmptyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
|
||||
// 全新库 → 创建。
|
||||
@@ -136,6 +165,7 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次 InitAdmin 应创建:created=%v err=%v", created, err)
|
||||
}
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if admin == nil || !admin.IsAdmin {
|
||||
t.Fatalf("admin 未正确创建/标记: %+v", admin)
|
||||
@@ -150,23 +180,29 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
if err != nil || created2 {
|
||||
t.Fatalf("二次 InitAdmin 应重置:created=%v err=%v", created2, err)
|
||||
}
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
|
||||
t.Fatal("旧密码 pw1 应已失效")
|
||||
}
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
|
||||
t.Fatal("新密码 pw2 应可用")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitAdmin_DoesNotValidatePassword 密码强度校验由调用方负责(ensureAdmin),
|
||||
// InitAdmin 本身不拒绝空密码,仅保证不 panic 且能完成创建。
|
||||
// TestInitAdmin_DoesNotValidatePassword 负责TestInitAdminDoesNotValidate密码相关处理。
|
||||
func TestInitAdmin_DoesNotValidatePassword(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newEmptyStore(t)
|
||||
defer cleanup()
|
||||
if _, err := InitAdmin(context.Background(), store, "[email protected]", ""); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := InitAdmin(context.Background(), store, "[email protected]", ""); err != nil {
|
||||
t.Fatalf("InitAdmin 不应自行拒绝空密码: %v", err)
|
||||
}
|
||||
if admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
|
||||
if // admin 保存admin,供当前处理流程使用
|
||||
admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
|
||||
t.Fatal("空密码也应创建 admin")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user