221 lines
7.8 KiB
Go
221 lines
7.8 KiB
Go
// Package auth 认证服务(Day 24):登录(bcrypt + 失败 5 次锁定 15 分钟)、
|
|
// 登出(JWT 黑名单,TTL=剩余有效期)、刷新令牌(旧令牌轮换作废)。
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/gorm"
|
|
|
|
"go-sms/internal/model/entity"
|
|
errs "go-sms/internal/pkg/errors"
|
|
jwtpkg "go-sms/internal/pkg/jwt"
|
|
"go-sms/internal/repository/mysql"
|
|
)
|
|
|
|
// 登录保护默认值(验收:错误密码 5 次锁定 15 分钟)。
|
|
const (
|
|
DefaultMaxFails = 5
|
|
DefaultLockWindow = 15 * time.Minute
|
|
)
|
|
|
|
// TokenStore 令牌黑名单与登录失败计数存储(生产 Redis,内存实现供测试/降级)。
|
|
type TokenStore interface {
|
|
// Revoke 将令牌哈希写入黑名单,ttl 为剩余有效期。
|
|
Revoke(ctx context.Context, tokenHash string, ttl time.Duration) error
|
|
// IsRevoked 令牌是否已注销。
|
|
IsRevoked(ctx context.Context, tokenHash string) (bool, error)
|
|
// IncrFail 失败计数 +1(进入新窗口时重置为 1),返回当前计数。
|
|
IncrFail(ctx context.Context, key string, window time.Duration) (int64, error)
|
|
// GetFail 当前失败计数(窗口过期返回 0)。
|
|
GetFail(ctx context.Context, key string) (int64, error)
|
|
// ResetFail 清零失败计数(登录成功调用)。
|
|
ResetFail(ctx context.Context, key string) error
|
|
}
|
|
|
|
// Service 认证服务。
|
|
// maxFails/lockWindow 未导出但同包测试可注入。
|
|
type Service struct {
|
|
dao *mysql.AccountDAO
|
|
jwt *jwtpkg.Manager
|
|
store TokenStore // nil 时降级内存实现
|
|
maxFails int
|
|
lockWindow time.Duration
|
|
}
|
|
|
|
// NewService 构造;store 为 nil 时降级内存实现(单实例有效)。
|
|
func NewService(db *gorm.DB, jm *jwtpkg.Manager, store TokenStore) *Service {
|
|
if store == nil {
|
|
store = NewMemoryTokenStore()
|
|
}
|
|
return &Service{
|
|
dao: mysql.NewAccountDAO(db),
|
|
jwt: jm,
|
|
store: store,
|
|
maxFails: DefaultMaxFails,
|
|
lockWindow: DefaultLockWindow,
|
|
}
|
|
}
|
|
|
|
// LoginRequest 登录请求(POST /api/v1/auth/login)。
|
|
type LoginRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
// LoginResult 登录/刷新响应。
|
|
type LoginResult struct {
|
|
Token string `json:"token"`
|
|
ExpiresIn int64 `json:"expires_in"` // 秒
|
|
Username string `json:"username"` // 兼容保留(Day 31 前已暴露)
|
|
Role string `json:"role"` // 兼容保留(单数)
|
|
User LoginUser `json:"user"` // 前端契约主字段(web user store 依赖)
|
|
}
|
|
|
|
// LoginUser 登录用户视图(与前端 UserInfo 契约对齐:account_id/username/roles/permissions)。
|
|
type LoginUser struct {
|
|
AccountID int64 `json:"account_id"`
|
|
Username string `json:"username"`
|
|
RealName string `json:"real_name,omitempty"`
|
|
Roles []string `json:"roles"`
|
|
Permissions []string `json:"permissions"`
|
|
}
|
|
|
|
// failKey 登录失败计数键(按用户名隔离)。
|
|
func failKey(username string) string { return "login:fail:" + username }
|
|
|
|
// tokenKey 令牌黑名单键:原始令牌 SHA-256(Redis key 定长,避免存储整段 JWT)。
|
|
func tokenKey(raw string) string {
|
|
sum := sha256.Sum256([]byte(raw))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
// Login 登录:锁定检查 → 口令校验(bcrypt)→ 失败计数 → 签发 JWT。
|
|
// 验收:正确密码返回 Token;错误密码 5 次锁定 15 分钟。
|
|
func (s *Service) Login(ctx context.Context, username, password, clientIP string) (*LoginResult, error) {
|
|
username = strings.TrimSpace(username)
|
|
if username == "" || password == "" {
|
|
return nil, errs.InvalidParam.WithMsg("用户名与密码不能为空")
|
|
}
|
|
// 锁定检查:失败计数达上限后窗口内一律拒绝(含正确密码)
|
|
if n, _ := s.store.GetFail(ctx, failKey(username)); n >= int64(s.maxFails) {
|
|
return nil, errs.RateLimited.WithMsg(
|
|
"密码连续错误达上限,账号已锁定,请 " + s.lockAgoTip() + " 后重试")
|
|
}
|
|
|
|
u, err := s.dao.GetByUsername(ctx, username)
|
|
if err != nil {
|
|
if errors.Is(err, mysql.ErrNotFound) {
|
|
// 用户不存在与口令错误同响应,避免账号枚举
|
|
_, _ = s.store.IncrFail(ctx, failKey(username), s.lockWindow)
|
|
s.recordLogin(ctx, username, 0, clientIP, "用户名或密码错误")
|
|
return nil, errs.Unauthorized.WithMsg("用户名或密码错误")
|
|
}
|
|
return nil, err
|
|
}
|
|
if u.Status != 1 {
|
|
s.recordLogin(ctx, username, u.ID, clientIP, "账号被禁用")
|
|
return nil, errs.AccountDisabled // ISC:002
|
|
}
|
|
if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil {
|
|
n, _ := s.store.IncrFail(ctx, failKey(username), s.lockWindow)
|
|
if n >= int64(s.maxFails) {
|
|
s.recordLogin(ctx, username, u.ID, clientIP, "连续错误锁定")
|
|
return nil, errs.RateLimited.WithMsg("密码连续错误达上限,账号已锁定 15 分钟")
|
|
}
|
|
s.recordLogin(ctx, username, u.ID, clientIP, "用户名或密码错误")
|
|
return nil, errs.Unauthorized.WithMsg("用户名或密码错误")
|
|
}
|
|
|
|
// 成功:清零计数 + 签发令牌 + 回写登录时间/IP(尽力而为)
|
|
_ = s.store.ResetFail(ctx, failKey(username))
|
|
s.recordLogin(ctx, username, u.ID, clientIP, "")
|
|
token, err := s.jwt.Sign(u.ID, u.Username, []string{u.Role}, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
now := time.Now()
|
|
s.dao.DB().WithContext(ctx).Model(&entity.AccountUser{}).
|
|
Where("id = ?", u.ID).
|
|
Updates(map[string]any{"last_login_at": now, "last_login_ip": clientIP})
|
|
|
|
return &LoginResult{
|
|
Token: token, ExpiresIn: int64(s.jwt.Validity().Seconds()),
|
|
Username: u.Username, Role: u.Role,
|
|
User: LoginUser{
|
|
AccountID: u.ID, Username: u.Username, RealName: u.RealName,
|
|
Roles: []string{u.Role}, Permissions: []string{},
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// lockAgoTip 锁定提示(分钟粒度)。
|
|
func (s *Service) lockAgoTip() string { return "15 分钟" }
|
|
|
|
// recordLogin 登录审计留痕(Day 29,尽力而为:无审计表/写失败不影响登录流程)。
|
|
// Ok 列 default:1,失败记录 Ok=0 需 map 创建避免被 GORM 零值过滤吞掉。
|
|
func (s *Service) recordLogin(ctx context.Context, username string, accountID int64, ip, failReason string) {
|
|
ok := 1
|
|
if failReason != "" {
|
|
ok = 0
|
|
}
|
|
_ = s.dao.DB().WithContext(ctx).Model(&entity.SystemLoginLog{}).Create(map[string]any{
|
|
"username": username, "account_id": accountID, "ip": ip,
|
|
"user_agent": "gateway", "ok": ok, "fail_reason": failReason,
|
|
}).Error
|
|
}
|
|
|
|
// Logout 登出:令牌写入黑名单,TTL=剩余有效期(过期令牌无需写入)。
|
|
func (s *Service) Logout(ctx context.Context, rawToken string) error {
|
|
claims, err := s.jwt.Parse(rawToken)
|
|
if err != nil {
|
|
return errs.Unauthorized.WithMsg("令牌无效")
|
|
}
|
|
ttl := time.Until(claims.ExpiresAt.Time)
|
|
if ttl <= 0 {
|
|
return nil // 已过期:自然失效,无需黑名单
|
|
}
|
|
return s.store.Revoke(ctx, tokenKey(rawToken), ttl)
|
|
}
|
|
|
|
// Refresh 刷新令牌:旧令牌立即作废(轮换),按原 claims 重签。
|
|
func (s *Service) Refresh(ctx context.Context, rawToken string, claims *jwtpkg.Claims) (*LoginResult, error) {
|
|
if claims == nil || claims.Username == "" {
|
|
return nil, errs.Unauthorized.WithMsg("缺少有效的认证信息")
|
|
}
|
|
if err := s.Logout(ctx, rawToken); err != nil { // 旧令牌轮换作废
|
|
return nil, err
|
|
}
|
|
token, err := s.jwt.Sign(claims.AccountID, claims.Username, claims.Roles, claims.Permissions)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
role := ""
|
|
if len(claims.Roles) > 0 {
|
|
role = claims.Roles[0]
|
|
}
|
|
return &LoginResult{
|
|
Token: token, ExpiresIn: int64(s.jwt.Validity().Seconds()),
|
|
Username: claims.Username, Role: role,
|
|
User: LoginUser{
|
|
AccountID: claims.AccountID, Username: claims.Username,
|
|
Roles: claims.Roles, Permissions: claims.Permissions,
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// Revoked 令牌是否已注销(鉴权中间件回调;查询失败放行,由状态校验兜底)。
|
|
func (s *Service) Revoked(ctx context.Context, rawToken string) bool {
|
|
if rawToken == "" {
|
|
return false
|
|
}
|
|
ok, err := s.store.IsRevoked(ctx, tokenKey(rawToken))
|
|
return err == nil && ok
|
|
}
|