feat(panel): add domain-admin role with per-domain authorization
test / test (push) Has been cancelled

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-10 23:43:59 +03:00
parent c9076655b9
commit 15baa1e5d0
28 changed files with 1425 additions and 333 deletions
+9 -10
View File
@@ -61,7 +61,7 @@ func (m *Module) clearSessionCookies(w http.ResponseWriter) {
// HandleLogin serves the login form (GET) and authenticates (POST).
func (m *Module) HandleLogin(w http.ResponseWriter, r *http.Request) {
exists, err := m.store.AdminExists()
exists, err := m.store.UserExists()
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
@@ -106,22 +106,21 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
username := strings.TrimSpace(r.PostFormValue("username"))
password := r.PostFormValue("password")
admin, err := m.store.GetAdmin()
user, err := m.store.GetUserByUsername(username)
if err != nil {
if !errors.Is(err, store.ErrNoAdmin) {
logf("panel: login: get admin failed: %v", err)
if !errors.Is(err, store.ErrUserNotFound) {
logf("panel: login: get user failed: %v", err)
}
m.renderLogin(w, http.StatusUnauthorized, "Invalid username or password.")
return
}
pwErr := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(password))
if username != admin.Username || pwErr != nil {
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
m.renderLogin(w, http.StatusUnauthorized, "Invalid username or password.")
return
}
token := m.sessions.Create(admin.Username)
token := m.sessions.Create(user.Username)
m.setSessionCookie(w, token)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
@@ -222,13 +221,13 @@ func (m *Module) submitSetup(w http.ResponseWriter, r *http.Request, token strin
return
}
if err := m.store.CreateAdmin(username, string(hash)); err != nil {
if exists, _ := m.store.AdminExists(); exists {
if err := m.store.CreateGlobalUser(username, string(hash)); err != nil {
if exists, _ := m.store.UserExists(); exists {
m.setup.complete()
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
logf("panel: setup: create admin failed: %v", err)
logf("panel: setup: create user failed: %v", err)
m.renderSetupForm(w, http.StatusInternalServerError, token, "Internal error. Please try again.")
return
}
+20 -7
View File
@@ -1,17 +1,12 @@
package auth
import (
"context"
"net/http"
)
type ctxKey int
const usernameKey ctxKey = 0
// RequireAuth wraps a handler so only requests with a valid session cookie
// reach it; everyone else is redirected to the login page. The authenticated
// username is stashed in the request context for downstream handlers.
// principal is stashed in the request context for downstream handlers.
func (m *Module) RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := m.sessionToken(r)
@@ -27,7 +22,13 @@ func (m *Module) RequireAuth(next http.Handler) http.Handler {
if isSessionActivity(r) && m.sessions.Touch(token) {
m.setSessionCookie(w, token)
}
ctx := context.WithValue(r.Context(), usernameKey, username)
u, err := m.store.GetUserByUsername(username)
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
p := principalFromUser(u)
ctx := withPrincipal(r.Context(), p)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -43,3 +44,15 @@ func CurrentUser(r *http.Request) string {
}
return ""
}
// RequireGlobal wraps a handler that only global administrators may reach.
func RequireGlobal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, ok := CurrentPrincipal(r.Context())
if !ok || !p.IsGlobal() {
http.NotFound(w, r)
return
}
next.ServeHTTP(w, r)
})
}
+86
View File
@@ -0,0 +1,86 @@
package auth
import (
"context"
"net/http"
"github.com/mixeme/selfpost/internal/store"
)
type ctxKey int
const (
usernameKey ctxKey = 0
principalKey ctxKey = 1
)
// Role is a panel user's access level.
type Role = store.Role
const (
RoleGlobal = store.RoleGlobal
RoleDomainAdmin = store.RoleDomainAdmin
)
// Principal is the authenticated panel user attached to a request.
type Principal struct {
ID int64
Username string
Role Role
Domains []int64 // assigned domain IDs; empty for global (all domains)
}
// IsGlobal reports whether the principal has full panel access.
func (p Principal) IsGlobal() bool {
return p.Role == RoleGlobal
}
// CanAccessDomain reports whether the principal may access a domain id.
func (p Principal) CanAccessDomain(domainID int64) bool {
if p.IsGlobal() {
return true
}
for _, id := range p.Domains {
if id == domainID {
return true
}
}
return false
}
// CanAccessApp reports whether the principal may access an application.
func (p Principal) CanAccessApp(app store.Application) bool {
return p.CanAccessDomain(app.DomainID)
}
func principalFromUser(u store.User) Principal {
return Principal{
ID: u.ID,
Username: u.Username,
Role: u.Role,
Domains: u.DomainIDs,
}
}
func withPrincipal(ctx context.Context, p Principal) context.Context {
ctx = context.WithValue(ctx, usernameKey, p.Username)
return context.WithValue(ctx, principalKey, p)
}
// CurrentPrincipal returns the authenticated principal from the request context.
func CurrentPrincipal(ctx context.Context) (Principal, bool) {
if v, ok := ctx.Value(principalKey).(Principal); ok {
return v, true
}
return Principal{}, false
}
// PrincipalFromRequest returns the authenticated principal from an HTTP request.
func PrincipalFromRequest(r *http.Request) (Principal, bool) {
return CurrentPrincipal(r.Context())
}
// RequestWithPrincipal attaches a principal for middleware-equivalent tests.
func RequestWithPrincipal(r *http.Request, p Principal) *http.Request {
return r.WithContext(withPrincipal(r.Context(), p))
}
+3 -3
View File
@@ -33,7 +33,7 @@ func newSetupManager(st *store.Store, hostname, tokenPath string) *setupManager
}
func (m *setupManager) bootstrap() error {
done, err := m.store.AdminExists()
done, err := m.store.UserExists()
if err != nil {
return err
}
@@ -48,9 +48,9 @@ func (m *setupManager) bootstrap() error {
}
func (m *setupManager) activeToken() (string, bool) {
done, err := m.store.AdminExists()
done, err := m.store.UserExists()
if err != nil {
logf("panel: setup: admin check failed: %v", err)
logf("panel: setup: user check failed: %v", err)
return "", false
}
if done {