diff --git a/.env.example b/.env.example index 4c589d6..b14ef1e 100644 --- a/.env.example +++ b/.env.example @@ -26,6 +26,18 @@ APP_REGISTRATION_ENABLED=false SPRINGDOC_ENABLED=false LOG_LEVEL_APP=INFO +# --- Time zone --- +# The school's time zone. Exam start/end times and assignment deadlines are compared against this clock. +# Asia/Jakarta = WIB, Asia/Makassar = WITA, Asia/Jayapura = WIT. +APP_TIMEZONE=Asia/Jakarta + +# --- Login rate limits (requests per minute from one IP address) --- +# Must fit every student who signs in from the same public IP within a minute (a computer lab, or the +# whole school). Guessing one account stays limited to 5 attempts per minute per e-mail. +# AUTH covers login + first-login password change, so keep it at about twice LOGIN. +APP_RATE_LIMIT_LOGIN_PER_IP=100 +APP_RATE_LIMIT_AUTH_PER_IP=200 + # --- Storage Configuration --- STORAGE_UPLOAD_DIR=/app/storage/uploads diff --git a/README.id.md b/README.id.md index cb9f28e..ccd6055 100644 --- a/README.id.md +++ b/README.id.md @@ -37,7 +37,7 @@ Platform web **E-Learning** dan **Computer Based Test (CBT)** berfitur lengkap u | **Dashboard** | Statistik mengajar, jadwal ujian CBT mendatang, tugas aktif, dan aktivitas terkini | | **Materi Belajar** | CRUD + 5 tipe konten (Dokumen, Video, Teks, Link, Audio) + pelacakan pembaca siswa | | **Tugas Siswa** | CRUD + tenggat waktu + petunjuk pengerjaan + penilaian submission & umpan balik | -| **Ujian CBT** | CRUD + durasi timer + KKM (passing grade) + acak soal/opsi + izin remidi (retry) | +| **Ujian CBT** | CRUD + durasi timer + KKM (passing grade) + acak soal/opsi + izin remidi (retry) + tampilkan atau sembunyikan nilai dari siswa | | **Bank & Editor Soal** | Pilihan Ganda (A-E), Benar/Salah, Esai + bobot poin + **📥 Import Soal Excel** | | **Monitor Telemetri** | Pemantauan progres pengerjaan kandidat, indikator soal terjawab, dan deteksi pelanggaran anti-cheat real-time | | **Cetak Kartu Ujian** | Cetak kartu resmi peserta ujian CBT yang siap digunakan lengkap dengan barcode NIS | @@ -174,7 +174,7 @@ graph TD | **A04: Insecure Design** | Kunci jawaban dan pembahasan disembunyikan (`null`) dari payload siswa saat ujian; durasi ujian dikalkulasi di sisi server (*server-side deadline*), tidak mempercayai jam lokal klien. | | **A05: Security Misconfiguration** | Endpoint Actuator diblokir (`404`) dari Nginx publik; semua port Docker internal diikat ke loopback `127.0.0.1`; header keamanan HTTP (`nosniff`, `SAMEORIGIN`) aktif. | | **A06: Vulnerable Components** | Java 21 LTS, Spring Boot 3.5.7, PostgreSQL 16, Redis 7, React 19. Multi-stage Docker container berjalan menggunakan pengguna non-root `spring:spring`. | -| **A07: Identification Failures** | **Rate Limiter Login Bucket4j**: Dibatasi maksimal 5 percobaan per menit per alamat IP (`CF-Connecting-IP` / `X-Forwarded-For`) dan per email akun, menghasilkan HTTP `429 Too Many Requests` disertai header `Retry-After`. | +| **A07: Identification Failures** | **Rate Limiter Login**: Dibatasi 5 percobaan per menit per email akun dan 100 per menit per alamat IP (cukup untuk satu lab komputer di balik satu IP publik, `APP_RATE_LIMIT_LOGIN_PER_IP`), menghasilkan HTTP `429 Too Many Requests` disertai header `Retry-After`. Panggilan API setelah login dibatasi per pengguna, bukan per IP. | | **A08: Software & Data Integrity** | Whitelist ketat ekstensi file upload (`.pdf`, `.docx`, `.xlsx`, `.jpg`, `.png`, dll); ekstensi yang dapat dieksekusi atau berisi skrip (`.html`, `.svg`, `.exe`, `.sh`) ditolak keras untuk mencegah Stored XSS; unduhan disajikan dengan `Content-Disposition` aman. | | **A09: Logging & Monitoring** | Log pelanggaran anti-cheat ujian tercatat lengkap dengan identitas NIS siswa; probe internal `/actuator/health` tersedia untuk healthcheck container. | | **A10: SSRF** | Tidak ada fitur backend yang melakukan pemanggilan HTTP outbound ke URL luar dari input pengguna. | @@ -372,7 +372,8 @@ Untuk menerapkan ke server production: 8. Refresh token disimpan di cookie httpOnly `Secure`, jadi aplikasi harus diakses lewat HTTPS. Set `APP_REFRESH_COOKIE_SECURE=false` hanya untuk menjalankan lokal tanpa HTTPS (`docker-compose.yml` lokal sudah mengaturnya). 9. SPA mengirim header Content-Security-Policy. Jika memakai analytics, izinkan host-nya di container frontend, misalnya `CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com"` dan `CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com"`. 10. **Beberapa instance backend:** set `APP_REALTIME_MODE=redis`, `APP_RATE_LIMIT_STORE=redis`, dan `APP_STORAGE_TYPE=s3` dengan `APP_STORAGE_S3_BUCKET` (ditambah `APP_STORAGE_S3_ENDPOINT` dan `APP_STORAGE_S3_PATH_STYLE=true` untuk MinIO), lalu aktifkan sticky session untuk `/ws`. Detail ada di [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#scaling-limits-and-roadmap). -11. **IP asli klien / rate limiting:** backend hanya mempercayai `X-Forwarded-For` dari proxy internal (jaringan Docker). Jika situs berada di belakang Cloudflare, pulihkan IP pengunjung di Nginx host, jika tidak semua user akan berbagi IP Cloudflare untuk rate limit: +11. **Zona waktu:** jadwal ujian dan tenggat tugas dibandingkan dengan jam backend. Image berjalan di `Asia/Jakarta` (WIB); set `APP_TIMEZONE=Asia/Makassar` (WITA) atau `Asia/Jayapura` (WIT) untuk daerah lain. Ubah di luar jam ujian, karena attempt yang sedang berjalan dihitung dengan jam ini. +12. **IP asli klien / rate limiting:** backend hanya mempercayai `X-Forwarded-For` dari proxy internal (jaringan Docker). Jika situs berada di belakang Cloudflare, pulihkan IP pengunjung di Nginx host, jika tidak semua user akan berbagi IP Cloudflare untuk rate limit: ```nginx # blok http {} di nginx host — samakan daftarnya dengan https://www.cloudflare.com/ips/ set_real_ip_from 173.245.48.0/20; # ...tambahkan semua range IPv4/IPv6 Cloudflare diff --git a/README.md b/README.md index bdd24af..0b852c4 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ A full-featured web-based **E-Learning** and **Computer Based Test (CBT)** platf | **Dashboard** | Teaching metrics, scheduled examinations, active assignments, and recent activity | | **Learning Materials** | CRUD + multi-type content (Document, Video, Text, Link, Audio) + student view tracking | | **Assignments** | CRUD + deadline dates + instructions + submission grading with feedback | -| **CBT Examinations** | CRUD + duration timer + passing grade (KKM) + randomize questions/options + retry toggles | +| **CBT Examinations** | CRUD + duration timer + passing grade (KKM) + randomize questions/options + retry toggles + show or hide the score from students | | **Question Builder** | Multiple Choice (A-E), True/False, Essay + points allocation + **📥 Excel Import** | | **Live Telemetry Monitor** | Real-time WebSocket candidate status, question progress bar, and anti-cheat flag alerts | | **Exam Hall Tickets** | Print ready-to-use official CBT student candidate cards with NIS barcodes | @@ -174,7 +174,7 @@ graph TD | **A04: Insecure Design** | Examination answer keys and explanations strictly stripped (`null`) from student payloads; examination duration deadlines enforced on the server-side, not trusting client clocks. | | **A05: Security Misconfiguration** | Spring Boot Actuator endpoints strictly blocked (`404`) from public Nginx reverse proxy; all Docker service ports bound to loopback `127.0.0.1`; security headers (`X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`) enforced. | | **A06: Vulnerable Components** | Java 21 LTS, Spring Boot 3.5.7, PostgreSQL 16, Redis 7, React 19. Multi-stage Docker containers running under non-root `spring:spring` user. | -| **A07: Identification Failures** | **Bucket4j Login Rate Limiter**: 5 attempts per minute per IP address (`CF-Connecting-IP` / `X-Forwarded-For`) and per account email, returning `429 Too Many Requests` with `Retry-After` header. | +| **A07: Identification Failures** | **Login Rate Limiter**: 5 attempts per minute per account email and 100 per minute per IP address (sized for a computer lab behind one public IP, `APP_RATE_LIMIT_LOGIN_PER_IP`), returning `429 Too Many Requests` with `Retry-After` header. Signed-in API calls are limited per user, not per IP. | | **A08: Software & Data Integrity** | Strict file upload extension whitelist (`.pdf`, `.docx`, `.xlsx`, `.jpg`, `.png`, etc.); executable and scriptable types (`.html`, `.svg`, `.exe`, `.sh`) explicitly rejected to prevent Stored XSS; safe download `Content-Disposition`. | | **A09: Logging & Monitoring** | Anti-cheat proctoring violation alerts logged with student NIS; internal `/actuator/health` probe available for container healthchecks. | | **A10: SSRF** | Zero user-controlled outbound HTTP requests from backend services. | @@ -373,7 +373,8 @@ For production deployments: 8. The refresh token is an httpOnly `Secure` cookie, so serve the app over HTTPS. Set `APP_REFRESH_COOKIE_SECURE=false` only for plain-HTTP local runs (the local `docker-compose.yml` already does). 9. The SPA sends a Content-Security-Policy. If you enable analytics, allow its hosts on the frontend container, e.g. `CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com"` and `CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com"`. 10. **Several backend instances:** set `APP_REALTIME_MODE=redis`, `APP_RATE_LIMIT_STORE=redis`, and `APP_STORAGE_TYPE=s3` with `APP_STORAGE_S3_BUCKET` (plus `APP_STORAGE_S3_ENDPOINT` and `APP_STORAGE_S3_PATH_STYLE=true` for MinIO), and enable sticky sessions for `/ws`. Details in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#scaling-limits-and-roadmap). -11. **Real client IP / rate limiting:** the backend trusts `X-Forwarded-For` only from internal proxies (Docker network). If the site is behind Cloudflare, restore the visitor IP on the host Nginx, otherwise all users share Cloudflare's IPs for rate limiting: +11. **Time zone:** exam schedules and deadlines are compared against the backend's clock. The image runs in `Asia/Jakarta` (WIB); set `APP_TIMEZONE=Asia/Makassar` (WITA) or `Asia/Jayapura` (WIT) for other regions. Change it outside exam hours: attempts in progress are timed against this clock. +12. **Real client IP / rate limiting:** the backend trusts `X-Forwarded-For` only from internal proxies (Docker network). If the site is behind Cloudflare, restore the visitor IP on the host Nginx, otherwise all users share Cloudflare's IPs for rate limiting: ```nginx # http {} block of the host nginx — keep the list in sync with https://www.cloudflare.com/ips/ set_real_ip_from 173.245.48.0/20; # ...add every Cloudflare IPv4/IPv6 range diff --git a/backend/Dockerfile b/backend/Dockerfile index efac255..cf33641 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -11,5 +11,10 @@ RUN addgroup -S spring && adduser -S spring -G spring && \ chown -R spring:spring /app USER spring:spring COPY --from=build /app/target/*.jar app.jar +# Exam schedules, deadlines and timestamps are stored as local wall-clock time, so the JVM must run in the +# school's time zone. Without this the container runs in UTC and an exam scheduled for 07:00 WIB opens at 14:00. +# Override with the TZ environment variable (Asia/Makassar for WITA, Asia/Jayapura for WIT). +ENV TZ=Asia/Jakarta + EXPOSE 8080 ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"] diff --git a/backend/src/main/java/com/elearning/modules/exam/controller/ExamRunnerController.java b/backend/src/main/java/com/elearning/modules/exam/controller/ExamRunnerController.java index a10ccad..212df37 100644 --- a/backend/src/main/java/com/elearning/modules/exam/controller/ExamRunnerController.java +++ b/backend/src/main/java/com/elearning/modules/exam/controller/ExamRunnerController.java @@ -15,6 +15,7 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -73,12 +74,19 @@ public ResponseEntity>> submitAttempt( @PathVariable Long attemptId, @AuthenticationPrincipal UserPrincipal principal) { ExamAttempt attempt = examRunnerService.submitAttempt(attemptId, principal); - return ResponseEntity.ok(ApiResponse.success(Map.of( - "attemptId", attempt.getId(), - "status", attempt.getStatus(), - "score", attempt.getScore() != null ? attempt.getScore() : 0, - "passed", attempt.getPassed() != null ? attempt.getPassed() : false - ), "Exam submitted successfully")); + + Map result = new LinkedHashMap<>(); + result.put("attemptId", attempt.getId()); + result.put("status", attempt.getStatus()); + if (examRunnerService.isResultVisibleToStudent(attempt.getId())) { + result.put("score", attempt.getScore() != null ? attempt.getScore() : 0); + result.put("passed", attempt.getPassed() != null ? attempt.getPassed() : false); + result.put("resultHidden", false); + } else { + // The exam does not show results: the student only learns that the attempt was received. + result.put("resultHidden", true); + } + return ResponseEntity.ok(ApiResponse.success(result, "Exam submitted successfully")); } @PostMapping("/attempts/{attemptId}/answers/{answerId}/grade-essay") diff --git a/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java b/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java index b26cecf..a44d7a4 100644 --- a/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java +++ b/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java @@ -2,6 +2,10 @@ import com.elearning.common.enums.ExamType; import com.elearning.common.enums.Status; +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; @@ -9,6 +13,7 @@ import lombok.Data; import lombok.NoArgsConstructor; +import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -23,6 +28,12 @@ public class ExamDto { @NotNull(message = "Classroom ID is required") private Long classroomId; + /** + * Teacher who owns the exam. Only read when an admin creates the exam (an admin has no teacher + * profile); a teacher always owns the exams they create. + */ + private Long teacherId; + @NotBlank(message = "Title is required") private String title; @@ -31,9 +42,14 @@ public class ExamDto { @Builder.Default private ExamType type = ExamType.quiz; + @NotNull(message = "Duration is required") + @Min(value = 1, message = "Duration must be at least 1 minute") @Builder.Default private Integer durationMinutes = 60; + @NotNull(message = "Passing score is required") + @Min(value = 0, message = "Passing score must be between 0 and 100") + @Max(value = 100, message = "Passing score must be between 0 and 100") @Builder.Default private Integer passingScore = 75; @@ -59,4 +75,24 @@ public class ExamDto { @Builder.Default private Status status = Status.draft; + + /** The exam window must close after it opens; otherwise no student could ever start the exam. */ + @JsonIgnore + @AssertTrue(message = "End time must be after start time") + public boolean isEndAfterStart() { + if (startAt == null || endAt == null) { + return true; // reported by @NotNull + } + return endAt.isAfter(startAt); + } + + /** A student who starts at the opening time must be able to use the whole duration. */ + @JsonIgnore + @AssertTrue(message = "Duration does not fit between start time and end time") + public boolean isDurationWithinWindow() { + if (startAt == null || endAt == null || durationMinutes == null || !endAt.isAfter(startAt)) { + return true; // reported by the other constraints + } + return durationMinutes <= Duration.between(startAt, endAt).toMinutes(); + } } diff --git a/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java b/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java index b052d1b..9eee93a 100644 --- a/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java +++ b/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java @@ -391,6 +391,17 @@ public List getExamMonitor(Long examId, UserPrincipal princ }).collect(Collectors.toList()); } + /** + * Whether the student may see the score of this attempt: the exam's "show result" setting. The teacher + * can turn it on later to release the results. An unknown attempt shows nothing. + */ + @Transactional(readOnly = true) + public boolean isResultVisibleToStudent(Long attemptId) { + return attemptRepository.findById(attemptId) + .map(attempt -> attempt.getExamination().isShowResult()) + .orElse(false); + } + private ExamAttempt createNewAttempt(Examination exam, Student student, int attemptNumber) { ExamAttempt attempt = ExamAttempt.builder() .examination(exam) diff --git a/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java b/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java index 5684746..0a8c894 100644 --- a/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java +++ b/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java @@ -105,8 +105,7 @@ public ExamResponse getExamById(Long id, UserPrincipal principal) { @Transactional public ExamResponse createExam(ExamDto dto, UserPrincipal principal) { - Teacher teacher = teacherRepository.findByUserId(principal.getId()) - .orElseThrow(() -> new IllegalArgumentException("Teacher profile not found")); + Teacher teacher = resolveOwnerTeacher(dto.getTeacherId(), principal); Subject subject = subjectRepository.findById(dto.getSubjectId()) .orElseThrow(() -> new IllegalArgumentException("Subject not found: " + dto.getSubjectId())); @@ -396,6 +395,22 @@ public Map importQuestionsFromExcel(Long examId, MultipartFile f return result; } + /** + * A teacher owns the exams they create. An admin has no teacher profile, so an admin names the + * owning teacher with {@code teacherId}; a teacher cannot create exams on behalf of someone else. + */ + private Teacher resolveOwnerTeacher(Long teacherId, UserPrincipal principal) { + boolean isAdmin = principal.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); + if (isAdmin && teacherId != null) { + return teacherRepository.findById(teacherId) + .orElseThrow(() -> new IllegalArgumentException("Teacher not found: " + teacherId)); + } + return teacherRepository.findByUserId(principal.getId()) + .orElseThrow(() -> new IllegalArgumentException(isAdmin + ? "Choose the teacher who owns this exam" + : "Teacher profile not found")); + } + private void validateTeacherOwnership(Examination exam, UserPrincipal principal) { boolean isAdmin = principal.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); if (!isAdmin && !exam.getTeacher().getUser().getId().equals(principal.getId())) { @@ -414,8 +429,11 @@ private ExamResponse mapToResponse(Examination e, Long studentId) { if (attempt.isPresent()) { ExamAttempt att = attempt.get(); attemptStatus = att.getStatus().name(); - studentScore = att.getScore(); - studentPassed = att.getPassed(); + // The score stays hidden from the student until the exam shows results. + if (e.isShowResult()) { + studentScore = att.getScore(); + studentPassed = att.getPassed(); + } currentAttemptId = att.getId(); } } diff --git a/backend/src/main/java/com/elearning/modules/grade/service/GradeService.java b/backend/src/main/java/com/elearning/modules/grade/service/GradeService.java index c1e9da6..ebcf780 100644 --- a/backend/src/main/java/com/elearning/modules/grade/service/GradeService.java +++ b/backend/src/main/java/com/elearning/modules/grade/service/GradeService.java @@ -36,7 +36,8 @@ public GradeReportResponse getStudentGradeReport(UserPrincipal principal) { List subjects = subjectRepository.findAll(); List attempts = attemptRepository.findByStudentId(student.getId()).stream() - .filter(a -> a.getStatus() == AttemptStatus.completed) + // Exams that do not show results are left out, or their scores would leak through the averages. + .filter(a -> a.getStatus() == AttemptStatus.completed && a.getExamination().isShowResult()) .collect(Collectors.toList()); List submissions = submissionRepository.findAll().stream() diff --git a/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java b/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java index d0eb443..e006a6c 100644 --- a/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java +++ b/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java @@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -18,14 +19,21 @@ public class LoginRateLimiterService { private final RateLimiter rateLimiter; private static final Duration WINDOW = Duration.ofMinutes(1); - // 5 login attempts per minute per IP address - private static final int MAX_ATTEMPTS_PER_IP = 5; - // 5 login attempts per minute per account email - private static final int MAX_ATTEMPTS_PER_EMAIL = 5; + /** + * Login attempts per minute from one IP address, successful ones included. A school computer lab shares + * one public IP, so this must fit a whole class signing in at the start of an exam. Guessing the password + * of a single account is stopped by the much lower per-e-mail limit below. + */ + @Value("${app.rate-limit.login-per-ip:100}") + private int maxAttemptsPerIp = 100; + + /** Login attempts per minute for one account e-mail (reset after a successful login). */ + @Value("${app.rate-limit.login-per-email:5}") + private int maxAttemptsPerEmail = 5; public void checkLoginAllowed(String clientIp, String email) { if (clientIp != null && !clientIp.isBlank()) { - if (!rateLimiter.tryAcquire("login:ip:" + clientIp, MAX_ATTEMPTS_PER_IP, WINDOW)) { + if (!rateLimiter.tryAcquire("login:ip:" + clientIp, maxAttemptsPerIp, WINDOW)) { log.warn("Login rate limit exceeded for IP: {}", clientIp); throw new RateLimitExceededException("Terlalu banyak percobaan login dari alamat IP ini. Silakan tunggu 1 menit sebelum mencoba lagi."); } @@ -33,7 +41,7 @@ public void checkLoginAllowed(String clientIp, String email) { if (email != null && !email.isBlank()) { String normalizedEmail = email.trim().toLowerCase(); - if (!rateLimiter.tryAcquire("login:email:" + normalizedEmail, MAX_ATTEMPTS_PER_EMAIL, WINDOW)) { + if (!rateLimiter.tryAcquire("login:email:" + normalizedEmail, maxAttemptsPerEmail, WINDOW)) { log.warn("Login rate limit exceeded for email: {}", email); throw new RateLimitExceededException("Terlalu banyak percobaan login gagal untuk akun ini. Silakan tunggu 1 menit sebelum mencoba lagi."); } diff --git a/backend/src/main/java/com/elearning/security/RateLimitingFilter.java b/backend/src/main/java/com/elearning/security/RateLimitingFilter.java index 46fe73d..045123e 100644 --- a/backend/src/main/java/com/elearning/security/RateLimitingFilter.java +++ b/backend/src/main/java/com/elearning/security/RateLimitingFilter.java @@ -6,6 +6,7 @@ import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.lang.NonNull; @@ -13,27 +14,45 @@ import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; - import java.time.Duration; /** * Server-side rate limiting filter (counters in memory or in Redis, see {@link RateLimiter}). * Intercepts incoming HTTP requests at the Servlet Filter layer before hitting controllers, * protecting against brute-force attacks, DDoS, and excessive API burst traffic. + * + *

