Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ func (h *Handler) AdminMiddleware(next http.HandlerFunc) http.HandlerFunc {
http.Error(w, "Forbidden: Admin access required", http.StatusForbidden)
return
}
if !user.IsActive {
http.Error(w, "Forbidden: Inactive user", http.StatusForbidden)
return
}

next(w, r)
}
Expand Down Expand Up @@ -79,12 +83,42 @@ func (h *Handler) UpdateUserHandler(w http.ResponseWriter, r *http.Request) {
return
}

var user models.User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
var body struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
IsAdmin bool `json:"is_admin"`
IsActive *bool `json:"is_active"`
Category string `json:"category"`
TotalPoints int `json:"total_points"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

existing, err := h.db.GetUser(id)
if err != nil {
if err == database.ErrNotFound {
http.Error(w, "User not found", http.StatusNotFound)
return
}
h.logger.WithContext(r.Context()).WithError(err).Error("Failed to get user for update")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

user := *existing
user.Username = body.Username
user.Email = body.Email
user.Password = body.Password
user.IsAdmin = body.IsAdmin
user.Category = body.Category
user.TotalPoints = body.TotalPoints
if body.IsActive != nil {
user.IsActive = *body.IsActive
}

// Hash password if provided
if user.Password != "" {
hashedPassword, err := hashPassword(user.Password)
Expand Down
11 changes: 9 additions & 2 deletions api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,17 @@ func (h *Handler) RegisterHandler(w http.ResponseWriter, r *http.Request) {
Email: req.Email,
Password: hashedPassword,
IsAdmin: false,
IsActive: true,
IsActiveSet: true,
TotalPoints: 0,
CreatedAt: time.Now(),
}

// Try to create the user in SQLite database
if sqlDB, ok := h.db.(*database.SQLiteDB); ok {
result, err := sqlDB.DB().Exec(
"INSERT INTO users (username, email, password, is_admin, total_points, created_at) VALUES (?, ?, ?, ?, ?, ?)",
user.Username, user.Email, user.Password, user.IsAdmin, user.TotalPoints, user.CreatedAt,
"INSERT INTO users (username, email, password, is_admin, is_active, total_points, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
user.Username, user.Email, user.Password, user.IsAdmin, user.IsActive, user.TotalPoints, user.CreatedAt,
)
if err != nil {
h.logger.WithContext(r.Context()).WithFields(map[string]interface{}{
Expand Down Expand Up @@ -192,6 +194,11 @@ func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
if !user.IsActive {
h.logger.LogAuthentication(r.Context(), req.Username, false, "inactive user")
http.Error(w, "Account is inactive", http.StatusUnauthorized)
return
}

// Log successful authentication
h.logger.LogAuthentication(r.Context(), req.Username, true, "")
Expand Down
49 changes: 32 additions & 17 deletions api/exam.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,24 +279,39 @@ func (h *Handler) StartExamHandler(w http.ResponseWriter, r *http.Request) {
return
}

// Verify the exam is assigned to this user
assignedExams, err := h.db.GetAssignedExamsForUser(userID)
user, err := h.db.GetUser(userID)
if err != nil {
if err == database.ErrNotFound {
http.Error(w, "User not found", http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
assigned := false
for _, ae := range assignedExams {
if ae.ExamID == exam.ID {
assigned = true
break
}
}
if !assigned {
http.Error(w, "Exam not assigned to this user", http.StatusForbidden)
if !user.IsActive {
http.Error(w, "User account is inactive", http.StatusForbidden)
return
}

if !user.IsAdmin {
assignedExams, err := h.db.GetAssignedExamsForUser(userID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
assigned := false
for _, ae := range assignedExams {
if ae.ExamID == exam.ID {
assigned = true
break
}
}
if !assigned {
http.Error(w, "Exam not assigned to this user", http.StatusForbidden)
return
}
}

// Build question list with answers
type examAnswer struct {
ID int `json:"id"`
Expand Down Expand Up @@ -400,12 +415,12 @@ func (h *Handler) SubmitExamHandler(w http.ResponseWriter, r *http.Request) {

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"attempt_id": attempt.ID,
"exam_id": attempt.ExamID,
"score": attempt.Score,
"correct_answers": attempt.CorrectAnswers,
"total_questions": attempt.TotalQuestions,
"completed_at": attempt.CompletedAt,
"attempt_id": attempt.ID,
"exam_id": attempt.ExamID,
"score": attempt.Score,
"correct_answers": attempt.CorrectAnswers,
"total_questions": attempt.TotalQuestions,
"completed_at": attempt.CompletedAt,
"question_results": attempt.QuestionResults,
})
}
Expand Down
63 changes: 62 additions & 1 deletion api/exam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func setupExamDB(t *testing.T) (*database.InMemoryDB, *models.User, *models.User
q := &models.Question{
TopicID: topic.ID,
QuestionText: fmt.Sprintf("Question %d?", i),
Difficulty: i % 3 + 1, // cycles through 2,3,1
Difficulty: i%3 + 1, // cycles through 2,3,1
Tags: []string{"java"},
TopicQuestionID: fmt.Sprintf("%d.%d", topic.ID, i),
IsActive: true,
Expand Down Expand Up @@ -167,6 +167,44 @@ func TestAssignExamToStudentsHandler(t *testing.T) {
}
}

func TestAssignExamToStudentsHandler_InactiveStudentRejected(t *testing.T) {
db, admin, student := setupExamDB(t)
handler := NewHandler(db)

student.IsActive = false
if err := db.UpdateUser(student); err != nil {
t.Fatalf("failed to deactivate student: %v", err)
}

exam := &models.Exam{
Name: "Assigned Exam", Categories: []string{"java"}, DifficultyLevels: []int{1},
QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "inactive-token",
CreatedBy: admin.ID, CreatedAt: time.Now(),
}
db.CreateExam(exam)

body, _ := json.Marshal(map[string]interface{}{
"user_ids": []int{student.ID},
})

req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/instructor/exams/assign?exam_id=%d", exam.ID), bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID))
w := httptest.NewRecorder()

handler.AssignExamToStudentsHandler(w, req)

if w.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String())
}

var result map[string]interface{}
json.NewDecoder(w.Body).Decode(&result)
if result["assigned"].(float64) != 0 {
t.Errorf("Expected assigned=0, got %v", result["assigned"])
}
}

func TestGetAssignedExamsHandler(t *testing.T) {
db, admin, student := setupExamDB(t)
handler := NewHandler(db)
Expand Down Expand Up @@ -263,6 +301,29 @@ func TestStartExamHandler_NotAssigned(t *testing.T) {
}
}

func TestStartExamHandler_AllowsAdminPreview(t *testing.T) {
db, admin, student := setupExamDB(t)
handler := NewHandler(db)

exam := &models.Exam{
Name: "Preview Exam", Categories: []string{"java"}, DifficultyLevels: []int{1, 2, 3},
QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "preview-token",
CreatedBy: admin.ID, CreatedAt: time.Now(),
}
db.CreateExam(exam)
db.AssignExamToUser(exam.ID, student.ID, admin.ID)

req := httptest.NewRequest(http.MethodPost,
fmt.Sprintf("/exam/start?token=%s&user_id=%d", exam.AccessToken, admin.ID), nil)
w := httptest.NewRecorder()

handler.StartExamHandler(w, req)

if w.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String())
}
}

func TestSubmitExamHandler(t *testing.T) {
db, admin, student := setupExamDB(t)
handler := NewHandler(db)
Expand Down
26 changes: 24 additions & 2 deletions api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,34 @@ func (h *Handler) CreateUserHandler(w http.ResponseWriter, r *http.Request) {
return
}

var user models.User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
var body struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
IsAdmin bool `json:"is_admin"`
IsActive *bool `json:"is_active"`
Category string `json:"category"`
TotalPoints int `json:"total_points"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

