Shioriko/pkg/middleware/auth_middleware.go

52 lines
1018 B
Go
Raw Permalink Normal View History

2021-05-09 15:07:23 +00:00
package middleware
import (
"strings"
"github.com/Damillora/Shioriko/pkg/models"
"github.com/Damillora/Shioriko/pkg/services"
"github.com/gin-gonic/gin"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
clientToken := c.Request.Header.Get("Authorization")
if clientToken == "" {
c.JSON(403, models.ErrorResponse{
Code: 403,
Message: "Authorization required",
})
c.Abort()
return
}
extractedToken := strings.Split(clientToken, "Bearer ")
if len(extractedToken) == 2 {
clientToken = strings.TrimSpace(extractedToken[1])
} else {
c.JSON(400, models.ErrorResponse{
Code: 400,
Message: "Incorrect Format of Authorization Token",
})
c.Abort()
return
}
claims, err := services.ValidateToken(clientToken)
if err != nil {
c.JSON(401, models.ErrorResponse{
Code: 401,
Message: err.Error(),
})
c.Abort()
return
}
user := services.GetUser(claims["sub"].(string))
2021-05-11 10:50:34 +00:00
2021-05-09 15:07:23 +00:00
c.Set("user", user)
c.Next()
}
}