goipam/web/auth/middleware.go

39 lines
1.0 KiB
Go
Raw Normal View History

2024-02-22 10:18:59 +01:00
package auth
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"git.jmbit.de/jmb/goipam/utils"
"git.jmbit.de/jmb/goipam/web/templates"
)
// AuthMiddleware deals with checking authentication and authorization (Is the user logged in and permitted to see/do something)
func AuthMiddleware(requiredLevel int) gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
isLoggedIn := session.Get("isLoggedIn")
accessLevel := session.Get("accessLevel")
if isLoggedIn != true {
c.Redirect(http.StatusFound, "/login.html")
// Not logged in, abort
c.Abort()
return
}
if accessLevelValue, ok := accessLevel.(int); ok {
if accessLevelValue < requiredLevel {
metaContent := utils.GenMetaContent(c)
metaContent.ErrorTitle = "Not Authorized"
metaContent.ErrorText = "You are not authorized to do this Action"
c.HTML(http.StatusUnauthorized, "", templates.Index(metaContent))
c.Abort()
return
}
}
// Logged in and authorized, continue
c.Next()
}
}