57 lines
1.6 KiB
Go
Executable File
57 lines
1.6 KiB
Go
Executable File
package api
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.nochill.in/nochill/hiling_go/util/token"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// func CORSMiddleware() gin.HandlerFunc {
|
|
// return func(ctx *gin.Context) {
|
|
// ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
// ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
// ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
|
// ctx.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
|
|
|
|
// if ctx.Request.Method == "OPTIONS" {
|
|
// ctx.AbortWithStatus(204)
|
|
// return
|
|
// }
|
|
|
|
// ctx.Next()
|
|
// }
|
|
// }
|
|
|
|
const (
|
|
authorizationPayloadKey = "authorization_payload"
|
|
)
|
|
|
|
func authMiddleware(tokenMaker token.Maker, redisClient *redis.Client) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
|
|
str, err := ctx.Cookie("paseto")
|
|
if err != nil {
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse(err, "Unauthorized"))
|
|
return
|
|
}
|
|
|
|
payload, err := tokenMaker.VerifyToken(str)
|
|
if err != nil {
|
|
ctx.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse(err, "Something went wrong while try to verify token"))
|
|
return
|
|
}
|
|
|
|
_, err = redisClient.Get(ctx, "blacklist:"+str).Result()
|
|
if err == nil {
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Token has been revoked"})
|
|
return
|
|
}
|
|
// redis.Nil = key not found (not blacklisted); other errors = Redis down → fail-open
|
|
|
|
ctx.Set(authorizationPayloadKey, payload)
|
|
ctx.Next()
|
|
}
|
|
}
|