admin page updates
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/golib/cookies"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"git.haelnorr.com/h/oslstats/internal/roles"
|
||||
"git.haelnorr.com/h/oslstats/internal/throw"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
// RequirePermission creates middleware that requires a specific permission
|
||||
@@ -72,3 +74,39 @@ func (c *Checker) RequireRole(s *hws.Server, role roles.Role) func(http.Handler)
|
||||
func (c *Checker) RequireAdmin(server *hws.Server) func(http.Handler) http.Handler {
|
||||
return c.RequireRole(server, roles.Admin)
|
||||
}
|
||||
|
||||
// RequireActualAdmin checks if the user's ACTUAL role is admin, ignoring preview mode
|
||||
// This is used for critical operations like stopping preview mode
|
||||
func (c *Checker) RequireActualAdmin(s *hws.Server) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := db.CurrentUser(r.Context())
|
||||
if user == nil {
|
||||
// Not logged in - redirect to login
|
||||
cookies.SetPageFrom(w, r, r.URL.Path)
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Check user's ACTUAL role in database, bypassing preview mode
|
||||
var hasAdmin bool
|
||||
if ok := db.WithReadTx(s, w, r, c.conn, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
||||
var err error
|
||||
hasAdmin, err = user.HasRole(ctx, tx, roles.Admin)
|
||||
if err != nil {
|
||||
return false, errors.Wrap(err, "user.HasRole")
|
||||
}
|
||||
return true, nil
|
||||
}); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if !hasAdmin {
|
||||
throw.Forbidden(s, w, r, "You don't have the required role to access this resource", errors.New("missing admin role"))
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user