filegate/web/auth/middleware.go

68 lines
1.7 KiB
Go

package auth
import (
"fmt"
"log"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"git.jmbit.de/filegate/filegate/utils"
"git.jmbit.de/filegate/filegate/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)
err := &AuthenticationError{
Code: http.StatusForbidden,
Message: "You are not authorized to do this Action",
}
metaContent.ErrorTitle = "Not Authorized"
metaContent.ErrorText = "You are not authorized to do this Action"
c.HTML(http.StatusUnauthorized, "", templates.Index(metaContent, err))
log.Printf(
"[WARN] %s: %s User: %s IP: %s Unauthorized",
c.Request.Method,
c.Request.URL,
session.Get("username"),
c.Request.RemoteAddr,
)
c.Abort()
log.Printf(
"[INFO] %s: %s User: %s IP: %s",
c.Request.Method,
c.Request.URL,
session.Get("username"),
c.Request.RemoteAddr,
)
return
}
}
// Logged in and authorized, continue
c.Next()
}
}
type AuthenticationError struct {
Code int
Message string
}
func (e *AuthenticationError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}