38 lines
1.0 KiB
Go
38 lines
1.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"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 := templates.GenMetaContent(c)
|
|
metaContent.ErrorTitle = "Not Authorized"
|
|
metaContent.ErrorText += "\nYou are not authorized to do this Action"
|
|
c.HTML(http.StatusUnauthorized, "", templates.Login(metaContent, "Login"))
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
// Logged in and authorized, continue
|
|
c.Next()
|
|
}
|
|
}
|