Feat: Add JWT config, auth middleware, and token parsing using username.
Signed-off-by: Goldbro233 <bowensun_06@outlook.com>
This commit is contained in:
28
middlewares/auth_middleware.go
Normal file
28
middlewares/auth_middleware.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"GinTutorial/utils"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AuthMiddleWare() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
token := ctx.GetHeader("Authorization")
|
||||
if token == "" {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"message": "Token is empty"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
username, err := utils.ParseToken(token)
|
||||
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Token"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
ctx.Set("username", username)
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user