/*
* This file is part of sdbapi
* Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
package middlewares
import (
"api/auth"
"net/http"
"github.com/gin-gonic/gin"
)
// JWT authorization middleware
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
// get the authorization header and check if it exists
token := c.Request.Header.Get("Authorization")
if token == "" {
// no authorization header
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization"})
c.Abort()
return
}
// check if the token is valid
err := auth.ValidateJWTToken(token)
if err != nil {
// something is wrong with the token, error out
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
c.Abort()
return
}
// continue to the next handler
c.Next()
}
}