Reapply "Adminbereich mit Rollen und Nutzerauswertung ergänzen"
This reverts commit 2447537652.
This commit is contained in:
@@ -6,9 +6,34 @@ type User struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
UILanguage string `json:"ui_language"`
|
||||
Role string `json:"role"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type AdminOverview struct {
|
||||
UsersTotal int `json:"users_total"`
|
||||
UsersActive7Days int `json:"users_active_7_days"`
|
||||
AttemptsTotal int `json:"attempts_total"`
|
||||
ExercisesGenerated int `json:"exercises_generated"`
|
||||
AverageScore float64 `json:"average_score"`
|
||||
}
|
||||
|
||||
type AdminUser struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Attempts int `json:"attempts"`
|
||||
AverageScore float64 `json:"average_score"`
|
||||
LastAttempt *time.Time `json:"last_attempt,omitempty"`
|
||||
}
|
||||
|
||||
type AdminUserPage struct {
|
||||
Users []AdminUser `json:"users"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
|
||||
type LearnerProfile struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
|
||||
@@ -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)))
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
|
||||
"speech-learning-api/internal/domain"
|
||||
)
|
||||
|
||||
func (s *PostgresStore) AdminOverview(ctx context.Context) (domain.AdminOverview, error) {
|
||||
var overview domain.AdminOverview
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM users),
|
||||
(SELECT COUNT(DISTINCT user_id) FROM attempts WHERE created_at >= now() - interval '7 days'),
|
||||
(SELECT COUNT(*) FROM attempts),
|
||||
(SELECT COUNT(*) FROM exercises WHERE source = 'flowise'),
|
||||
(SELECT COALESCE(AVG(overall_score), 0) FROM attempts)
|
||||
`).Scan(&overview.UsersTotal, &overview.UsersActive7Days, &overview.AttemptsTotal,
|
||||
&overview.ExercisesGenerated, &overview.AverageScore)
|
||||
return overview, err
|
||||
}
|
||||
|
||||
func (s *PostgresStore) AdminUsers(ctx context.Context, search string, page int) (domain.AdminUserPage, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
search = strings.TrimSpace(search)
|
||||
result := domain.AdminUserPage{Users: []domain.AdminUser{}, Page: page}
|
||||
if err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE '%' || $1 || '%')
|
||||
`, search).Scan(&result.Total); err != nil {
|
||||
return domain.AdminUserPage{}, err
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
WITH selected AS (
|
||||
SELECT id, email, role, created_at
|
||||
FROM users
|
||||
WHERE ($1 = '' OR email ILIKE '%' || $1 || '%')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 25 OFFSET $2
|
||||
)
|
||||
SELECT u.id, u.email, u.role, u.created_at,
|
||||
a.attempts, a.average_score, a.last_attempt
|
||||
FROM selected u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT COUNT(*) AS attempts, COALESCE(AVG(overall_score), 0) AS average_score,
|
||||
MAX(created_at) AS last_attempt
|
||||
FROM attempts WHERE user_id = u.id
|
||||
) a ON true
|
||||
ORDER BY u.created_at DESC, u.id DESC
|
||||
`, search, (page-1)*25)
|
||||
if err != nil {
|
||||
return domain.AdminUserPage{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var user domain.AdminUser
|
||||
var last sql.NullTime
|
||||
if err := rows.Scan(&user.ID, &user.Email, &user.Role, &user.CreatedAt,
|
||||
&user.Attempts, &user.AverageScore, &last); err != nil {
|
||||
return domain.AdminUserPage{}, err
|
||||
}
|
||||
if last.Valid {
|
||||
user.LastAttempt = &last.Time
|
||||
}
|
||||
result.Users = append(result.Users, user)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -142,9 +142,9 @@ func (s *PostgresStore) CreateUser(ctx context.Context, email, passwordHash, uiL
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
INSERT INTO users (id, email, password_hash, ui_language)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, email, ui_language, created_at
|
||||
RETURNING id, email, ui_language, role, created_at
|
||||
`, user.ID, user.Email, passwordHash, uiLanguage)
|
||||
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.CreatedAt); err != nil {
|
||||
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.Role, &user.CreatedAt); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return user, nil
|
||||
@@ -154,11 +154,11 @@ func (s *PostgresStore) GetPasswordHashByEmail(ctx context.Context, email string
|
||||
var user domain.User
|
||||
var hash string
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, email, password_hash, ui_language, created_at
|
||||
SELECT id, email, password_hash, ui_language, role, created_at
|
||||
FROM users
|
||||
WHERE email = $1
|
||||
`, strings.ToLower(strings.TrimSpace(email)))
|
||||
if err := row.Scan(&user.ID, &user.Email, &hash, &user.UILanguage, &user.CreatedAt); err != nil {
|
||||
if err := row.Scan(&user.ID, &user.Email, &hash, &user.UILanguage, &user.Role, &user.CreatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
@@ -170,11 +170,11 @@ func (s *PostgresStore) GetPasswordHashByEmail(ctx context.Context, email string
|
||||
func (s *PostgresStore) GetUser(ctx context.Context, id string) (domain.User, error) {
|
||||
var user domain.User
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, email, ui_language, created_at
|
||||
SELECT id, email, ui_language, role, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`, id)
|
||||
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.CreatedAt); err != nil {
|
||||
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.Role, &user.CreatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
@@ -558,6 +558,11 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Existing installations receive the role on startup; public registration
|
||||
-- continues to create only learner accounts.
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'learner'
|
||||
CHECK (role IN ('learner', 'admin'));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS learner_profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
|
||||
Reference in New Issue
Block a user