auth.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package handler
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/golang-jwt/jwt/v5"
  10. "github.com/redis/go-redis/v9"
  11. "golang.org/x/crypto/bcrypt"
  12. "spider/internal/config"
  13. "spider/internal/model"
  14. "spider/internal/store"
  15. "gorm.io/gorm"
  16. )
  17. const jwtExpiry = 7 * 24 * time.Hour // 7 days
  18. func getJWTSecret() string {
  19. if cfg := config.Get(); cfg != nil && cfg.Security.JWTSecret != "" {
  20. return cfg.Security.JWTSecret
  21. }
  22. return "spider-jwt-secret-2026"
  23. }
  24. // rdb is the shared Redis client for token blacklist. Set via SetAuthRedis.
  25. var authRedis *redis.Client
  26. // SetAuthRedis sets the Redis client used for token blacklisting.
  27. func SetAuthRedis(r *redis.Client) {
  28. authRedis = r
  29. }
  30. // AuthHandler handles authentication.
  31. type AuthHandler struct {
  32. store *store.Store
  33. }
  34. // LoginRequest is the login payload.
  35. type LoginRequest struct {
  36. Username string `json:"username" binding:"required"`
  37. Password string `json:"password" binding:"required"`
  38. }
  39. // Login handles POST /auth/login
  40. func (h *AuthHandler) Login(c *gin.Context) {
  41. var req LoginRequest
  42. if err := c.ShouldBindJSON(&req); err != nil {
  43. Fail(c, 400, "请输入用户名和密码")
  44. return
  45. }
  46. var user model.User
  47. if err := h.store.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
  48. Fail(c, 401, "用户名或密码错误")
  49. return
  50. }
  51. if !user.Enabled {
  52. Fail(c, 403, "账号已禁用")
  53. return
  54. }
  55. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
  56. Fail(c, 401, "用户名或密码错误")
  57. return
  58. }
  59. // Generate JWT with expiration
  60. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  61. "user_id": user.ID,
  62. "username": user.Username,
  63. "role": user.Role,
  64. "exp": time.Now().Add(jwtExpiry).Unix(),
  65. })
  66. tokenStr, err := token.SignedString([]byte(getJWTSecret()))
  67. if err != nil {
  68. Fail(c, 500, "生成令牌失败")
  69. return
  70. }
  71. // Update last login info & audit
  72. now := time.Now()
  73. ip := c.ClientIP()
  74. go func() {
  75. h.store.DB.Model(&user).Updates(map[string]any{
  76. "last_login_at": now,
  77. "last_login_ip": ip,
  78. })
  79. h.store.DB.Create(&model.AuditLog{
  80. Username: user.Username,
  81. Action: "login",
  82. TargetType: "user",
  83. TargetID: fmt.Sprintf("%d", user.ID),
  84. IP: ip,
  85. })
  86. }()
  87. OK(c, gin.H{
  88. "token": tokenStr,
  89. "user": gin.H{
  90. "id": user.ID,
  91. "username": user.Username,
  92. "nickname": user.Nickname,
  93. "role": user.Role,
  94. "must_change_password": user.MustChangePassword,
  95. },
  96. })
  97. }
  98. // ChangePassword handles PUT /auth/password
  99. func (h *AuthHandler) ChangePassword(c *gin.Context) {
  100. userID := c.GetUint("user_id")
  101. var req struct {
  102. OldPassword string `json:"old_password" binding:"required"`
  103. NewPassword string `json:"new_password" binding:"required,min=6"`
  104. }
  105. if err := c.ShouldBindJSON(&req); err != nil {
  106. Fail(c, 400, "新密码至少6位")
  107. return
  108. }
  109. var user model.User
  110. if err := h.store.DB.First(&user, userID).Error; err != nil {
  111. Fail(c, 404, "用户不存在")
  112. return
  113. }
  114. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  115. Fail(c, 400, "旧密码错误")
  116. return
  117. }
  118. if err := ValidatePassword(req.NewPassword); err != nil {
  119. Fail(c, 400, err.Error())
  120. return
  121. }
  122. hashed, _ := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  123. h.store.DB.Model(&user).Updates(map[string]any{
  124. "password": string(hashed),
  125. "must_change_password": false,
  126. })
  127. LogAudit(h.store, c, "update", "user", fmt.Sprintf("%d", userID), gin.H{"action": "change_password"})
  128. OK(c, gin.H{"message": "密码已修改"})
  129. }
  130. // GetProfile handles GET /auth/profile
  131. func (h *AuthHandler) GetProfile(c *gin.Context) {
  132. userID := c.GetUint("user_id")
  133. var user model.User
  134. if err := h.store.DB.First(&user, userID).Error; err != nil {
  135. Fail(c, 404, "用户不存在")
  136. return
  137. }
  138. OK(c, gin.H{
  139. "id": user.ID,
  140. "username": user.Username,
  141. "nickname": user.Nickname,
  142. "role": user.Role,
  143. })
  144. }
  145. // UpdateProfile handles PUT /auth/profile — user updates their own nickname
  146. func (h *AuthHandler) UpdateProfile(c *gin.Context) {
  147. userID := c.GetUint("user_id")
  148. var req struct {
  149. Nickname *string `json:"nickname"`
  150. }
  151. if err := c.ShouldBindJSON(&req); err != nil {
  152. Fail(c, 400, err.Error())
  153. return
  154. }
  155. var user model.User
  156. if err := h.store.DB.First(&user, userID).Error; err != nil {
  157. Fail(c, 404, "用户不存在")
  158. return
  159. }
  160. if req.Nickname != nil {
  161. h.store.DB.Model(&user).Update("nickname", *req.Nickname)
  162. }
  163. h.store.DB.First(&user, userID)
  164. OK(c, gin.H{
  165. "id": user.ID,
  166. "username": user.Username,
  167. "nickname": user.Nickname,
  168. "role": user.Role,
  169. })
  170. }
  171. // Logout handles POST /auth/logout — blacklists the current token
  172. func (h *AuthHandler) Logout(c *gin.Context) {
  173. auth := c.GetHeader("Authorization")
  174. if auth != "" && strings.HasPrefix(auth, "Bearer ") {
  175. tokenStr := strings.TrimPrefix(auth, "Bearer ")
  176. if authRedis != nil {
  177. // Blacklist token until its expiry
  178. authRedis.Set(context.Background(), "spider:token:blacklist:"+tokenStr, "1", jwtExpiry)
  179. }
  180. }
  181. LogAudit(h.store, c, "logout", "user", c.GetString("username"), nil)
  182. OK(c, gin.H{"message": "已退出"})
  183. }
  184. // ── JWT Middleware ──
  185. // JWTAuth is the authentication middleware.
  186. func JWTAuth() gin.HandlerFunc {
  187. return func(c *gin.Context) {
  188. auth := c.GetHeader("Authorization")
  189. if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
  190. c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
  191. return
  192. }
  193. tokenStr := strings.TrimPrefix(auth, "Bearer ")
  194. // Check blacklist
  195. if authRedis != nil {
  196. blacklisted, _ := authRedis.Exists(context.Background(), "spider:token:blacklist:"+tokenStr).Result()
  197. if blacklisted > 0 {
  198. c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: 401, Message: "令牌已失效"})
  199. return
  200. }
  201. }
  202. token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
  203. return []byte(getJWTSecret()), nil
  204. })
  205. if err != nil || !token.Valid {
  206. c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: 401, Message: "令牌无效"})
  207. return
  208. }
  209. claims, ok := token.Claims.(jwt.MapClaims)
  210. if !ok {
  211. c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: 401, Message: "令牌解析失败"})
  212. return
  213. }
  214. // Set user info in context
  215. if uid, ok := claims["user_id"].(float64); ok {
  216. c.Set("user_id", uint(uid))
  217. }
  218. if username, ok := claims["username"].(string); ok {
  219. c.Set("username", username)
  220. }
  221. if role, ok := claims["role"].(string); ok {
  222. c.Set("role", role)
  223. }
  224. c.Next()
  225. }
  226. }
  227. // RequireRole returns middleware that checks the user's role.
  228. func RequireRole(roles ...string) gin.HandlerFunc {
  229. roleSet := make(map[string]bool)
  230. for _, r := range roles {
  231. roleSet[r] = true
  232. }
  233. return func(c *gin.Context) {
  234. role := c.GetString("role")
  235. if !roleSet[role] {
  236. c.AbortWithStatusJSON(http.StatusForbidden, Response{Code: 403, Message: "权限不足"})
  237. return
  238. }
  239. c.Next()
  240. }
  241. }
  242. // RequireAction returns middleware that checks the user's role has the required action permission.
  243. // Falls back to default permissions if no DB record exists.
  244. func RequireAction(action string) gin.HandlerFunc {
  245. return func(c *gin.Context) {
  246. role := c.GetString("role")
  247. // Admin always has all permissions
  248. if role == "admin" {
  249. c.Next()
  250. return
  251. }
  252. // Check DB for role permissions
  253. var perm model.RolePermission
  254. if err := getPermissionDB().Where("role = ?", role).First(&perm).Error; err == nil {
  255. // Found in DB
  256. for _, a := range strings.Split(perm.Actions, ",") {
  257. if strings.TrimSpace(a) == action {
  258. c.Next()
  259. return
  260. }
  261. }
  262. } else {
  263. // Fallback to defaults
  264. defaults := model.DefaultPermissions()
  265. if d, ok := defaults[role]; ok {
  266. for _, a := range strings.Split(d.Actions, ",") {
  267. if strings.TrimSpace(a) == action {
  268. c.Next()
  269. return
  270. }
  271. }
  272. }
  273. }
  274. c.AbortWithStatusJSON(http.StatusForbidden, Response{Code: 403, Message: "无此操作权限"})
  275. }
  276. }
  277. // permDB is cached reference to avoid import cycles
  278. var permDB interface{ Where(query interface{}, args ...interface{}) *gorm.DB }
  279. func setPermissionDB(db *gorm.DB) { permDB = db }
  280. func getPermissionDB() *gorm.DB {
  281. if permDB == nil {
  282. return nil
  283. }
  284. return permDB.(*gorm.DB)
  285. }
  286. // HashPassword hashes a password with bcrypt.
  287. func HashPassword(password string) string {
  288. hashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  289. return string(hashed)
  290. }
  291. // ValidatePassword checks password meets complexity requirements.
  292. func ValidatePassword(password string) error {
  293. minLen := 8
  294. if cfg := config.Get(); cfg != nil && cfg.Security.PasswordMinLen > 0 {
  295. minLen = cfg.Security.PasswordMinLen
  296. }
  297. if len(password) < minLen {
  298. return fmt.Errorf("密码至少 %d 位", minLen)
  299. }
  300. var hasUpper, hasLower, hasDigit bool
  301. for _, c := range password {
  302. switch {
  303. case c >= 'A' && c <= 'Z':
  304. hasUpper = true
  305. case c >= 'a' && c <= 'z':
  306. hasLower = true
  307. case c >= '0' && c <= '9':
  308. hasDigit = true
  309. }
  310. }
  311. if !hasUpper || !hasLower || !hasDigit {
  312. return fmt.Errorf("密码必须包含大写字母、小写字母和数字")
  313. }
  314. return nil
  315. }