user := models.User{
Username: body.Username,
Email: body.Email,
Password: body.Password,
IsAdmin: body.IsAdmin,
IsActive: true,
IsActiveSet: body.IsActive != nil,
Category: body.Category,
TotalPoints: body.TotalPoints,
}
if body.IsActive != nil {
user.IsActive = *body.IsActive
}

// Hash password if provided
if user.Password != "" {
hashedPassword, err := hashPassword(user.Password)
Expand Down
75 changes: 75 additions & 0 deletions api/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func TestCreateUserHandler(t *testing.T) {
Username: "testuser",
Email: "test@example.com",
IsAdmin: false,
IsActive: true,
}

body, _ := json.Marshal(user)
Expand Down Expand Up @@ -654,6 +655,7 @@ func TestCreateUserWithPasswordHashing(t *testing.T) {
Email: "test@example.com",
Password: testPassword,
IsAdmin: false,
IsActive: true,
}

body, _ := json.Marshal(user)
Expand Down Expand Up @@ -739,6 +741,7 @@ func TestUpdateUserPasswordHashing(t *testing.T) {
Email: "test@example.com",
Password: initialPassword,
IsAdmin: false,
IsActive: true,
}

createBody, _ := json.Marshal(user)
Expand Down Expand Up @@ -777,6 +780,7 @@ func TestUpdateUserPasswordHashing(t *testing.T) {
Email: "test@example.com",
Password: newPassword,
IsAdmin: false,
IsActive: true,
TotalPoints: 0,
}

Expand Down Expand Up @@ -833,6 +837,77 @@ func TestUpdateUserPasswordHashing(t *testing.T) {
}
}

