60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package common
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"gitea.com/bitwsd/document_ai/pkg/constant"
|
|
"gitea.com/bitwsd/document_ai/pkg/jwt"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func MiddlewareContext(c *gin.Context) {
|
|
c.Set(constant.ContextIP, c.ClientIP())
|
|
}
|
|
|
|
func GetIPFromContext(ctx context.Context) string {
|
|
return ctx.Value(constant.ContextIP).(string)
|
|
}
|
|
|
|
func GetUserIDFromContext(ctx *gin.Context) int64 {
|
|
return ctx.GetInt64(constant.ContextUserID)
|
|
}
|
|
|
|
func AuthMiddleware(ctx *gin.Context) {
|
|
token := ctx.GetHeader("Authorization")
|
|
if token == "" {
|
|
ctx.JSON(http.StatusOK, ErrorResponse(ctx, CodeUnauthorized, CodeUnauthorizedMsg))
|
|
ctx.Abort()
|
|
}
|
|
|
|
token = strings.TrimPrefix(token, "Bearer ")
|
|
|
|
claims, err := jwt.ParseToken(token)
|
|
if err != nil {
|
|
ctx.JSON(http.StatusOK, ErrorResponse(ctx, CodeUnauthorized, CodeUnauthorizedMsg))
|
|
ctx.Abort()
|
|
}
|
|
|
|
if claims == nil {
|
|
ctx.JSON(http.StatusOK, ErrorResponse(ctx, CodeUnauthorized, CodeUnauthorizedMsg))
|
|
ctx.Abort()
|
|
}
|
|
|
|
ctx.Set(constant.ContextUserID, claims.UserId)
|
|
}
|
|
|
|
func GetAuthMiddleware() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
token := ctx.GetHeader("Authorization")
|
|
if token != "" {
|
|
token = strings.TrimPrefix(token, "Bearer ")
|
|
claims, err := jwt.ParseToken(token)
|
|
if err == nil {
|
|
ctx.Set(constant.ContextUserID, claims.UserId)
|
|
}
|
|
}
|
|
}
|
|
}
|