Moved admin only to middleware.
This commit is contained in:
52
internal/http/middleware/admin.go
Normal file
52
internal/http/middleware/admin.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
httphelpers "synlotto-website/internal/helpers/http"
|
||||
securityHelpers "synlotto-website/internal/helpers/security"
|
||||
auditlogStorage "synlotto-website/internal/storage/auditlog"
|
||||
|
||||
"synlotto-website/internal/platform/bootstrap"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AdminOnly() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
app := c.MustGet("app").(*bootstrap.App)
|
||||
sm := app.SessionManager
|
||||
ctx := c.Request.Context()
|
||||
|
||||
v := sm.Get(ctx, "user_id")
|
||||
var uid int64
|
||||
switch t := v.(type) {
|
||||
case int64:
|
||||
uid = t
|
||||
case int:
|
||||
uid = int64(t)
|
||||
default:
|
||||
c.Redirect(http.StatusSeeOther, "/account/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if !securityHelpers.IsAdmin(app.DB, int(uid)) {
|
||||
c.String(http.StatusForbidden, "Forbidden")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
auditlogStorage.LogAdminAccess(
|
||||
app.DB,
|
||||
uid,
|
||||
c.Request.URL.Path,
|
||||
httphelpers.ClientIP(c.Request),
|
||||
c.Request.UserAgent(),
|
||||
time.Now().UTC(),
|
||||
)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user