2023-09-14 22:51:01 +07:00
|
|
|
package api
|
|
|
|
|
2023-09-27 21:58:14 +07:00
|
|
|
import (
|
|
|
|
"net/http"
|
2023-09-14 22:51:01 +07:00
|
|
|
|
2023-09-27 21:58:14 +07:00
|
|
|
"git.nochill.in/nochill/hiling_go/util/token"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
2023-09-14 22:51:01 +07:00
|
|
|
|
2023-09-27 21:58:14 +07:00
|
|
|
// 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) gin.HandlerFunc {
|
|
|
|
return func(ctx *gin.Context) {
|
|
|
|
|
|
|
|
str, err := ctx.Cookie("paseto")
|
|
|
|
if err != nil {
|
|
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse(err, "Unauthorized"))
|
2023-09-14 22:51:01 +07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-09-27 21:58:14 +07:00
|
|
|
payload, err := tokenMaker.VerifyToken(str)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
ctx.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse(err, "Something went wrong while try to verify token"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Set(authorizationPayloadKey, payload)
|
|
|
|
|
|
|
|
ctx.Next()
|
2023-09-14 22:51:01 +07:00
|
|
|
}
|
|
|
|
}
|