func TestInactiveUserCannotLoginAfterAdminUpdate(t *testing.T) {
tmpDir := t.TempDir()
dbPath := tmpDir + "/test_inactive_login.db"

db, err := database.NewSQLiteDB(dbPath)
if err != nil {
t.Fatalf("Failed to create SQLite database: %v", err)
}
defer db.Close()

handler := NewHandler(db)

admin := &models.User{
Username: "admin",
Email: "admin@example.com",
Password: "ignored",
IsAdmin: true,
IsActive: true,
IsActiveSet: true,
CreatedAt: time.Now(),
}
if err := db.CreateUser(admin); err != nil {
t.Fatalf("failed to create admin: %v", err)
}

createBody, _ := json.Marshal(models.User{
Username: "inactive-user",
Email: "inactive@example.com",
Password: "password123",
})
createReq := httptest.NewRequest(http.MethodPost, "/users", bytes.NewBuffer(createBody))
createW := httptest.NewRecorder()
handler.CreateUserHandler(createW, createReq)
if createW.Code != http.StatusCreated {
t.Fatalf("Expected status %d, got %d. Body: %s", http.StatusCreated, createW.Code, createW.Body.String())
}

var created models.User
if err := json.NewDecoder(createW.Body).Decode(&created); err != nil {
t.Fatalf("failed to decode created user: %v", err)
}

updateBody, _ := json.Marshal(map[string]interface{}{
"username": created.Username,
"email": created.Email,
"is_admin": false,
"is_active": false,
"category": created.Category,
"total_points": created.TotalPoints,
})
updateReq := httptest.NewRequest(http.MethodPut, "/admin/users?id="+strconv.Itoa(created.ID), bytes.NewBuffer(updateBody))
updateReq.Header.Set("X-User-ID", strconv.Itoa(admin.ID))
updateW := httptest.NewRecorder()
handler.AdminMiddleware(handler.UpdateUserHandler)(updateW, updateReq)
if updateW.Code != http.StatusOK {
t.Fatalf("Expected status %d, got %d. Body: %s", http.StatusOK, updateW.Code, updateW.Body.String())
}

loginBody, _ := json.Marshal(LoginRequest{
Username: created.Username,
Password: "password123",
})
loginReq := httptest.NewRequest(http.MethodPost, "/auth/login", bytes.NewBuffer(loginBody))
loginW := httptest.NewRecorder()
handler.LoginHandler(loginW, loginReq)

if loginW.Code != http.StatusUnauthorized {
t.Fatalf("Expected status %d, got %d. Body: %s", http.StatusUnauthorized, loginW.Code, loginW.Body.String())
}
}

// Test: Verify dashboard stats are per-user, not aggregate (GitHub Issue #74)
// This test explicitly validates that each user sees only their own stats
func TestDashboardStatsArePerUser(t *testing.T) {
Expand Down
Loading
Loading