2022-09-11 22:58:19 -06:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/auth"
|
2022-09-13 19:41:10 -06:00
|
|
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
2022-09-11 22:58:19 -06:00
|
|
|
"github.com/gin-gonic/gin"
|
2022-09-11 23:03:20 -06:00
|
|
|
"log"
|
2022-09-11 22:58:19 -06:00
|
|
|
"net/http"
|
2022-09-11 23:03:20 -06:00
|
|
|
"strings"
|
2022-09-11 22:58:19 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
func RequireAuth() gin.HandlerFunc {
|
2022-09-12 19:20:56 -06:00
|
|
|
return func(c *gin.Context) {
|
2022-09-13 19:41:10 -06:00
|
|
|
appConfig := c.MustGet("CONFIG").(config.Interface)
|
|
|
|
|
2022-09-12 19:20:56 -06:00
|
|
|
authHeader := c.GetHeader("Authorization")
|
2022-09-11 23:03:20 -06:00
|
|
|
authHeaderParts := strings.Split(authHeader, " ")
|
|
|
|
|
|
|
|
if len(authHeaderParts) != 2 {
|
|
|
|
log.Println("Authentication header is invalid: " + authHeader)
|
2022-09-12 19:20:56 -06:00
|
|
|
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "request does not contain a valid token"})
|
|
|
|
c.Abort()
|
2022-09-11 23:03:20 -06:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tokenString := authHeaderParts[1]
|
|
|
|
|
2022-09-11 22:58:19 -06:00
|
|
|
if tokenString == "" {
|
2022-09-12 19:20:56 -06:00
|
|
|
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "request does not contain an access token"})
|
|
|
|
c.Abort()
|
2022-09-11 22:58:19 -06:00
|
|
|
return
|
|
|
|
}
|
2022-09-14 09:19:28 -06:00
|
|
|
claim, err := auth.ValidateToken(appConfig.GetString("web.jwt.encryptionkey"), tokenString)
|
2022-09-11 22:58:19 -06:00
|
|
|
if err != nil {
|
2022-09-12 19:20:56 -06:00
|
|
|
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": err.Error()})
|
|
|
|
c.Abort()
|
2022-09-11 22:58:19 -06:00
|
|
|
return
|
|
|
|
}
|
2022-09-12 19:20:56 -06:00
|
|
|
|
2022-09-13 19:41:10 -06:00
|
|
|
//todo, is this shared between all sessions??
|
2022-09-12 19:20:56 -06:00
|
|
|
c.Set("AUTH_TOKEN", tokenString)
|
|
|
|
c.Set("AUTH_USERNAME", claim.Username)
|
|
|
|
|
|
|
|
c.Next()
|
2022-09-11 22:58:19 -06:00
|
|
|
}
|
|
|
|
}
|