瀏覽代碼

Auth 中间件

runningwater 8 月之前
父節點
當前提交
a62860bf52
共有 5 個文件被更改,包括 87 次插入1 次删除
  1. 35 0
      app/http/middlewares/auth_jwt.go
  2. 6 0
      app/models/user/user_util.go
  3. 23 1
      gohub.http
  4. 5 0
      main.go
  5. 18 0
      pkg/auth/auth.go

+ 35 - 0
app/http/middlewares/auth_jwt.go

@@ -0,0 +1,35 @@
+package middlewares
+
+import (
+	"fmt"
+
+	"github.com/gin-gonic/gin"
+	"github.com/runningwater/gohub/app/models/user"
+	"github.com/runningwater/gohub/pkg/config"
+	"github.com/runningwater/gohub/pkg/jwt"
+	"github.com/runningwater/gohub/pkg/response"
+)
+
+func AuthJWT() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		// 从请求头中获取 Authorization 字段,并验证 JWT
+		claims, err := jwt.NewJWT().ParseToken(c)
+		if err != nil {
+			response.Unauthorized(c, fmt.Sprintf("请查看 %v 相关的接口认证文档", config.GetString("app.name")))
+			return
+		}
+
+		// JWT 验证通过,将用户信息存入上下文
+		userModel := user.Get(claims.UserID)
+		if userModel.ID == 0 {
+			response.Unauthorized(c, "找不到对应用户,用户可能已删除")
+			return
+		}
+		c.Set("current_user_id", userModel.GetStringID())
+		c.Set("current_user_name", userModel.Name)
+		c.Set("current_user", userModel)
+
+		c.Next()
+
+	}
+}

+ 6 - 0
app/models/user/user_util.go

@@ -31,3 +31,9 @@ func GetByPhone(phone string) (userModel User) {
 	database.DB.Where("phone = ?", phone).First(&userModel)
 	return
 }
+
+// Get 根据 ID 查询用户
+func Get(idStr string) (userModel User) {
+	database.DB.Where("id =?", idStr).First(&userModel)
+	return
+}

+ 23 - 1
gohub.http

@@ -60,4 +60,26 @@ Content-Type: application/json
     "password_confirm":"secret",
     "verify_code": "123123",
     "email": "summer@testing.com"
-}
+}
+
+### 登录用户
+POST {{base_url}}/v1/auth/login/using-password HTTP/1.1
+Content-Type: application/json
+
+{
+    "captcha_id" :"xTS6AtcgjUVABJj2M9NE",
+    "captcha_answer": "338750",
+    "login_id": "summer@testing.com",
+    "password": "secret"
+}
+
+### 刷新token
+POST {{base_url}}/v1/auth/login/refresh-token HTTP/1.1
+Authorization: Bearer {{access_token}}
+Content-Type: application/json
+
+{}
+
+### /test_auth 测试认证
+GET {{base_url}}/test_auth HTTP/1.1
+Authorization: Bearer {{access_token}}

+ 5 - 0
main.go

@@ -42,6 +42,11 @@ func main() {
 	// 初始化路由绑定
 	bootstrap.SetupRoute(r)
 
+	// r.GET("/test_auth", middlewares.AuthJWT(), func(c *gin.Context) {
+	// 	userModle := auth.CurrentUser(c)
+	// 	response.Data(c, userModle)
+	// })
+
 	// 测试发送短信
 	// verifycode.NewVerifyCode().SendSMS("15968875425")
 

+ 18 - 0
pkg/auth/auth.go

@@ -4,7 +4,9 @@ package auth
 import (
 	"errors"
 
+	"github.com/gin-gonic/gin"
 	"github.com/runningwater/gohub/app/models/user"
+	"github.com/runningwater/gohub/pkg/logger"
 )
 
 // Attemp login
@@ -30,3 +32,19 @@ func LoginByPhone(phone string) (user.User, error) {
 
 	return userModel, nil
 }
+
+// CurrentUser 获取当前用户
+func CurrentUser(c *gin.Context) user.User {
+	userModel, ok := c.MustGet("current_user").(user.User)
+	if !ok {
+		logger.LogIf(errors.New("无法获取用户"))
+		return user.User{}
+	}
+	// db is now a *gorm.DB object
+	return userModel
+}
+
+// CurrentUID 获取当前用户 ID
+func CurrentUID(c *gin.Context) string {
+	return c.GetString("current_user_id")
+}