Requests that carry a valid access token are counted per user. A school computer lab usually shares + * one public IP address, so counting per IP would make a whole class share one budget and lock students + * out while they save answers. Only requests without a valid token (and the auth endpoints, where no + * token exists yet) are counted per IP. */ @Component @RequiredArgsConstructor @Slf4j public class RateLimitingFilter extends OncePerRequestFilter { + private static final Duration WINDOW = Duration.ofMinutes(1); + private static final String USER_KEY_PREFIX = "user:"; + private static final String IP_KEY_PREFIX = "ip:"; + private static final String BEARER_PREFIX = "Bearer "; + /** In-memory or Redis-backed, see {@code RateLimitConfig}. */ private final RateLimiter rateLimiter; - private static final Duration WINDOW = Duration.ofMinutes(1); + /** Reads the user id from the access token; this filter runs before {@link JwtAuthenticationFilter}. */ + private final JwtProvider jwtProvider; + + // Requests per minute (see app.rate-limit.* in application.yml) + @Value("${app.rate-limit.auth-per-ip:200}") + private int authPerIp = 200; + + @Value("${app.rate-limit.exam-per-user:120}") + private int examPerUser = 120; - // Rate limit thresholds - private static final int AUTH_CAPACITY = 10; // 10 login/auth requests per minute per IP - private static final int SUBMIT_CAPACITY = 60; // 60 autosave/submit requests per minute per IP - private static final int GENERAL_CAPACITY = 120; // 120 general API requests per minute per IP + @Value("${app.rate-limit.api-per-user:120}") + private int apiPerUser = 120; + + @Value("${app.rate-limit.anonymous-per-ip:300}") + private int anonymousPerIp = 300; @Override protected boolean shouldNotFilter(@NonNull HttpServletRequest request) { @@ -57,29 +76,27 @@ protected void doFilterInternal( String clientIp = LoginRateLimiterService.getClientIp(request); String requestUri = request.getRequestURI(); - // 1. Strictest tier: Auth endpoints (Login, Refresh, Register) - if (requestUri.startsWith("/api/v1/auth/login") || requestUri.startsWith("/api/v1/auth/register") - || requestUri.startsWith("/api/v1/auth/change-password")) { - if (!rateLimiter.tryAcquire("api:auth:" + clientIp, AUTH_CAPACITY, WINDOW)) { + if (isAuthEndpoint(requestUri)) { + // 1. Auth endpoints (login, register, change password): no trusted identity yet, so count per IP. + // Brute force on a single account is limited separately, per e-mail, in LoginRateLimiterService. + if (!rateLimiter.tryAcquire("api:auth:" + clientIp, authPerIp, WINDOW)) { log.warn("Rate limit [AUTH] exceeded for IP {} on {}", clientIp, requestUri); sendRateLimitResponse(response, "Terlalu banyak percobaan autentikasi dari alamat IP ini. Silakan tunggu 1 menit sebelum mencoba lagi."); return; } - } - - // 2. Medium tier: Exam autosave and submissions (anti-flood during high-concurrency CBT) - else if (requestUri.contains("/exams/") && (requestUri.endsWith("/submit") || requestUri.endsWith("/answer") || requestUri.endsWith("/answers"))) { - if (!rateLimiter.tryAcquire("api:submit:" + clientIp, SUBMIT_CAPACITY, WINDOW)) { - log.warn("Rate limit [EXAM SUBMIT] exceeded for IP {} on {}", clientIp, requestUri); - sendRateLimitResponse(response, "Terlalu banyak permintaan submit ujian secara bersamaan. Silakan tunggu beberapa saat."); + } else if (isExamWriteEndpoint(requestUri)) { + // 2. Exam autosave and submissions (anti-flood during high-concurrency CBT), per student. + String clientKey = resolveClientKey(request, clientIp); + if (!rateLimiter.tryAcquire("api:submit:" + clientKey, capacityFor(clientKey, examPerUser), WINDOW)) { + log.warn("Rate limit [EXAM SUBMIT] exceeded for {} on {}", clientKey, requestUri); + sendRateLimitResponse(response, "Terlalu banyak permintaan simpan jawaban dalam waktu singkat. Silakan tunggu beberapa saat."); return; } - } - - // 3. General API tier: All other /api/v1/** endpoints - else if (requestUri.startsWith("/api/v1")) { - if (!rateLimiter.tryAcquire("api:general:" + clientIp, GENERAL_CAPACITY, WINDOW)) { - log.warn("Rate limit [GENERAL API] exceeded for IP {} on {}", clientIp, requestUri); + } else if (requestUri.startsWith("/api/v1")) { + // 3. Every other /api/v1/** endpoint, per user. + String clientKey = resolveClientKey(request, clientIp); + if (!rateLimiter.tryAcquire("api:general:" + clientKey, capacityFor(clientKey, apiPerUser), WINDOW)) { + log.warn("Rate limit [GENERAL API] exceeded for {} on {}", clientKey, requestUri); sendRateLimitResponse(response, "Batas permintaan API terlampaui. Silakan kurangi frekuensi permintaan Anda."); return; } @@ -88,6 +105,40 @@ else if (requestUri.startsWith("/api/v1")) { filterChain.doFilter(request, response); } + private static boolean isAuthEndpoint(String requestUri) { + return requestUri.startsWith("/api/v1/auth/login") + || requestUri.startsWith("/api/v1/auth/register") + || requestUri.startsWith("/api/v1/auth/change-password"); + } + + private static boolean isExamWriteEndpoint(String requestUri) { + return requestUri.contains("/exams/") + && (requestUri.endsWith("/submit") || requestUri.endsWith("/answer") || requestUri.endsWith("/answers")); + } + + /** + * {@code "user:"} when the request carries a valid access token, otherwise {@code "ip:

"}. + * A forged or expired token never selects a user bucket, so it cannot be used to dodge the IP limit. + */ + String resolveClientKey(HttpServletRequest request, String clientIp) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith(BEARER_PREFIX)) { + String token = header.substring(BEARER_PREFIX.length()); + try { + if (jwtProvider.validateAccessToken(token)) { + return USER_KEY_PREFIX + jwtProvider.getUserIdFromToken(token); + } + } catch (RuntimeException e) { + // Malformed token or subject: fall through and count the request per IP. + } + } + return IP_KEY_PREFIX + clientIp; + } + + private int capacityFor(String clientKey, int perUserCapacity) { + return clientKey.startsWith(USER_KEY_PREFIX) ? perUserCapacity : anonymousPerIp; + } + private void sendRateLimitResponse(HttpServletResponse response, String message) throws IOException { response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index 2dd3f41..8accf2d 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -83,6 +83,14 @@ app: rate-limit: # memory = per instance; redis = shared by all instances store: ${APP_RATE_LIMIT_STORE:memory} + # Requests per minute. Signed-in users are counted per account, so a computer lab behind one public + # IP address does not share a single budget. Only requests without a valid token are counted per IP. + login-per-ip: ${APP_RATE_LIMIT_LOGIN_PER_IP:100} # login attempts from one IP address + login-per-email: ${APP_RATE_LIMIT_LOGIN_PER_EMAIL:5} # login attempts for one account (brute force) + auth-per-ip: ${APP_RATE_LIMIT_AUTH_PER_IP:200} # login + register + change-password from one IP + exam-per-user: ${APP_RATE_LIMIT_EXAM_PER_USER:120} # answer autosave + submit of one student + api-per-user: ${APP_RATE_LIMIT_API_PER_USER:120} # every other API call of one user + anonymous-per-ip: ${APP_RATE_LIMIT_ANONYMOUS_PER_IP:300} # API calls without a valid access token realtime: # local = in-memory STOMP broker of this instance; redis = relay exam events to every instance mode: ${APP_REALTIME_MODE:local} diff --git a/backend/src/main/resources/db/migration/V6__show_results_for_existing_exams.sql b/backend/src/main/resources/db/migration/V6__show_results_for_existing_exams.sql new file mode 100644 index 0000000..244f454 --- /dev/null +++ b/backend/src/main/resources/db/migration/V6__show_results_for_existing_exams.sql @@ -0,0 +1,7 @@ +-- V6: keep showing results for the exams that exist today. +-- +-- Until this version the show_result flag was stored but never applied: students always saw their +-- score. The backend now hides the score of exams with show_result = FALSE, so existing exams are +-- switched on to keep behaving as they did. Teachers can turn it off per exam in the exam form. + +UPDATE examinations SET show_result = TRUE WHERE show_result = FALSE; diff --git a/backend/src/main/resources/db/migration/seed_demo_data.sql b/backend/src/main/resources/db/migration/seed_demo_data.sql index 021d5c4..0fa65e0 100644 --- a/backend/src/main/resources/db/migration/seed_demo_data.sql +++ b/backend/src/main/resources/db/migration/seed_demo_data.sql @@ -142,14 +142,14 @@ BEGIN (v_budi_teacher_id, v_subj_mtk, v_class_x1, 'Latihan Soal Matriks dan Vektor Ruang', 'Kerjakan soal latihan halaman 45-50 buku pegangan siswa.', 'Tulis tangan jawaban di kertas folio lalu unggah foto/scan PDF.', 100, CURRENT_TIMESTAMP + INTERVAL '5 days', 'published'); -- Examinations - INSERT INTO examinations (teacher_id, subject_id, classroom_id, title, description, type, duration_minutes, passing_score, start_at, end_at, total_questions, status, shuffle_questions, shuffle_options) + INSERT INTO examinations (teacher_id, subject_id, classroom_id, title, description, type, duration_minutes, passing_score, start_at, end_at, total_questions, status, shuffle_questions, shuffle_options, show_result) VALUES - (v_budi_teacher_id, v_subj_mtk, v_class_x1, 'Penilaian Akhir Semester (PAS) Matematika Wajib', 'Ujian CBT terintegrasi proctoring anti-cheat', 'uas', 90, 75, CURRENT_TIMESTAMP - INTERVAL '1 day', CURRENT_TIMESTAMP + INTERVAL '30 days', 5, 'published', TRUE, TRUE) + (v_budi_teacher_id, v_subj_mtk, v_class_x1, 'Penilaian Akhir Semester (PAS) Matematika Wajib', 'Ujian CBT terintegrasi proctoring anti-cheat', 'uas', 90, 75, CURRENT_TIMESTAMP - INTERVAL '1 day', CURRENT_TIMESTAMP + INTERVAL '30 days', 5, 'published', TRUE, TRUE, TRUE) RETURNING id INTO v_exam1; - INSERT INTO examinations (teacher_id, subject_id, classroom_id, title, description, type, duration_minutes, passing_score, start_at, end_at, total_questions, status, shuffle_questions, shuffle_options) + INSERT INTO examinations (teacher_id, subject_id, classroom_id, title, description, type, duration_minutes, passing_score, start_at, end_at, total_questions, status, shuffle_questions, shuffle_options, show_result) VALUES - (v_budi_teacher_id, v_subj_pwb, v_class_x1, 'Ujian Harian: Pemrograman Web & Java 21', 'Kuis pemahaman konsep OOP, Spring Beans, dan React Hooks', 'quiz', 60, 75, CURRENT_TIMESTAMP - INTERVAL '1 day', CURRENT_TIMESTAMP + INTERVAL '30 days', 3, 'published', TRUE, TRUE) + (v_budi_teacher_id, v_subj_pwb, v_class_x1, 'Ujian Harian: Pemrograman Web & Java 21', 'Kuis pemahaman konsep OOP, Spring Beans, dan React Hooks', 'quiz', 60, 75, CURRENT_TIMESTAMP - INTERVAL '1 day', CURRENT_TIMESTAMP + INTERVAL '30 days', 3, 'published', TRUE, TRUE, TRUE) RETURNING id INTO v_exam2; -- Questions diff --git a/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java b/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java new file mode 100644 index 0000000..1857fe3 --- /dev/null +++ b/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java @@ -0,0 +1,96 @@ +package com.elearning.modules.exam.dto; + +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Schedule rules of an exam: the window must be open, and the duration must fit inside it. */ +class ExamDtoValidationTest { + + private static final LocalDateTime START = LocalDateTime.of(2026, 12, 1, 7, 0); + + private static ValidatorFactory factory; + private static Validator validator; + + @BeforeAll + static void createValidator() { + factory = Validation.buildDefaultValidatorFactory(); + validator = factory.getValidator(); + } + + @AfterAll + static void closeValidator() { + factory.close(); + } + + /** 60 minutes inside a two-hour window. */ + private static ExamDto.ExamDtoBuilder validExam() { + return ExamDto.builder() + .subjectId(1L) + .classroomId(1L) + .title("Ujian Harian") + .durationMinutes(60) + .startAt(START) + .endAt(START.plusHours(2)); + } + + private static Set violatedProperties(ExamDto dto) { + return validator.validate(dto).stream() + .map(violation -> violation.getPropertyPath().toString()) + .collect(Collectors.toSet()); + } + + @Test + void acceptsADurationThatFitsTheWindow() { + assertThat(violatedProperties(validExam().build())).isEmpty(); + } + + @Test + void acceptsADurationThatFillsTheWholeWindow() { + assertThat(violatedProperties(validExam().durationMinutes(120).build())).isEmpty(); + } + + @Test + void rejectsAnEndTimeBeforeTheStartTime() { + ExamDto dto = validExam().endAt(START.minusMinutes(1)).build(); + + assertThat(violatedProperties(dto)).containsExactly("endAfterStart"); + } + + @Test + void rejectsAnEndTimeEqualToTheStartTime() { + ExamDto dto = validExam().endAt(START).build(); + + assertThat(violatedProperties(dto)).containsExactly("endAfterStart"); + } + + @Test + void rejectsADurationLongerThanTheWindow() { + ExamDto dto = validExam().durationMinutes(121).build(); + + assertThat(violatedProperties(dto)).containsExactly("durationWithinWindow"); + } + + @Test + void reportsMissingTimesOnlyAsMissing() { + ExamDto dto = validExam().startAt(null).endAt(null).build(); + + assertThat(violatedProperties(dto)).containsExactlyInAnyOrder("startAt", "endAt"); + } + + @Test + void rejectsAPassingScoreAbove100() { + ExamDto dto = validExam().passingScore(101).build(); + + assertThat(violatedProperties(dto)).containsExactly("passingScore"); + } +} diff --git a/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java b/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java index 213c107..e87cd7b 100644 --- a/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java +++ b/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java @@ -317,6 +317,27 @@ void startCreatesTheNextAttemptNumberWhenRetriesAreAllowed() { assertEquals(AttemptStatus.in_progress, created.getValue().getStatus()); } + // --- result visibility ------------------------------------------------------------------------ + + @Test + void resultIsVisibleToTheStudentOnlyWhenTheExamShowsResults() { + ExamAttempt attempt = attempt(AttemptStatus.completed, LocalDateTime.now().minusMinutes(30)); + when(attemptRepository.findById(ATTEMPT_ID)).thenReturn(Optional.of(attempt)); + + exam.setShowResult(false); + assertFalse(service.isResultVisibleToStudent(ATTEMPT_ID)); + + exam.setShowResult(true); + assertTrue(service.isResultVisibleToStudent(ATTEMPT_ID)); + } + + @Test + void resultOfAnUnknownAttemptIsNotVisible() { + when(attemptRepository.findById(ATTEMPT_ID)).thenReturn(Optional.empty()); + + assertFalse(service.isResultVisibleToStudent(ATTEMPT_ID)); + } + // --- helpers --------------------------------------------------------------------------------- private Question question(long id, QuestionType type, String correctAnswer, int points) { diff --git a/docker-compose.gcp.yml b/docker-compose.gcp.yml index fd1c9b5..8e6964a 100644 --- a/docker-compose.gcp.yml +++ b/docker-compose.gcp.yml @@ -76,6 +76,11 @@ services: APP_NOTIFY_EXAM_RESULTS: ${APP_NOTIFY_EXAM_RESULTS:-true} APP_OUTBOX_PUBLISHER: pubsub APP_OUTBOX_PUBSUB_TOPIC: projects/${GCP_PROJECT:?GCP_PROJECT is required}/topics/exam-results + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} + # Logins per minute from one IP address: must fit a computer lab behind one public IP. + APP_RATE_LIMIT_LOGIN_PER_IP: ${APP_RATE_LIMIT_LOGIN_PER_IP:-100} + APP_RATE_LIMIT_AUTH_PER_IP: ${APP_RATE_LIMIT_AUTH_PER_IP:-200} APP_CORS_ALLOWED_ORIGINS: https://${DOMAIN:?DOMAIN is required} APP_DEMO_MODE: ${APP_DEMO_MODE:-false} APP_REGISTRATION_ENABLED: ${APP_REGISTRATION_ENABLED:-false} diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 90433da..35ba284 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -44,6 +44,11 @@ services: SPRING_DATA_REDIS_HOST: redis SPRING_DATA_REDIS_PORT: 6379 JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required (openssl rand -base64 32)} + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} + # Logins per minute from one IP address: must fit a computer lab behind one public IP. + APP_RATE_LIMIT_LOGIN_PER_IP: ${APP_RATE_LIMIT_LOGIN_PER_IP:-100} + APP_RATE_LIMIT_AUTH_PER_IP: ${APP_RATE_LIMIT_AUTH_PER_IP:-200} STORAGE_UPLOAD_DIR: /app/storage/uploads APP_CORS_ALLOWED_ORIGINS: ${APP_CORS_ALLOWED_ORIGINS:-http://localhost:3000,http://localhost:5173} APP_DEMO_MODE: ${APP_DEMO_MODE:-false} diff --git a/docker-compose.yml b/docker-compose.yml index 821b6ce..7d6d9ce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -58,6 +58,8 @@ services: SPRING_DATA_REDIS_HOST: redis SPRING_DATA_REDIS_PORT: 6379 JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required - create .env with output of openssl rand -base64 32} + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} STORAGE_UPLOAD_DIR: /app/storage/uploads APP_DEMO_MODE: ${APP_DEMO_MODE:-false} # Local stack is served over plain HTTP, so the refresh-token cookie cannot be Secure here. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5770b4e..cb5b66b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -158,7 +158,7 @@ sequenceDiagram participant DB as PostgreSQL B->>API: POST /api/v1/auth/login (email, password) - API->>API: Rate limit per IP and per email (5/min) + API->>API: Rate limit per email (5/min) and per IP (100/min) API->>DB: Load user, verify BCrypt hash API->>R: SET auth:refresh:{jti} = userId (TTL 7d) API-->>B: accessToken in body + Set-Cookie refresh_token (httpOnly, Secure, SameSite=Strict, Path=/api/v1/auth) diff --git a/frontend/src/i18n/messages/examEditor.ts b/frontend/src/i18n/messages/examEditor.ts index 21545a8..227ba14 100644 --- a/frontend/src/i18n/messages/examEditor.ts +++ b/frontend/src/i18n/messages/examEditor.ts @@ -17,6 +17,7 @@ export const examEditor = defineMessages({ typeMultipleChoice: 'Pilihan Ganda', typeTrueFalse: 'Benar / Salah', typeEssay: 'Esai', + typeShortAnswer: 'Isian Singkat', deleteQuestion: 'Hapus soal', correctAnswerLabel: 'Kunci Jawaban:', addFailed: 'Gagal menambahkan soal', @@ -28,6 +29,16 @@ export const examEditor = defineMessages({ optionMultipleChoice: 'Pilihan Ganda', optionTrueFalse: 'Benar / Salah', optionEssay: 'Esai / Uraian', + optionShortAnswer: 'Isian Singkat', + answerKey: 'Kunci Jawaban', + answerKeyPlaceholder: 'cth. Jakarta|DKI Jakarta', + answerKeyHint: 'Pisahkan jawaban alternatif dengan tanda |. Huruf besar-kecil, spasi berlebih, dan tanda baca di ujung diabaikan saat menilai.', + chooseCorrectOption: 'Pilih jawaban yang benar terlebih dahulu.', + editQuestion: 'Ubah soal', + editModalTitle: 'Ubah Soal Ujian', + updateFailed: 'Gagal menyimpan perubahan soal', + explanation: 'Pembahasan (opsional)', + explanationPlaceholder: 'Mengapa jawaban itu benar. Belum ditampilkan ke siswa.', points: 'Poin / Bobot Nilai', questionText: 'Teks Soal', questionTextPlaceholder: 'Tulis pernyataan atau pertanyaan soal...', @@ -62,6 +73,7 @@ export const examEditor = defineMessages({ typeMultipleChoice: 'Multiple choice', typeTrueFalse: 'True / False', typeEssay: 'Essay', + typeShortAnswer: 'Short Answer', deleteQuestion: 'Delete question', correctAnswerLabel: 'Answer key:', addFailed: 'Could not add the question', @@ -73,6 +85,16 @@ export const examEditor = defineMessages({ optionMultipleChoice: 'Multiple Choice', optionTrueFalse: 'True / False', optionEssay: 'Essay / Descriptive', + optionShortAnswer: 'Short Answer', + answerKey: 'Answer Key', + answerKeyPlaceholder: 'e.g. Jakarta|DKI Jakarta', + answerKeyHint: 'Separate accepted alternatives with |. Letter case, extra spaces and punctuation at the ends are ignored when grading.', + chooseCorrectOption: 'Choose the correct answer first.', + editQuestion: 'Edit question', + editModalTitle: 'Edit Exam Question', + updateFailed: 'Could not save the question changes', + explanation: 'Explanation (optional)', + explanationPlaceholder: 'Why that answer is correct. Not shown to students yet.', points: 'Points / Score', questionText: 'Question Text', questionTextPlaceholder: 'Enter the problem statement or question...', diff --git a/frontend/src/i18n/messages/examList.ts b/frontend/src/i18n/messages/examList.ts index 82c56d7..6411e4b 100644 --- a/frontend/src/i18n/messages/examList.ts +++ b/frontend/src/i18n/messages/examList.ts @@ -39,6 +39,28 @@ export const examList = defineMessages({ shuffleQuestions: 'Acak Soal', shuffleOptions: 'Acak Pilihan Jawaban', createAndPublish: 'Buat & Publikasikan Ujian', + ownerTeacher: 'Guru Pemilik Ujian', + chooseTeacher: '-- Pilih Guru --', + endBeforeStart: 'Waktu selesai harus setelah waktu mulai.', + durationTooLong: 'Durasi {duration} menit tidak muat di antara waktu mulai dan waktu selesai ({window} menit).', + awaitingGrading: 'Menunggu penilaian guru', + alreadySubmitted: 'Sudah dikumpulkan', + editExam: 'Ubah ujian', + editModalTitle: 'Ubah Ujian CBT', + saveChanges: 'Simpan Perubahan', + updateFailed: 'Gagal menyimpan perubahan ujian', + examType: 'Jenis Ujian', + typeQuiz: 'Kuis / Ulangan Harian', + typeUts: 'UTS', + typeUas: 'UAS', + typePraktik: 'Ujian Praktik', + typeTryout: 'Tryout', + allowRetry: 'Izinkan remidi (siswa boleh mengulang ujian ini)', + retryExam: 'Ulangi Ujian', + showResult: 'Tampilkan nilai ke siswa', + showResultHint: 'Jika tidak dicentang, siswa hanya melihat bahwa ujiannya selesai. Centang nanti untuk membagikan nilai.', + resultNotShared: 'Selesai. Nilai belum dibagikan guru.', + resultHiddenBadge: 'Nilai disembunyikan dari siswa', }, en: { title: 'CBT Exams (Computer-Based Test)', @@ -78,5 +100,27 @@ export const examList = defineMessages({ shuffleQuestions: 'Shuffle Questions', shuffleOptions: 'Shuffle Answer Options', createAndPublish: 'Create & Publish Exam', + ownerTeacher: 'Teacher Who Owns the Exam', + chooseTeacher: '-- Choose Teacher --', + endBeforeStart: 'The end time must be after the start time.', + durationTooLong: 'A duration of {duration} minutes does not fit between the start and end time ({window} minutes).', + awaitingGrading: 'Waiting for teacher grading', + alreadySubmitted: 'Already submitted', + editExam: 'Edit exam', + editModalTitle: 'Edit CBT Exam', + saveChanges: 'Save Changes', + updateFailed: 'Could not save the exam changes', + examType: 'Exam Type', + typeQuiz: 'Quiz / Daily Test', + typeUts: 'Midterm (UTS)', + typeUas: 'Final (UAS)', + typePraktik: 'Practical Exam', + typeTryout: 'Tryout', + allowRetry: 'Allow retakes (students may take this exam again)', + retryExam: 'Retake Exam', + showResult: 'Show the score to students', + showResultHint: 'When unchecked, students only see that their exam is finished. Check it later to share the scores.', + resultNotShared: 'Finished. The teacher has not shared the score yet.', + resultHiddenBadge: 'Score hidden from students', }, }); diff --git a/frontend/src/i18n/messages/examMonitor.ts b/frontend/src/i18n/messages/examMonitor.ts index be9961e..8a074d8 100644 --- a/frontend/src/i18n/messages/examMonitor.ts +++ b/frontend/src/i18n/messages/examMonitor.ts @@ -33,6 +33,7 @@ export const examMonitor = defineMessages({ statusSubmitted: 'Dikumpulkan', statusNeedsGrading: 'Perlu dinilai', statusCompleted: 'Selesai', + statusForceFinished: 'Dihentikan pengawas', warningCount: '{count} Peringatan', warningOne: '1 Peringatan', noFlags: '0 Tanda', @@ -70,6 +71,7 @@ export const examMonitor = defineMessages({ statusSubmitted: 'Submitted', statusNeedsGrading: 'Needs grading', statusCompleted: 'Completed', + statusForceFinished: 'Stopped by proctor', warningCount: '{count} Warnings', warningOne: '1 Warning', noFlags: '0 Flags', diff --git a/frontend/src/i18n/messages/examRunner.ts b/frontend/src/i18n/messages/examRunner.ts index d9603ac..3d08931 100644 --- a/frontend/src/i18n/messages/examRunner.ts +++ b/frontend/src/i18n/messages/examRunner.ts @@ -16,7 +16,26 @@ export const examRunner = defineMessages({ notPassed: 'REMIDIAL (TIDAK LULUS)', backToExams: 'Kembali ke Halaman Ujian', activeSession: 'Sesi Aktif', - autoSaved: 'Tersimpan Otomatis', + allSaved: 'Semua jawaban tersimpan', + unsavedCount: '{count} jawaban belum tersimpan', + notSaved: 'Belum tersimpan', + saveFailedBanner: 'Koneksi bermasalah. {count} jawaban belum tersimpan dan akan dikirim ulang otomatis.', + retryNow: 'Coba sekarang', + unsavedBlocksSubmit: 'Masih ada {count} jawaban yang belum tersimpan. Periksa koneksi, lalu coba lagi.', + submitting: 'Mengumpulkan...', + autoSubmitting: 'Mengumpulkan jawaban Anda. Jangan tutup halaman ini.', + timeUpTitle: 'Waktu Habis', + timeUpText: 'Waktu ujian sudah habis. Jawaban Anda dikumpulkan secara otomatis.', + autoSubmittedTitle: 'Ujian Dikumpulkan Otomatis', + closedTitle: 'Ujian Sudah Ditutup', + closedText: 'Ujian ini sudah ditutup oleh sistem, sehingga jawaban tidak bisa diubah lagi.', + lostAnswers: '{count} jawaban terakhir tidak sempat tersimpan sebelum ujian ditutup.', + pendingGradingTitle: 'Menunggu Penilaian Guru', + pendingGradingText: 'Jawaban esai Anda akan dinilai oleh guru. Nilai akhir tampil setelah penilaian selesai.', + provisionalScore: 'Nilai sementara dari soal yang dinilai otomatis', + pendingGradingHiddenText: 'Jawaban esai Anda akan dinilai oleh guru. Nilai ujian ini dibagikan oleh guru.', + resultHiddenTitle: 'Nilai Belum Dibagikan', + resultHiddenText: 'Jawaban Anda sudah diterima. Nilai ujian ini akan dibagikan oleh guru.', toggleFullscreen: 'Aktifkan/nonaktifkan layar penuh', securityAlert: 'Peringatan Keamanan: {count}/5 pelanggaran tercatat. Meninggalkan tab ujian akan mengumpulkan ujian Anda secara otomatis!', @@ -27,6 +46,8 @@ export const examRunner = defineMessages({ falseLabel: 'Salah', essayLabel: 'Tulis penjelasan / jawaban Anda:', essayPlaceholder: 'Ketik jawaban Anda di sini...', + shortAnswerLabel: 'Jawaban singkat Anda:', + shortAnswerPlaceholder: 'Ketik jawaban singkat...', previous: 'Sebelumnya', nextQuestion: 'Soal Berikutnya', finishAndSubmit: 'Selesai & Kumpulkan Ujian', @@ -54,7 +75,26 @@ export const examRunner = defineMessages({ notPassed: 'REMEDIAL (NOT PASSED)', backToExams: 'Back to Exams', activeSession: 'Active Session', - autoSaved: 'Auto-saved', + allSaved: 'All answers saved', + unsavedCount: '{count} answers not saved yet', + notSaved: 'Not saved yet', + saveFailedBanner: 'Connection problem. {count} answers are not saved yet and will be sent again automatically.', + retryNow: 'Retry now', + unsavedBlocksSubmit: '{count} answers are still not saved. Check your connection, then try again.', + submitting: 'Submitting...', + autoSubmitting: 'Submitting your answers. Do not close this page.', + timeUpTitle: 'Time Is Up', + timeUpText: 'The exam time has run out. Your answers were submitted automatically.', + autoSubmittedTitle: 'Exam Submitted Automatically', + closedTitle: 'Exam Already Closed', + closedText: 'This exam was closed by the system, so the answers can no longer be changed.', + lostAnswers: '{count} of your last answers could not be saved before the exam was closed.', + pendingGradingTitle: 'Waiting for Teacher Grading', + pendingGradingText: 'Your essay answers will be graded by the teacher. The final score appears once grading is done.', + provisionalScore: 'Provisional score from automatically graded questions', + pendingGradingHiddenText: 'Your essay answers will be graded by the teacher. The teacher shares the score of this exam.', + resultHiddenTitle: 'Score Not Shared Yet', + resultHiddenText: 'Your answers have been received. The teacher will share the score of this exam.', toggleFullscreen: 'Toggle fullscreen', securityAlert: 'Security Alert: {count}/5 violations recorded. Leaving the exam tab will submit your exam automatically!', @@ -65,6 +105,8 @@ export const examRunner = defineMessages({ falseLabel: 'False', essayLabel: 'Write your explanation / answer:', essayPlaceholder: 'Type your answer here...', + shortAnswerLabel: 'Your short answer:', + shortAnswerPlaceholder: 'Type a short answer...', previous: 'Previous', nextQuestion: 'Next Question', finishAndSubmit: 'Finish & Submit Exam', diff --git a/frontend/src/pages/exams/ExamEditor.tsx b/frontend/src/pages/exams/ExamEditor.tsx index 53681ab..8d9e3fa 100644 --- a/frontend/src/pages/exams/ExamEditor.tsx +++ b/frontend/src/pages/exams/ExamEditor.tsx @@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react'; import { useParams, Link } from 'react-router-dom'; import api from '../../api/client'; import type { Exam, Question, ApiResponse } from '../../types'; +import { apiErrorMessage } from '../../utils/errors'; import { ArrowLeft, Plus, @@ -10,15 +11,40 @@ import { FileQuestion, CheckCircle, X, + Edit2, } from 'lucide-react'; import { useI18n, type MessageKey } from '../../i18n'; const QUESTION_TYPE_LABELS: Record = { multiple_choice: 'examEditor.typeMultipleChoice', true_false: 'examEditor.typeTrueFalse', + short_answer: 'examEditor.typeShortAnswer', essay: 'examEditor.typeEssay', }; +const OPTION_LETTERS = ['A', 'B', 'C', 'D', 'E'] as const; +type OptionLetter = (typeof OPTION_LETTERS)[number]; + +const EMPTY_FORM = { + questionText: '', + questionType: 'multiple_choice' as Question['questionType'], + optA: '', + optB: '', + optC: '', + optD: '', + optE: '', + // Multiple choice: the letter of the correct option, so retyping an option keeps it marked as the key. + correctLetter: '' as OptionLetter | '', + // True/false: "Benar" or "Salah". Short answer: the key. Essay: the rubric. + correctAnswer: '', + points: 1, + difficulty: 'medium' as Question['difficulty'], + explanation: '', +}; +type QuestionForm = typeof EMPTY_FORM; + +const optionKey = (letter: OptionLetter) => `opt${letter}` as 'optA' | 'optB' | 'optC' | 'optD' | 'optE'; + export const ExamEditor: React.FC = () => { const { id } = useParams<{ id: string }>(); const { t } = useI18n(); @@ -28,23 +54,20 @@ export const ExamEditor: React.FC = () => { // Modals const [modalOpen, setModalOpen] = useState(false); + // null = the modal adds a question; otherwise it edits this one. + const [editingQuestion, setEditingQuestion] = useState(null); + const [formError, setFormError] = useState(null); const [excelModalOpen, setExcelModalOpen] = useState(false); const [excelFile, setExcelFile] = useState(null); const [importLoading, setImportLoading] = useState(false); - const [form, setForm] = useState({ - questionText: '', - questionType: 'multiple_choice' as 'multiple_choice' | 'essay' | 'true_false', - optA: '', - optB: '', - optC: '', - optD: '', - optE: '', - correctAnswer: '', - points: 1, - difficulty: 'medium' as 'easy' | 'medium' | 'hard', - explanation: '', - }); + const [form, setForm] = useState(EMPTY_FORM); + + /** Changes form fields. A message about the previous values no longer applies, so it is cleared. */ + const updateForm = (patch: Partial) => { + setForm((prev) => ({ ...prev, ...patch })); + setFormError(null); + }; const loadExamAndQuestions = async () => { try { @@ -66,47 +89,88 @@ export const ExamEditor: React.FC = () => { if (id) loadExamAndQuestions(); }, [id]); + const openAddModal = () => { + setEditingQuestion(null); + setForm(EMPTY_FORM); + setFormError(null); + setModalOpen(true); + }; + + const openEditModal = (q: Question) => { + const options = q.options ?? []; + const next: QuestionForm = { + ...EMPTY_FORM, + questionText: q.questionText, + questionType: q.questionType, + points: q.points, + difficulty: q.difficulty, + explanation: q.explanation ?? '', + }; + if (q.questionType === 'multiple_choice') { + OPTION_LETTERS.forEach((letter, index) => { + next[optionKey(letter)] = options[index] ?? ''; + }); + // The key is stored as the option text; older imports may hold the letter instead. + const byText = options.findIndex((opt) => opt === q.correctAnswer); + const byLetter = OPTION_LETTERS.findIndex((letter) => letter === q.correctAnswer); + next.correctLetter = OPTION_LETTERS[byText >= 0 ? byText : byLetter] ?? ''; + } else { + next.correctAnswer = q.correctAnswer ?? ''; + } + setEditingQuestion(q); + setForm(next); + setFormError(null); + setModalOpen(true); + }; + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - try { - let options: string[] = []; - let correctAnswer = form.correctAnswer; + setFormError(null); + + let options: string[] = []; + let correctAnswer = form.correctAnswer.trim(); - if (form.questionType === 'multiple_choice') { - options = [form.optA, form.optB, form.optC, form.optD, form.optE].filter(Boolean); - } else if (form.questionType === 'true_false') { - options = ['Benar', 'Salah']; + if (form.questionType === 'multiple_choice') { + options = OPTION_LETTERS.map((letter) => form[optionKey(letter)].trim()).filter(Boolean); + correctAnswer = form.correctLetter ? form[optionKey(form.correctLetter)].trim() : ''; + if (!correctAnswer) { + setFormError(t('examEditor.chooseCorrectOption')); + return; } + } else if (form.questionType === 'true_false') { + options = ['Benar', 'Salah']; + if (!correctAnswer) { + setFormError(t('examEditor.chooseCorrectOption')); + return; + } + } + + const payload = { + examinationId: Number(id), + questionText: form.questionText, + questionType: form.questionType, + options, + correctAnswer, + points: Number(form.points), + difficulty: form.difficulty, + explanation: form.explanation, + // The update replaces every field, so pass the media paths through unchanged. + audioPath: editingQuestion?.audioPath, + imagePath: editingQuestion?.imagePath, + }; - const payload = { - examinationId: Number(id), - questionText: form.questionText, - questionType: form.questionType, - options, - correctAnswer, - points: Number(form.points), - difficulty: form.difficulty, - explanation: form.explanation, - }; - - await api.post(`/exams/${id}/questions`, payload); + try { + if (editingQuestion) { + await api.put(`/exams/${id}/questions/${editingQuestion.id}`, payload); + } else { + await api.post(`/exams/${id}/questions`, payload); + } setModalOpen(false); - setForm({ - questionText: '', - questionType: 'multiple_choice', - optA: '', - optB: '', - optC: '', - optD: '', - optE: '', - correctAnswer: '', - points: 1, - difficulty: 'medium', - explanation: '', - }); + setEditingQuestion(null); + setForm(EMPTY_FORM); loadExamAndQuestions(); - } catch (err: any) { - alert(err.response?.data?.message || t('examEditor.addFailed')); + } catch (err) { + setFormError(apiErrorMessage(err, editingQuestion ? t('examEditor.updateFailed') : t('examEditor.addFailed'))); } }; @@ -160,7 +224,7 @@ export const ExamEditor: React.FC = () => { {t('examEditor.excelImport')} +
+ + +
{q.questionText}
@@ -258,7 +332,7 @@ export const ExamEditor: React.FC = () => { )} - {/* Add Question Modal */} + {/* Add / Edit Question Modal */} {modalOpen && (
@@ -269,7 +343,9 @@ export const ExamEditor: React.FC = () => { > -

{t('examEditor.modalTitle')}

+

+ {editingQuestion ? t('examEditor.editModalTitle') : t('examEditor.modalTitle')} +

@@ -277,11 +353,19 @@ export const ExamEditor: React.FC = () => {
@@ -293,7 +377,7 @@ export const ExamEditor: React.FC = () => { min={1} max={50} value={form.points} - onChange={(e) => setForm({ ...form, points: Number(e.target.value) })} + onChange={(e) => updateForm({ points: Number(e.target.value) })} className="w-full border border-slate-300 rounded-xl px-3 py-2 focus:ring-1 focus:ring-emerald-500 focus:outline-none" />
@@ -305,7 +389,7 @@ export const ExamEditor: React.FC = () => { rows={3} required value={form.questionText} - onChange={(e) => setForm({ ...form, questionText: e.target.value })} + onChange={(e) => updateForm({ questionText: e.target.value })} className="w-full border border-slate-300 rounded-xl px-3 py-2 focus:ring-1 focus:ring-emerald-500 focus:outline-none" placeholder={t('examEditor.questionTextPlaceholder')} /> @@ -314,8 +398,8 @@ export const ExamEditor: React.FC = () => { {form.questionType === 'multiple_choice' && (
{t('examEditor.answerOptions')}
- {['A', 'B', 'C', 'D', 'E'].map((letter) => { - const keyName = `opt${letter}` as keyof typeof form; + {OPTION_LETTERS.map((letter) => { + const keyName = optionKey(letter); return (
@@ -325,16 +409,18 @@ export const ExamEditor: React.FC = () => { type="text" required={letter === 'A' || letter === 'B'} placeholder={t('examEditor.optionPlaceholder', { letter })} - value={String(form[keyName])} - onChange={(e) => setForm({ ...form, [keyName]: e.target.value })} + aria-label={t('examEditor.optionPlaceholder', { letter })} + value={form[keyName]} + onChange={(e) => updateForm({ [keyName]: e.target.value })} className="flex-1 border border-slate-300 rounded-xl px-3 py-1.5 focus:ring-1 focus:ring-emerald-500 focus:outline-none text-xs" />
)} + {form.questionType === 'short_answer' && ( +
+ + updateForm({ correctAnswer: e.target.value })} + placeholder={t('examEditor.answerKeyPlaceholder')} + className="w-full border border-slate-300 rounded-xl px-3 py-2 focus:ring-1 focus:ring-emerald-500 focus:outline-none" + /> +

{t('examEditor.answerKeyHint')}

+
+ )} + {form.questionType === 'essay' && (
- +