Reapply "Adminbereich mit Rollen und Nutzerauswertung ergänzen"
This reverts commit 2447537652.
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
overview, err := s.store.AdminOverview(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, overview)
|
||||
}
|
||||
|
||||
func (s *Server) adminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
search := strings.TrimSpace(r.URL.Query().Get("search"))
|
||||
if len(search) > 100 {
|
||||
writeError(w, http.StatusBadRequest, nil)
|
||||
return
|
||||
}
|
||||
page := 1
|
||||
if value := r.URL.Query().Get("page"); value != "" {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < 1 || parsed > 100000 {
|
||||
writeError(w, http.StatusBadRequest, nil)
|
||||
return
|
||||
}
|
||||
page = parsed
|
||||
}
|
||||
users, err := s.store.AdminUsers(r.Context(), search, page)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, users)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"speech-learning-api/internal/config"
|
||||
"speech-learning-api/internal/domain"
|
||||
"speech-learning-api/internal/services"
|
||||
)
|
||||
|
||||
type adminTestStore struct {
|
||||
DataStore
|
||||
role string
|
||||
}
|
||||
|
||||
func (s *adminTestStore) GetUser(_ context.Context, id string) (domain.User, error) {
|
||||
return domain.User{ID: id, Role: s.role}, nil
|
||||
}
|
||||
|
||||
func (s *adminTestStore) AdminOverview(_ context.Context) (domain.AdminOverview, error) {
|
||||
return domain.AdminOverview{UsersTotal: 3}, nil
|
||||
}
|
||||
|
||||
func (s *adminTestStore) AdminUsers(_ context.Context, _ string, page int) (domain.AdminUserPage, error) {
|
||||
return domain.AdminUserPage{Page: page}, nil
|
||||
}
|
||||
|
||||
func (s *adminTestStore) DebugStatus(_ context.Context) domain.DebugDBStatus {
|
||||
return domain.DebugDBStatus{OK: true}
|
||||
}
|
||||
|
||||
func TestAdminRoutesRequireCurrentAdminRole(t *testing.T) {
|
||||
data := &adminTestStore{role: "learner"}
|
||||
auth := services.NewAuthService(nil, "test-secret")
|
||||
server := &Server{
|
||||
cfg: config.Config{DebugEnabled: true},
|
||||
store: data, auth: auth,
|
||||
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
}
|
||||
token, err := auth.IssueToken("usr_1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, testCase := range []struct {
|
||||
path string
|
||||
}{
|
||||
{"/admin/overview"},
|
||||
{"/admin/users"},
|
||||
{"/debug/status"},
|
||||
} {
|
||||
t.Run(testCase.path, func(t *testing.T) {
|
||||
handler := server.Routes()
|
||||
request := func(withToken bool) int {
|
||||
req := httptest.NewRequest(http.MethodGet, testCase.path, nil)
|
||||
if withToken {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
return recorder.Code
|
||||
}
|
||||
data.role = "learner"
|
||||
if got := request(false); got != http.StatusUnauthorized {
|
||||
t.Fatalf("anonymous status = %d, want 401", got)
|
||||
}
|
||||
if got := request(true); got != http.StatusForbidden {
|
||||
t.Fatalf("learner status = %d, want 403", got)
|
||||
}
|
||||
data.role = "admin"
|
||||
if got := request(true); got != http.StatusOK {
|
||||
t.Fatalf("admin status = %d, want 200", got)
|
||||
}
|
||||
data.role = "learner"
|
||||
if got := request(true); got != http.StatusForbidden {
|
||||
t.Fatalf("demoted admin status = %d, want 403", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,23 @@ func (s *Server) requireAuth(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// Admin rights are read from PostgreSQL for every request. A previously
|
||||
// issued token does not preserve privileges after an account is demoted.
|
||||
func (s *Server) requireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.store.GetUser(r.Context(), currentUserID(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
if user.Role != "admin" {
|
||||
writeError(w, http.StatusForbidden, nil)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func currentUserID(r *http.Request) string {
|
||||
value, _ := r.Context().Value(userIDKey).(string)
|
||||
return value
|
||||
|
||||
@@ -26,6 +26,8 @@ type DataStore interface {
|
||||
GetExercise(ctx context.Context, id, userID string) (domain.Exercise, error)
|
||||
SaveAttempt(ctx context.Context, attempt domain.Attempt) (domain.Attempt, error)
|
||||
Progress(ctx context.Context, userID string, limit int) (domain.ProgressSummary, error)
|
||||
AdminOverview(ctx context.Context) (domain.AdminOverview, error)
|
||||
AdminUsers(ctx context.Context, search string, page int) (domain.AdminUserPage, error)
|
||||
CreateConversationSession(ctx context.Context, userID, targetLanguage, cefrLevel string) (domain.ConversationSession, error)
|
||||
SaveConversationTurn(ctx context.Context, turn domain.ConversationTurn) (domain.ConversationTurn, error)
|
||||
DebugStatus(ctx context.Context) domain.DebugDBStatus
|
||||
@@ -62,12 +64,14 @@ func (s *Server) Routes() http.Handler {
|
||||
mux.Handle("POST /practice/attempts", s.requireAuth(http.HandlerFunc(s.createAttempt)))
|
||||
mux.Handle("POST /conversation/start", s.requireAuth(http.HandlerFunc(s.startConversation)))
|
||||
mux.Handle("POST /conversation/{id}/turn", s.requireAuth(http.HandlerFunc(s.conversationTurn)))
|
||||
mux.Handle("GET /admin/overview", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.adminOverview))))
|
||||
mux.Handle("GET /admin/users", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.adminUsers))))
|
||||
if s.cfg.DebugEnabled {
|
||||
mux.Handle("GET /debug/status", s.requireAuth(http.HandlerFunc(s.debugStatus)))
|
||||
mux.Handle("GET /debug/db", s.requireAuth(http.HandlerFunc(s.debugDB)))
|
||||
mux.Handle("GET /debug/flowise", s.requireAuth(http.HandlerFunc(s.debugFlowise)))
|
||||
mux.Handle("GET /debug/azure", s.requireAuth(http.HandlerFunc(s.debugAzure)))
|
||||
mux.Handle("GET /debug/runtime", s.requireAuth(http.HandlerFunc(s.debugRuntime)))
|
||||
mux.Handle("GET /debug/status", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.debugStatus))))
|
||||
mux.Handle("GET /debug/db", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.debugDB))))
|
||||
mux.Handle("GET /debug/flowise", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.debugFlowise))))
|
||||
mux.Handle("GET /debug/azure", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.debugAzure))))
|
||||
mux.Handle("GET /debug/runtime", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.debugRuntime))))
|
||||
}
|
||||
|
||||
return s.requestID(s.requestLogging(s.cors(mux)))
|
||||
|
||||
Reference in New Issue
Block a user