forge
Explore
Log in

Don't you dare go Hollow

Cover profiles, courses, marks, statistics, and admin seed

Browse files at this commit

a3d12c36f89b9500555e0e70bf016f2a2f9d498eAhmet Kaan GümüşParent: ea497d9
  • test
    • cover profiles, courses, marks, statistics, and admin seed
Show full message
✅ test: cover profiles, courses, marks, statistics, and admin seed

Integration: course CRUD with creator/manager guards and validation,
idempotent enrollment with roster and /courses/me, in-course exam
creation, grading gated on enrollment and course management, exam
statistics, weighted course averages and self-or-teacher mark reports,
course-delete cascade, concurrent enrollments converging on one row,
profile lifecycle (empty start, /users/me patch semantics, invalid
fields, admin read/edit), and the admin seed (creates a working admin,
idempotent, refuses to promote an existing non-admin).

Persistence: profiles and course marks survive a database reopen.
Common helpers: me_id, create_course, create_exam, enroll.
tests/common/mod.rsmodified+55 -0
@@ -119,3 +119,58 @@ pub async fn login(app: &Router, username: &str) -> String {
119 pub fn id_of(v: &Value) -> String {119 pub fn id_of(v: &Value) -> String {
120 v["id"].as_str().expect("id field").to_string()120 v["id"].as_str().expect("id field").to_string()
121 }121 }
122+
123+/// The caller's own user id via `GET /auth/me`.
124+pub async fn me_id(app: &Router, cookie: &str) -> String {
125+ let res = send(app, "GET", "/auth/me", Some(cookie), None).await;
126+ assert_eq!(res.status, StatusCode::OK, "GET /auth/me");
127+ id_of(&res.body)
128+}
129+
130+/// Create a course as `cookie` (asserts 201); returns its id.
131+pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String {
132+ let res = send(
133+ app,
134+ "POST",
135+ "/courses",
136+ Some(cookie),
137+ Some(json!({ "title": title })),
138+ )
139+ .await;
140+ assert_eq!(res.status, StatusCode::CREATED, "create course {title}");
141+ id_of(&res.body)
142+}
143+
144+/// Create an exam inside `course` as `cookie` (asserts 201); returns its id.
145+pub async fn create_exam(
146+ app: &Router,
147+ cookie: &str,
148+ course: &str,
149+ title: &str,
150+ kind: &str,
151+ weight: i64,
152+) -> String {
153+ let res = send(
154+ app,
155+ "POST",
156+ &format!("/courses/{course}/exams"),
157+ Some(cookie),
158+ Some(json!({ "title": title, "kind": kind, "weight": weight })),
159+ )
160+ .await;
161+ assert_eq!(res.status, StatusCode::CREATED, "create exam {title}");
162+ id_of(&res.body)
163+}
164+
165+/// Enroll `user_id` into `course` as `cookie` (asserts 200).
166+pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) {
167+ let res = send(
168+ app,
169+ "POST",
170+ &format!("/courses/{course}/enrollments"),
171+ Some(cookie),
172+ Some(json!({ "user_id": user_id })),
173+ )
174+ .await;
175+ assert_eq!(res.status, StatusCode::OK, "enroll {user_id}");
176+}
tests/integration.rsmodified+1184 -82
@@ -5,8 +5,11 @@ mod common;
5 5
6 use axum::body::Body;6 use axum::body::Body;
7 use axum::http::{Request, StatusCode};7 use axum::http::{Request, StatusCode};
8-use common::{app_and_db, id_of, login, login_as, mem_app, send};8+use common::{
9+ app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, mem_app, send,
10+};
9 use hezarfen_backend::domain::session::Session;11 use hezarfen_backend::domain::session::Session;
12+use hezarfen_backend::domain::user::{Password, User, Username};
10 use hezarfen_backend::state::AppState;13 use hezarfen_backend::state::AppState;
11 use hezarfen_backend::{build_router, database};14 use hezarfen_backend::{build_router, database};
12 use serde_json::json;15 use serde_json::json;
@@ -94,7 +97,10 @@ async fn protected_routes_require_session() {
94 ("GET", "/events"),97 ("GET", "/events"),
95 ("POST", "/events"),98 ("POST", "/events"),
96 ("GET", "/exams"),99 ("GET", "/exams"),
97- ("POST", "/exams"),100+ ("GET", "/courses"),
101+ ("POST", "/courses"),
102+ ("GET", "/courses/me"),
103+ ("GET", "/marks/me"),
98 ] {104 ] {
99 let res = send(&app, method, uri, None, None).await;105 let res = send(&app, method, uri, None, None).await;
100 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}");106 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}");
@@ -705,24 +711,27 @@ async fn event_timestamps_echo_and_validate() {
705 // --- exams + results -----------------------------------------------------711 // --- exams + results -----------------------------------------------------
706 712
707 #[tokio::test]713 #[tokio::test]
708-async fn exams_are_shared_but_creator_guarded() {714+async fn exams_are_shared_but_course_guarded() {
709 let (app, db) = app_and_db().await;715 let (app, db) = app_and_db().await;
710 let ali = login_as(&app, &db, "ali", "teacher").await;716 let ali = login_as(&app, &db, "ali", "teacher").await;
711 let veli = login_as(&app, &db, "veli", "teacher").await;717 let veli = login_as(&app, &db, "veli", "teacher").await;
712 718
719+ let course_id = create_course(&app, &ali, "algebra").await;
713 let ex = send(720 let ex = send(
714 &app,721 &app,
715 "POST",722 "POST",
716- "/exams",723+ &format!("/courses/{course_id}/exams"),
717 Some(&ali),724 Some(&ali),
718- Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })),725+ Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz", "weight": 2 })),
719 )726 )
720 .await;727 .await;
721 assert_eq!(ex.status, StatusCode::CREATED);728 assert_eq!(ex.status, StatusCode::CREATED);
722 assert_eq!(ex.body["kind"], "quiz");729 assert_eq!(ex.body["kind"], "quiz");
730+ assert_eq!(ex.body["course"], course_id);
731+ assert_eq!(ex.body["weight"], 2);
723 let exam_id = id_of(&ex.body);732 let exam_id = id_of(&ex.body);
724 733
725- // Any authenticated user can read the exam and the list.734+ // Any authenticated user can read the exam and the lists.
726 assert_eq!(735 assert_eq!(
727 send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None)736 send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None)
728 .await737 .await
@@ -738,8 +747,23 @@ async fn exams_are_shared_but_creator_guarded() {
738 .len(),747 .len(),
739 1748 1
740 );749 );
750+ assert_eq!(
751+ send(
752+ &app,
753+ "GET",
754+ &format!("/courses/{course_id}/exams"),
755+ Some(&veli),
756+ None
757+ )
758+ .await
759+ .body
760+ .as_array()
761+ .unwrap()
762+ .len(),
763+ 1
764+ );
741 765
742- // Non-creator teacher cannot edit or delete.766+ // A teacher who doesn't manage the course cannot edit or delete its exams.
743 assert_eq!(767 assert_eq!(
744 send(768 send(
745 &app,769 &app,
@@ -765,7 +789,7 @@ async fn exams_are_shared_but_creator_guarded() {
765 StatusCode::FORBIDDEN789 StatusCode::FORBIDDEN
766 );790 );
767 791
768- // Creator edits (partial) — kind flips homework, title kept.792+ // Course creator edits (partial) — kind flips homework, title/weight kept.
769 let res = send(793 let res = send(
770 &app,794 &app,
771 "PATCH",795 "PATCH",
@@ -777,39 +801,83 @@ async fn exams_are_shared_but_creator_guarded() {
777 assert_eq!(res.status, StatusCode::OK);801 assert_eq!(res.status, StatusCode::OK);
778 assert_eq!(res.body["kind"], "homework");802 assert_eq!(res.body["kind"], "homework");
779 assert_eq!(res.body["title"], "ch3");803 assert_eq!(res.body["title"], "ch3");
804+ assert_eq!(res.body["weight"], 2);
780 }805 }
781 806
782 #[tokio::test]807 #[tokio::test]
783 async fn exam_input_validation() {808 async fn exam_input_validation() {
784 let (app, db) = app_and_db().await;809 let (app, db) = app_and_db().await;
785 let ali = login_as(&app, &db, "ali", "teacher").await;810 let ali = login_as(&app, &db, "ali", "teacher").await;
811+ let course_id = create_course(&app, &ali, "algebra").await;
812+ let exams_uri = format!("/courses/{course_id}/exams");
786 813
787 // Missing/blank title -> 400.814 // Missing/blank title -> 400.
788 assert_eq!(815 assert_eq!(
789 send(816 send(
790 &app,817 &app,
791 "POST",818 "POST",
792- "/exams",819+ &exams_uri,
793 Some(&ali),820 Some(&ali),
794- Some(json!({"title":" ","kind":"quiz"}))821+ Some(json!({"title":" ","kind":"quiz","weight":1}))
795 )822 )
796 .await823 .await
797 .status,824 .status,
798 StatusCode::BAD_REQUEST825 StatusCode::BAD_REQUEST
799 );826 );
800- // Unknown kind -> 400.827+ // Unknown kind -> 400 ("final" is valid now; "essay" is not).
801 assert_eq!(828 assert_eq!(
802 send(829 send(
803 &app,830 &app,
804 "POST",831 "POST",
805- "/exams",832+ &exams_uri,
806 Some(&ali),833 Some(&ali),
807- Some(json!({"title":"t","kind":"final"}))834+ Some(json!({"title":"t","kind":"essay","weight":1}))
808 )835 )
809 .await836 .await
810 .status,837 .status,
811 StatusCode::BAD_REQUEST838 StatusCode::BAD_REQUEST
812 );839 );
840+ assert_eq!(
841+ send(
842+ &app,
843+ "POST",
844+ &exams_uri,
845+ Some(&ali),
846+ Some(json!({"title":"t","kind":"final","weight":1}))
847+ )
848+ .await
849+ .status,
850+ StatusCode::CREATED
851+ );
852+ // Weight out of range or missing -> 400 / 422.
853+ for weight in [json!(0), json!(101), json!(-1)] {
854+ assert_eq!(
855+ send(
856+ &app,
857+ "POST",
858+ &exams_uri,
859+ Some(&ali),
860+ Some(json!({"title":"t","kind":"quiz","weight":weight}))
861+ )
862+ .await
863+ .status,
864+ StatusCode::BAD_REQUEST,
865+ "weight {weight}"
866+ );
867+ }
868+ assert_eq!(
869+ send(
870+ &app,
871+ "POST",
872+ &exams_uri,
873+ Some(&ali),
874+ Some(json!({"title":"t","kind":"quiz"}))
875+ )
876+ .await
877+ .status,
878+ StatusCode::UNPROCESSABLE_ENTITY,
879+ "missing weight is a body schema error"
880+ );
813 // Missing exam -> 404.881 // Missing exam -> 404.
814 assert_eq!(882 assert_eq!(
815 send(&app, "GET", "/exams/nope", Some(&ali), None)883 send(&app, "GET", "/exams/nope", Some(&ali), None)
@@ -825,19 +893,11 @@ async fn grading_upsert_and_own_result() {
825 let teacher = login_as(&app, &db, "teacher", "teacher").await;893 let teacher = login_as(&app, &db, "teacher", "teacher").await;
826 let alice = login(&app, "alice").await; // student894 let alice = login(&app, "alice").await; // student
827 let bob = login(&app, "bob").await; // student895 let bob = login(&app, "bob").await; // student
828- let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);896+ let alice_id = me_id(&app, &alice).await;
829 897
830- let exam_id = id_of(898+ let course_id = create_course(&app, &teacher, "algebra").await;
831- &send(899+ enroll(&app, &teacher, &course_id, &alice_id).await;
832- &app,900+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;
833- "POST",
834- "/exams",
835- Some(&teacher),
836- Some(json!({"title":"mt","kind":"quiz"})),
837- )
838- .await
839- .body,
840- );
841 901
842 // Before grading, the student's own result is 404.902 // Before grading, the student's own result is 404.
843 assert_eq!(903 assert_eq!(
@@ -964,28 +1024,21 @@ async fn grading_rbac_and_validation() {
964 let teacher = login_as(&app, &db, "teacher", "teacher").await;1024 let teacher = login_as(&app, &db, "teacher", "teacher").await;
965 let alice = login(&app, "alice").await; // student1025 let alice = login(&app, "alice").await; // student
966 let bob = login(&app, "bob").await; // student1026 let bob = login(&app, "bob").await; // student
967- let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);1027+ let alice_id = me_id(&app, &alice).await;
1028+ let bob_id = me_id(&app, &bob).await;
968 1029
969- let exam_id = id_of(1030+ let course_id = create_course(&app, &teacher, "algebra").await;
970- &send(1031+ enroll(&app, &teacher, &course_id, &alice_id).await;
971- &app,1032+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework", 1).await;
972- "POST",
973- "/exams",
974- Some(&teacher),
975- Some(json!({"title":"e","kind":"homework"})),
976- )
977- .await
978- .body,
979- );
980 1033
981 // Students cannot create exams, grade anyone, list all results, or delete a result.1034 // Students cannot create exams, grade anyone, list all results, or delete a result.
982 assert_eq!(1035 assert_eq!(
983 send(1036 send(
984 &app,1037 &app,
985 "POST",1038 "POST",
986- "/exams",1039+ &format!("/courses/{course_id}/exams"),
987 Some(&alice),1040 Some(&alice),
988- Some(json!({"title":"x","kind":"quiz"}))1041+ Some(json!({"title":"x","kind":"quiz","weight":1}))
989 )1042 )
990 .await1043 .await
991 .status,1044 .status,
@@ -1054,6 +1107,19 @@ async fn grading_rbac_and_validation() {
1054 .status,1107 .status,
1055 StatusCode::BAD_REQUEST1108 StatusCode::BAD_REQUEST
1056 );1109 );
1110+ // Target exists but is not enrolled in the course -> 400.
1111+ assert_eq!(
1112+ send(
1113+ &app,
1114+ "POST",
1115+ &format!("/exams/{exam_id}/results"),
1116+ Some(&teacher),
1117+ Some(json!({"mark":50,"user_id":bob_id}))
1118+ )
1119+ .await
1120+ .status,
1121+ StatusCode::BAD_REQUEST
1122+ );
1057 // Grading on a missing exam -> 404.1123 // Grading on a missing exam -> 404.
1058 assert_eq!(1124 assert_eq!(
1059 send(1125 send(
@@ -1074,25 +1140,709 @@ async fn deleting_exam_cascades_results() {
1074 let (app, db) = app_and_db().await;1140 let (app, db) = app_and_db().await;
1075 let teacher = login_as(&app, &db, "teacher", "teacher").await;1141 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1076 let alice = login(&app, "alice").await;1142 let alice = login(&app, "alice").await;
1077- let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);1143+ let alice_id = me_id(&app, &alice).await;
1078 1144
1079- let exam_id = id_of(1145+ let course_id = create_course(&app, &teacher, "algebra").await;
1080- &send(1146+ enroll(&app, &teacher, &course_id, &alice_id).await;
1147+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await;
1148+ send(
1149+ &app,
1150+ "POST",
1151+ &format!("/exams/{exam_id}/results"),
1152+ Some(&teacher),
1153+ Some(json!({"mark":60,"user_id":alice_id})),
1154+ )
1155+ .await;
1156+
1157+ assert_eq!(
1158+ send(
1081 &app,1159 &app,
1082- "POST",1160+ "DELETE",
1083- "/exams",1161+ &format!("/exams/{exam_id}"),
1084 Some(&teacher),1162 Some(&teacher),
1085- Some(json!({"title":"e","kind":"quiz"})),1163+ None
1086 )1164 )
1087 .await1165 .await
1088- .body,1166+ .status,
1167+ StatusCode::NO_CONTENT
1168+ );
1169+ // Exam gone; the student's result is gone with it.
1170+ assert_eq!(
1171+ send(
1172+ &app,
1173+ "GET",
1174+ &format!("/exams/{exam_id}"),
1175+ Some(&teacher),
1176+ None
1177+ )
1178+ .await
1179+ .status,
1180+ StatusCode::NOT_FOUND
1181+ );
1182+ assert_eq!(
1183+ send(
1184+ &app,
1185+ "GET",
1186+ &format!("/exams/{exam_id}/result"),
1187+ Some(&alice),
1188+ None
1189+ )
1190+ .await
1191+ .status,
1192+ StatusCode::NOT_FOUND
1193+ );
1194+}
1195+
1196+// --- courses + enrollments + marks ----------------------------------------
1197+
1198+#[tokio::test]
1199+async fn courses_are_shared_but_creator_guarded() {
1200+ let (app, db) = app_and_db().await;
1201+ let ali = login_as(&app, &db, "ali", "teacher").await;
1202+ let veli = login_as(&app, &db, "veli", "teacher").await;
1203+ let boss = login_as(&app, &db, "boss", "manager").await;
1204+
1205+ let res = send(
1206+ &app,
1207+ "POST",
1208+ "/courses",
1209+ Some(&ali),
1210+ Some(json!({ "title": "algebra", "description": "numbers" })),
1211+ )
1212+ .await;
1213+ assert_eq!(res.status, StatusCode::CREATED);
1214+ assert_eq!(res.body["title"], "algebra");
1215+ let course_id = id_of(&res.body);
1216+
1217+ // Any authenticated user can read the course and the list.
1218+ assert_eq!(
1219+ send(
1220+ &app,
1221+ "GET",
1222+ &format!("/courses/{course_id}"),
1223+ Some(&veli),
1224+ None
1225+ )
1226+ .await
1227+ .status,
1228+ StatusCode::OK
1229+ );
1230+ assert_eq!(
1231+ send(&app, "GET", "/courses", Some(&veli), None)
1232+ .await
1233+ .body
1234+ .as_array()
1235+ .unwrap()
1236+ .len(),
1237+ 1
1238+ );
1239+
1240+ // Non-creator teacher cannot edit or delete.
1241+ assert_eq!(
1242+ send(
1243+ &app,
1244+ "PATCH",
1245+ &format!("/courses/{course_id}"),
1246+ Some(&veli),
1247+ Some(json!({"title":"hijack"}))
1248+ )
1249+ .await
1250+ .status,
1251+ StatusCode::FORBIDDEN
1252+ );
1253+ assert_eq!(
1254+ send(
1255+ &app,
1256+ "DELETE",
1257+ &format!("/courses/{course_id}"),
1258+ Some(&veli),
1259+ None
1260+ )
1261+ .await
1262+ .status,
1263+ StatusCode::FORBIDDEN
1264+ );
1265+
1266+ // Creator edits (partial) — description flips, title kept.
1267+ let res = send(
1268+ &app,
1269+ "PATCH",
1270+ &format!("/courses/{course_id}"),
1271+ Some(&ali),
1272+ Some(json!({ "description": "letters" })),
1273+ )
1274+ .await;
1275+ assert_eq!(res.status, StatusCode::OK);
1276+ assert_eq!(res.body["title"], "algebra");
1277+ assert_eq!(res.body["description"], "letters");
1278+
1279+ // A manager can edit anyone's course.
1280+ assert_eq!(
1281+ send(
1282+ &app,
1283+ "PATCH",
1284+ &format!("/courses/{course_id}"),
1285+ Some(&boss),
1286+ Some(json!({"title":"algebra II"}))
1287+ )
1288+ .await
1289+ .status,
1290+ StatusCode::OK
1291+ );
1292+}
1293+
1294+#[tokio::test]
1295+async fn course_input_validation() {
1296+ let (app, db) = app_and_db().await;
1297+ let ali = login_as(&app, &db, "ali", "teacher").await;
1298+
1299+ // Missing/blank title -> 400.
1300+ assert_eq!(
1301+ send(
1302+ &app,
1303+ "POST",
1304+ "/courses",
1305+ Some(&ali),
1306+ Some(json!({"title":" "}))
1307+ )
1308+ .await
1309+ .status,
1310+ StatusCode::BAD_REQUEST
1311+ );
1312+ // Missing course -> 404.
1313+ assert_eq!(
1314+ send(&app, "GET", "/courses/nope", Some(&ali), None)
1315+ .await
1316+ .status,
1317+ StatusCode::NOT_FOUND
1089 );1318 );
1319+}
1320+
1321+#[tokio::test]
1322+async fn enrollment_upsert_roster_and_my_courses() {
1323+ let (app, db) = app_and_db().await;
1324+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1325+ let alice = login(&app, "alice").await; // student
1326+ let bob = login(&app, "bob").await; // student
1327+ let alice_id = me_id(&app, &alice).await;
1328+ let course_id = create_course(&app, &teacher, "algebra").await;
1329+
1330+ // Enrolling twice is an upsert: same row id both times.
1331+ let first = send(
1332+ &app,
1333+ "POST",
1334+ &format!("/courses/{course_id}/enrollments"),
1335+ Some(&teacher),
1336+ Some(json!({ "user_id": alice_id })),
1337+ )
1338+ .await;
1339+ assert_eq!(first.status, StatusCode::OK);
1340+ let second = send(
1341+ &app,
1342+ "POST",
1343+ &format!("/courses/{course_id}/enrollments"),
1344+ Some(&teacher),
1345+ Some(json!({ "user_id": alice_id })),
1346+ )
1347+ .await;
1348+ assert_eq!(id_of(&first.body), id_of(&second.body), "upsert same row");
1349+
1350+ // Roster lists alice once; students can't read the roster.
1351+ let roster = send(
1352+ &app,
1353+ "GET",
1354+ &format!("/courses/{course_id}/enrollments"),
1355+ Some(&teacher),
1356+ None,
1357+ )
1358+ .await;
1359+ assert_eq!(roster.body.as_array().unwrap().len(), 1);
1360+ assert_eq!(
1361+ send(
1362+ &app,
1363+ "GET",
1364+ &format!("/courses/{course_id}/enrollments"),
1365+ Some(&alice),
1366+ None
1367+ )
1368+ .await
1369+ .status,
1370+ StatusCode::FORBIDDEN
1371+ );
1372+
1373+ // /courses/me shows the course for alice, stays empty for bob.
1374+ assert_eq!(
1375+ send(&app, "GET", "/courses/me", Some(&alice), None)
1376+ .await
1377+ .body
1378+ .as_array()
1379+ .unwrap()
1380+ .len(),
1381+ 1
1382+ );
1383+ assert_eq!(
1384+ send(&app, "GET", "/courses/me", Some(&bob), None)
1385+ .await
1386+ .body
1387+ .as_array()
1388+ .unwrap()
1389+ .len(),
1390+ 0
1391+ );
1392+
1393+ // Unenroll -> 204; repeating -> 404.
1394+ assert_eq!(
1395+ send(
1396+ &app,
1397+ "DELETE",
1398+ &format!("/courses/{course_id}/enrollments/{alice_id}"),
1399+ Some(&teacher),
1400+ None
1401+ )
1402+ .await
1403+ .status,
1404+ StatusCode::NO_CONTENT
1405+ );
1406+ assert_eq!(
1407+ send(
1408+ &app,
1409+ "DELETE",
1410+ &format!("/courses/{course_id}/enrollments/{alice_id}"),
1411+ Some(&teacher),
1412+ None
1413+ )
1414+ .await
1415+ .status,
1416+ StatusCode::NOT_FOUND
1417+ );
1418+}
1419+
1420+#[tokio::test]
1421+async fn enrollment_requires_course_management() {
1422+ let (app, db) = app_and_db().await;
1423+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1424+ let veli = login_as(&app, &db, "veli", "teacher").await;
1425+ let boss = login_as(&app, &db, "boss", "manager").await;
1426+ let alice = login(&app, "alice").await; // student
1427+ let alice_id = me_id(&app, &alice).await;
1428+ let course_id = create_course(&app, &teacher, "algebra").await;
1429+
1430+ // A teacher who doesn't manage the course cannot enroll anyone.
1431+ assert_eq!(
1432+ send(
1433+ &app,
1434+ "POST",
1435+ &format!("/courses/{course_id}/enrollments"),
1436+ Some(&veli),
1437+ Some(json!({ "user_id": alice_id }))
1438+ )
1439+ .await
1440+ .status,
1441+ StatusCode::FORBIDDEN
1442+ );
1443+ // A manager can.
1444+ assert_eq!(
1445+ send(
1446+ &app,
1447+ "POST",
1448+ &format!("/courses/{course_id}/enrollments"),
1449+ Some(&boss),
1450+ Some(json!({ "user_id": alice_id }))
1451+ )
1452+ .await
1453+ .status,
1454+ StatusCode::OK
1455+ );
1456+ // Unknown target -> 400; missing course -> 404.
1457+ assert_eq!(
1458+ send(
1459+ &app,
1460+ "POST",
1461+ &format!("/courses/{course_id}/enrollments"),
1462+ Some(&teacher),
1463+ Some(json!({ "user_id": "ghost" }))
1464+ )
1465+ .await
1466+ .status,
1467+ StatusCode::BAD_REQUEST
1468+ );
1469+ assert_eq!(
1470+ send(
1471+ &app,
1472+ "POST",
1473+ "/courses/nope/enrollments",
1474+ Some(&teacher),
1475+ Some(json!({ "user_id": alice_id }))
1476+ )
1477+ .await
1478+ .status,
1479+ StatusCode::NOT_FOUND
1480+ );
1481+}
1482+
1483+#[tokio::test]
1484+async fn exam_creation_lives_under_courses() {
1485+ let (app, db) = app_and_db().await;
1486+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1487+ let veli = login_as(&app, &db, "veli", "teacher").await;
1488+ let alice = login(&app, "alice").await; // student
1489+
1490+ // The old flat creation route is gone: /exams only serves GET now.
1491+ assert_eq!(
1492+ send(
1493+ &app,
1494+ "POST",
1495+ "/exams",
1496+ Some(&teacher),
1497+ Some(json!({"title":"t","kind":"quiz","weight":1}))
1498+ )
1499+ .await
1500+ .status,
1501+ StatusCode::METHOD_NOT_ALLOWED
1502+ );
1503+
1504+ let course_id = create_course(&app, &teacher, "algebra").await;
1505+ // Creation inside the course echoes course + weight.
1506+ let res = send(
1507+ &app,
1508+ "POST",
1509+ &format!("/courses/{course_id}/exams"),
1510+ Some(&teacher),
1511+ Some(json!({"title":"mt","kind":"midterm","weight":3})),
1512+ )
1513+ .await;
1514+ assert_eq!(res.status, StatusCode::CREATED);
1515+ assert_eq!(res.body["course"], course_id);
1516+ assert_eq!(res.body["weight"], 3);
1517+
1518+ // A teacher who doesn't manage the course cannot add exams to it.
1519+ assert_eq!(
1520+ send(
1521+ &app,
1522+ "POST",
1523+ &format!("/courses/{course_id}/exams"),
1524+ Some(&veli),
1525+ Some(json!({"title":"x","kind":"quiz","weight":1}))
1526+ )
1527+ .await
1528+ .status,
1529+ StatusCode::FORBIDDEN
1530+ );
1531+
1532+ // Any authenticated user (a student) can list the course's exams.
1533+ assert_eq!(
1534+ send(
1535+ &app,
1536+ "GET",
1537+ &format!("/courses/{course_id}/exams"),
1538+ Some(&alice),
1539+ None
1540+ )
1541+ .await
1542+ .body
1543+ .as_array()
1544+ .unwrap()
1545+ .len(),
1546+ 1
1547+ );
1548+}
1549+
1550+#[tokio::test]
1551+async fn grading_requires_enrollment() {
1552+ let (app, db) = app_and_db().await;
1553+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1554+ let alice = login(&app, "alice").await; // student
1555+ let alice_id = me_id(&app, &alice).await;
1556+
1557+ let course_id = create_course(&app, &teacher, "algebra").await;
1558+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;
1559+ let grade_uri = format!("/exams/{exam_id}/results");
1560+ let grade_body = json!({ "mark": 70, "user_id": alice_id });
1561+
1562+ // Not enrolled -> 400.
1563+ assert_eq!(
1564+ send(
1565+ &app,
1566+ "POST",
1567+ &grade_uri,
1568+ Some(&teacher),
1569+ Some(grade_body.clone())
1570+ )
1571+ .await
1572+ .status,
1573+ StatusCode::BAD_REQUEST
1574+ );
1575+
1576+ // Enrolled -> 200.
1577+ enroll(&app, &teacher, &course_id, &alice_id).await;
1578+ assert_eq!(
1579+ send(
1580+ &app,
1581+ "POST",
1582+ &grade_uri,
1583+ Some(&teacher),
1584+ Some(grade_body.clone())
1585+ )
1586+ .await
1587+ .status,
1588+ StatusCode::OK
1589+ );
1590+
1591+ // Unenrolling blocks further grading but keeps the recorded result:
1592+ // the row still lists for the teacher and the student still reads it.
1593+ assert_eq!(
1594+ send(
1595+ &app,
1596+ "DELETE",
1597+ &format!("/courses/{course_id}/enrollments/{alice_id}"),
1598+ Some(&teacher),
1599+ None
1600+ )
1601+ .await
1602+ .status,
1603+ StatusCode::NO_CONTENT
1604+ );
1605+ assert_eq!(
1606+ send(&app, "POST", &grade_uri, Some(&teacher), Some(grade_body))
1607+ .await
1608+ .status,
1609+ StatusCode::BAD_REQUEST
1610+ );
1611+ assert_eq!(
1612+ send(&app, "GET", &grade_uri, Some(&teacher), None)
1613+ .await
1614+ .body
1615+ .as_array()
1616+ .unwrap()
1617+ .len(),
1618+ 1
1619+ );
1620+ assert_eq!(
1621+ send(
1622+ &app,
1623+ "GET",
1624+ &format!("/exams/{exam_id}/result"),
1625+ Some(&alice),
1626+ None
1627+ )
1628+ .await
1629+ .body["mark"],
1630+ 70
1631+ );
1632+
1633+ // ...but the mark vanishes from the report until re-enrollment restores it.
1634+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
1635+ assert_eq!(report.body["courses"].as_array().unwrap().len(), 0);
1636+ enroll(&app, &teacher, &course_id, &alice_id).await;
1637+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
1638+ assert_eq!(report.body["courses"][0]["average"], 70.0);
1639+}
1640+
1641+#[tokio::test]
1642+async fn exam_writes_follow_course_management() {
1643+ let (app, db) = app_and_db().await;
1644+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1645+ let veli = login_as(&app, &db, "veli", "teacher").await;
1646+ let boss = login_as(&app, &db, "boss", "manager").await;
1647+ let course_id = create_course(&app, &teacher, "algebra").await;
1648+
1649+ // A manager creates an exam in the teacher's course...
1650+ let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm", 2).await;
1651+
1652+ // ...and the course creator (not the exam's creator) can edit and delete it.
1653+ assert_eq!(
1654+ send(
1655+ &app,
1656+ "PATCH",
1657+ &format!("/exams/{exam_id}"),
1658+ Some(&teacher),
1659+ Some(json!({"weight":5}))
1660+ )
1661+ .await
1662+ .body["weight"],
1663+ 5
1664+ );
1665+ // An unrelated teacher still cannot.
1666+ assert_eq!(
1667+ send(
1668+ &app,
1669+ "PATCH",
1670+ &format!("/exams/{exam_id}"),
1671+ Some(&veli),
1672+ Some(json!({"weight":1}))
1673+ )
1674+ .await
1675+ .status,
1676+ StatusCode::FORBIDDEN
1677+ );
1678+ assert_eq!(
1679+ send(
1680+ &app,
1681+ "DELETE",
1682+ &format!("/exams/{exam_id}"),
1683+ Some(&teacher),
1684+ None
1685+ )
1686+ .await
1687+ .status,
1688+ StatusCode::NO_CONTENT
1689+ );
1690+}
1691+
1692+#[tokio::test]
1693+async fn exam_statistics_summarize_results() {
1694+ let (app, db) = app_and_db().await;
1695+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1696+ let alice = login(&app, "alice").await;
1697+ let bob = login(&app, "bob").await;
1698+ let alice_id = me_id(&app, &alice).await;
1699+ let bob_id = me_id(&app, &bob).await;
1700+
1701+ let course_id = create_course(&app, &teacher, "algebra").await;
1702+ enroll(&app, &teacher, &course_id, &alice_id).await;
1703+ enroll(&app, &teacher, &course_id, &bob_id).await;
1704+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;
1705+ let stats_uri = format!("/exams/{exam_id}/statistics");
1706+
1707+ // Nothing graded yet: zero count, null aggregates.
1708+ let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await;
1709+ assert_eq!(res.status, StatusCode::OK);
1710+ assert_eq!(res.body["graded"], 0);
1711+ assert_eq!(res.body["average"], serde_json::Value::Null);
1712+ assert_eq!(res.body["min"], serde_json::Value::Null);
1713+ assert_eq!(res.body["max"], serde_json::Value::Null);
1714+
1715+ for (id, mark) in [(&alice_id, 60), (&bob_id, 80)] {
1716+ send(
1717+ &app,
1718+ "POST",
1719+ &format!("/exams/{exam_id}/results"),
1720+ Some(&teacher),
1721+ Some(json!({ "mark": mark, "user_id": id })),
1722+ )
1723+ .await;
1724+ }
1725+
1726+ let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await;
1727+ assert_eq!(res.body["graded"], 2);
1728+ assert_eq!(res.body["average"], 70.0);
1729+ assert_eq!(res.body["min"], 60);
1730+ assert_eq!(res.body["max"], 80);
1731+
1732+ // Students don't see statistics; missing exam is a 404.
1733+ assert_eq!(
1734+ send(&app, "GET", &stats_uri, Some(&alice), None)
1735+ .await
1736+ .status,
1737+ StatusCode::FORBIDDEN
1738+ );
1739+}
1740+
1741+#[tokio::test]
1742+async fn weighted_averages_follow_exam_weights() {
1743+ let (app, db) = app_and_db().await;
1744+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1745+ let alice = login(&app, "alice").await;
1746+ let alice_id = me_id(&app, &alice).await;
1747+
1748+ // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80.
1749+ let algebra = create_course(&app, &teacher, "algebra").await;
1750+ enroll(&app, &teacher, &algebra, &alice_id).await;
1751+ let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz", 1).await;
1752+ let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm", 3).await;
1753+ // A third exam stays ungraded and must not drag the average.
1754+ create_exam(&app, &teacher, &algebra, "final", "final", 4).await;
1755+ for (exam, mark) in [(&quiz, 50), (&midterm, 90)] {
1756+ let res = send(
1757+ &app,
1758+ "POST",
1759+ &format!("/exams/{exam}/results"),
1760+ Some(&teacher),
1761+ Some(json!({ "mark": mark, "user_id": alice_id })),
1762+ )
1763+ .await;
1764+ assert_eq!(res.status, StatusCode::OK);
1765+ }
1766+
1767+ // Course B: enrolled, nothing graded -> null average.
1768+ let physics = create_course(&app, &teacher, "physics").await;
1769+ enroll(&app, &teacher, &physics, &alice_id).await;
1770+ create_exam(&app, &teacher, &physics, "hw", "homework", 1).await;
1771+
1772+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
1773+ assert_eq!(report.status, StatusCode::OK);
1774+ let courses = report.body["courses"].as_array().unwrap();
1775+ assert_eq!(courses.len(), 2);
1776+ let algebra_block = courses
1777+ .iter()
1778+ .find(|c| c["course"]["title"] == "algebra")
1779+ .unwrap();
1780+ let physics_block = courses
1781+ .iter()
1782+ .find(|c| c["course"]["title"] == "physics")
1783+ .unwrap();
1784+
1785+ assert_eq!(algebra_block["average"], 80.0);
1786+ assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2);
1787+ assert_eq!(physics_block["average"], serde_json::Value::Null);
1788+ assert_eq!(physics_block["results"].as_array().unwrap().len(), 0);
1789+ // Overall skips the null course instead of zeroing it.
1790+ assert_eq!(report.body["overall_average"], 80.0);
1791+ assert_eq!(report.body["user"], alice_id);
1792+}
1793+
1794+#[tokio::test]
1795+async fn marks_reports_are_self_or_teacher_scoped() {
1796+ let (app, db) = app_and_db().await;
1797+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1798+ let alice = login(&app, "alice").await;
1799+ let bob = login(&app, "bob").await;
1800+ let alice_id = me_id(&app, &alice).await;
1801+
1802+ // Own report works for a student.
1803+ assert_eq!(
1804+ send(&app, "GET", "/marks/me", Some(&alice), None)
1805+ .await
1806+ .status,
1807+ StatusCode::OK
1808+ );
1809+ // Another user's report needs teacher+.
1810+ assert_eq!(
1811+ send(&app, "GET", &format!("/marks/{alice_id}"), Some(&bob), None)
1812+ .await
1813+ .status,
1814+ StatusCode::FORBIDDEN
1815+ );
1816+ assert_eq!(
1817+ send(
1818+ &app,
1819+ "GET",
1820+ &format!("/marks/{alice_id}"),
1821+ Some(&teacher),
1822+ None
1823+ )
1824+ .await
1825+ .status,
1826+ StatusCode::OK
1827+ );
1828+}
1829+
1830+#[tokio::test]
1831+async fn deleting_course_cascades_enrollments_exams_and_results() {
1832+ let (app, db) = app_and_db().await;
1833+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1834+ let alice = login(&app, "alice").await;
1835+ let alice_id = me_id(&app, &alice).await;
1836+
1837+ let course_id = create_course(&app, &teacher, "algebra").await;
1838+ enroll(&app, &teacher, &course_id, &alice_id).await;
1839+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;
1090 send(1840 send(
1091 &app,1841 &app,
1092 "POST",1842 "POST",
1093 &format!("/exams/{exam_id}/results"),1843 &format!("/exams/{exam_id}/results"),
1094 Some(&teacher),1844 Some(&teacher),
1095- Some(json!({"mark":60,"user_id":alice_id})),1845+ Some(json!({ "mark": 70, "user_id": alice_id })),
1096 )1846 )
1097 .await;1847 .await;
1098 1848
@@ -1100,7 +1850,7 @@ async fn deleting_exam_cascades_results() {
1100 send(1850 send(
1101 &app,1851 &app,
1102 "DELETE",1852 "DELETE",
1103- &format!("/exams/{exam_id}"),1853+ &format!("/courses/{course_id}"),
1104 Some(&teacher),1854 Some(&teacher),
1105 None1855 None
1106 )1856 )
@@ -1108,7 +1858,20 @@ async fn deleting_exam_cascades_results() {
1108 .status,1858 .status,
1109 StatusCode::NO_CONTENT1859 StatusCode::NO_CONTENT
1110 );1860 );
1111- // Exam gone; the student's result is gone with it.1861+
1862+ // Course, exam, result, and enrollment are all gone.
1863+ assert_eq!(
1864+ send(
1865+ &app,
1866+ "GET",
1867+ &format!("/courses/{course_id}"),
1868+ Some(&teacher),
1869+ None
1870+ )
1871+ .await
1872+ .status,
1873+ StatusCode::NOT_FOUND
1874+ );
1112 assert_eq!(1875 assert_eq!(
1113 send(1876 send(
1114 &app,1877 &app,
@@ -1133,6 +1896,69 @@ async fn deleting_exam_cascades_results() {
1133 .status,1896 .status,
1134 StatusCode::NOT_FOUND1897 StatusCode::NOT_FOUND
1135 );1898 );
1899+ assert_eq!(
1900+ send(&app, "GET", "/courses/me", Some(&alice), None)
1901+ .await
1902+ .body
1903+ .as_array()
1904+ .unwrap()
1905+ .len(),
1906+ 0
1907+ );
1908+ assert_eq!(
1909+ send(&app, "GET", "/marks/me", Some(&alice), None)
1910+ .await
1911+ .body["courses"]
1912+ .as_array()
1913+ .unwrap()
1914+ .len(),
1915+ 0
1916+ );
1917+}
1918+
1919+/// Same guarantee as attendance/grading: concurrent enrolls of the same pair
1920+/// converge on one row instead of racing the unique index into a 500.
1921+#[tokio::test]
1922+async fn concurrent_enrollments_never_collide() {
1923+ let (app, db) = app_and_db().await;
1924+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1925+ let alice = login(&app, "alice").await;
1926+ let alice_id = me_id(&app, &alice).await;
1927+ let course_id = create_course(&app, &teacher, "algebra").await;
1928+
1929+ let mut handles = Vec::new();
1930+ for _ in 0..24 {
1931+ let app = app.clone();
1932+ let teacher = teacher.clone();
1933+ let uri = format!("/courses/{course_id}/enrollments");
1934+ let body = json!({ "user_id": alice_id });
1935+ handles.push(tokio::spawn(async move {
1936+ send(&app, "POST", &uri, Some(&teacher), Some(body))
1937+ .await
1938+ .status
1939+ }));
1940+ }
1941+ for h in handles {
1942+ assert_eq!(
1943+ h.await.unwrap(),
1944+ StatusCode::OK,
1945+ "concurrent enroll must not fail"
1946+ );
1947+ }
1948+
1949+ let roster = send(
1950+ &app,
1951+ "GET",
1952+ &format!("/courses/{course_id}/enrollments"),
1953+ Some(&teacher),
1954+ None,
1955+ )
1956+ .await;
1957+ assert_eq!(
1958+ roster.body.as_array().unwrap().len(),
1959+ 1,
1960+ "upsert keeps a single row"
1961+ );
1136 }1962 }
1137 1963
1138 // --- roles / RBAC --------------------------------------------------------1964 // --- roles / RBAC --------------------------------------------------------
@@ -1362,6 +2188,208 @@ async fn admin_manages_roles_with_guards() {
1362 );2188 );
1363 }2189 }
1364 2190
2191+// --- users: personal info (profile) ---------------------------------------
2192+
2193+#[tokio::test]
2194+async fn profile_starts_empty_and_updates_via_users_me() {
2195+ let app = mem_app().await;
2196+ let bob = login(&app, "bob").await;
2197+
2198+ // A fresh account carries no personal info.
2199+ let me = send(&app, "GET", "/auth/me", Some(&bob), None).await;
2200+ assert_eq!(me.status, StatusCode::OK);
2201+ for field in ["name", "surname", "email", "phone", "birth_date"] {
2202+ assert!(me.body[field].is_null(), "{field} should start null");
2203+ }
2204+
2205+ // Fill everything in via the self-service endpoint.
2206+ let res = send(
2207+ &app,
2208+ "PATCH",
2209+ "/users/me",
2210+ Some(&bob),
2211+ Some(json!({
2212+ "name": "Bob",
2213+ "surname": "Gümüş",
2214+ "email": "bob@example.com",
2215+ "phone": "+90 555 123 45 67",
2216+ "birth_date": "1990-1-2",
2217+ })),
2218+ )
2219+ .await;
2220+ assert_eq!(res.status, StatusCode::OK);
2221+ assert_eq!(res.body["name"], "Bob");
2222+ assert_eq!(res.body["surname"], "Gümüş"); // unicode names allowed
2223+ assert_eq!(res.body["email"], "bob@example.com");
2224+ assert_eq!(res.body["phone"], "+90 555 123 45 67");
2225+ assert_eq!(res.body["birth_date"], "1990-01-02"); // canonicalized
2226+ assert!(res.body.get("password_hash").is_none());
2227+
2228+ // Partial patch: only phone changes, everything else survives.
2229+ let res = send(
2230+ &app,
2231+ "PATCH",
2232+ "/users/me",
2233+ Some(&bob),
2234+ Some(json!({ "phone": "05551112233" })),
2235+ )
2236+ .await;
2237+ assert_eq!(res.status, StatusCode::OK);
2238+ assert_eq!(res.body["phone"], "05551112233");
2239+ assert_eq!(res.body["name"], "Bob");
2240+ assert_eq!(res.body["email"], "bob@example.com");
2241+
2242+ // Empty string clears a field; the others stay.
2243+ let res = send(
2244+ &app,
2245+ "PATCH",
2246+ "/users/me",
2247+ Some(&bob),
2248+ Some(json!({ "phone": "" })),
2249+ )
2250+ .await;
2251+ assert_eq!(res.status, StatusCode::OK);
2252+ assert!(res.body["phone"].is_null());
2253+ assert_eq!(res.body["name"], "Bob");
2254+
2255+ // The merged state is what /auth/me reports afterwards.
2256+ let me = send(&app, "GET", "/auth/me", Some(&bob), None).await;
2257+ assert_eq!(me.body["name"], "Bob");
2258+ assert_eq!(me.body["surname"], "Gümüş");
2259+ assert_eq!(me.body["birth_date"], "1990-01-02");
2260+ assert!(me.body["phone"].is_null());
2261+
2262+ // No session -> 401.
2263+ assert_eq!(
2264+ send(&app, "PATCH", "/users/me", None, Some(json!({"name":"x"})))
2265+ .await
2266+ .status,
2267+ StatusCode::UNAUTHORIZED
2268+ );
2269+}
2270+
2271+#[tokio::test]
2272+async fn profile_rejects_invalid_fields() {
2273+ let app = mem_app().await;
2274+ let bob = login(&app, "bob").await;
2275+
2276+ let bad = [
2277+ json!({ "email": "not-an-email" }),
2278+ json!({ "email": "bob@nodot" }),
2279+ json!({ "phone": "123" }),
2280+ json!({ "phone": "letters" }),
2281+ json!({ "birth_date": "02/01/1990" }),
2282+ json!({ "birth_date": "1990-02-30" }),
2283+ json!({ "birth_date": "9999-01-01" }),
2284+ json!({ "name": " " }),
2285+ json!({ "name": "x".repeat(101) }),
2286+ ];
2287+ for body in bad {
2288+ let res = send(&app, "PATCH", "/users/me", Some(&bob), Some(body.clone())).await;
2289+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}");
2290+ }
2291+
2292+ // A rejected patch must not have half-applied: profile is still empty.
2293+ let me = send(&app, "GET", "/auth/me", Some(&bob), None).await;
2294+ for field in ["name", "surname", "email", "phone", "birth_date"] {
2295+ assert!(me.body[field].is_null(), "{field} should still be null");
2296+ }
2297+}
2298+
2299+#[tokio::test]
2300+async fn admin_reads_and_edits_any_profile_with_guards() {
2301+ let (app, db) = app_and_db().await;
2302+ let admin = login_as(&app, &db, "admin", "admin").await;
2303+ let alice = login(&app, "alice").await;
2304+ let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
2305+ let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body);
2306+
2307+ // Students can neither look up nor edit someone else's record.
2308+ assert_eq!(
2309+ send(
2310+ &app,
2311+ "GET",
2312+ &format!("/users/{admin_id}"),
2313+ Some(&alice),
2314+ None
2315+ )
2316+ .await
2317+ .status,
2318+ StatusCode::FORBIDDEN
2319+ );
2320+ assert_eq!(
2321+ send(
2322+ &app,
2323+ "PATCH",
2324+ &format!("/users/{admin_id}/profile"),
2325+ Some(&alice),
2326+ Some(json!({"name":"Mallory"}))
2327+ )
2328+ .await
2329+ .status,
2330+ StatusCode::FORBIDDEN
2331+ );
2332+
2333+ // Admin maintains alice's record on her behalf.
2334+ let res = send(
2335+ &app,
2336+ "PATCH",
2337+ &format!("/users/{alice_id}/profile"),
2338+ Some(&admin),
2339+ Some(json!({ "name": "Alice", "email": "alice@school.edu" })),
2340+ )
2341+ .await;
2342+ assert_eq!(res.status, StatusCode::OK);
2343+ assert_eq!(res.body["name"], "Alice");
2344+
2345+ // Admin reads a single user; alice sees the change on /auth/me.
2346+ let one = send(
2347+ &app,
2348+ "GET",
2349+ &format!("/users/{alice_id}"),
2350+ Some(&admin),
2351+ None,
2352+ )
2353+ .await;
2354+ assert_eq!(one.status, StatusCode::OK);
2355+ assert_eq!(one.body["username"], "alice");
2356+ assert_eq!(one.body["email"], "alice@school.edu");
2357+ let me = send(&app, "GET", "/auth/me", Some(&alice), None).await;
2358+ assert_eq!(me.body["name"], "Alice");
2359+
2360+ // The admin listing now carries the info columns too.
2361+ let list = send(&app, "GET", "/users", Some(&admin), None).await;
2362+ let listed = list
2363+ .body
2364+ .as_array()
2365+ .unwrap()
2366+ .iter()
2367+ .find(|u| u["username"] == "alice")
2368+ .expect("alice listed")
2369+ .clone();
2370+ assert_eq!(listed["email"], "alice@school.edu");
2371+
2372+ // Unknown ids -> 404 on both admin endpoints.
2373+ assert_eq!(
2374+ send(&app, "GET", "/users/does-not-exist", Some(&admin), None)
2375+ .await
2376+ .status,
2377+ StatusCode::NOT_FOUND
2378+ );
2379+ assert_eq!(
2380+ send(
2381+ &app,
2382+ "PATCH",
2383+ "/users/does-not-exist/profile",
2384+ Some(&admin),
2385+ Some(json!({"name":"Nobody"}))
2386+ )
2387+ .await
2388+ .status,
2389+ StatusCode::NOT_FOUND
2390+ );
2391+}
2392+
1365 // --- regression: race safety, session hygiene, CORS ----------------------2393 // --- regression: race safety, session hygiene, CORS ----------------------
1366 2394
1367 /// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert2395 /// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert
@@ -1431,22 +2459,10 @@ async fn concurrent_exam_grades_never_collide() {
1431 let (app, db) = app_and_db().await;2459 let (app, db) = app_and_db().await;
1432 let teacher = login_as(&app, &db, "teacher", "teacher").await;2460 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1433 let student = login(&app, "student").await;2461 let student = login(&app, "student").await;
1434- let student_id = id_of(2462+ let student_id = me_id(&app, &student).await;
1435- &send(&app, "GET", "/auth/me", Some(&student), None)2463+ let course_id = create_course(&app, &teacher, "algebra").await;
1436- .await2464+ enroll(&app, &teacher, &course_id, &student_id).await;
1437- .body,2465+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await;
1438- );
1439- let exam_id = id_of(
1440- &send(
1441- &app,
1442- "POST",
1443- "/exams",
1444- Some(&teacher),
1445- Some(json!({ "title": "e", "kind": "quiz" })),
1446- )
1447- .await
1448- .body,
1449- );
1450 2466
1451 let mut handles = Vec::new();2467 let mut handles = Vec::new();
1452 for mark in 0..24i64 {2468 for mark in 0..24i64 {
@@ -1589,26 +2605,16 @@ async fn graders_cannot_grade_themselves() {
1589 let (app, db) = app_and_db().await;2605 let (app, db) = app_and_db().await;
1590 let teacher = login_as(&app, &db, "teacher", "teacher").await;2606 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1591 let boss = login_as(&app, &db, "boss", "manager").await;2607 let boss = login_as(&app, &db, "boss", "manager").await;
1592- let teacher_id = id_of(2608+ let teacher_id = me_id(&app, &teacher).await;
1593- &send(&app, "GET", "/auth/me", Some(&teacher), None)2609+ let boss_id = me_id(&app, &boss).await;
1594- .await
1595- .body,
1596- );
1597- let boss_id = id_of(&send(&app, "GET", "/auth/me", Some(&boss), None).await.body);
1598 2610
1599- let exam_id = id_of(2611+ let course_id = create_course(&app, &teacher, "algebra").await;
1600- &send(2612+ enroll(&app, &teacher, &course_id, &teacher_id).await;
1601- &app,2613+ enroll(&app, &teacher, &course_id, &boss_id).await;
1602- "POST",2614+ let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz", 1).await;
1603- "/exams",
1604- Some(&teacher),
1605- Some(json!({"title":"t","kind":"quiz"})),
1606- )
1607- .await
1608- .body,
1609- );
1610 2615
1611 // Self-grading is forbidden at every privilege level, not just for teachers.2616 // Self-grading is forbidden at every privilege level, not just for teachers.
2617+ // (The teacher owns the course; the manager clears the gate by role.)
1612 for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] {2618 for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] {
1613 let res = send(2619 let res = send(
1614 &app,2620 &app,
@@ -1725,6 +2731,36 @@ async fn child_lists_of_missing_parents_are_404() {
1725 .status,2731 .status,
1726 StatusCode::NOT_FOUND2732 StatusCode::NOT_FOUND
1727 );2733 );
2734+ assert_eq!(
2735+ send(
2736+ &app,
2737+ "GET",
2738+ "/courses/nope/enrollments",
2739+ Some(&teacher),
2740+ None
2741+ )
2742+ .await
2743+ .status,
2744+ StatusCode::NOT_FOUND
2745+ );
2746+ assert_eq!(
2747+ send(&app, "GET", "/courses/nope/exams", Some(&teacher), None)
2748+ .await
2749+ .status,
2750+ StatusCode::NOT_FOUND
2751+ );
2752+ assert_eq!(
2753+ send(&app, "GET", "/exams/nope/statistics", Some(&teacher), None)
2754+ .await
2755+ .status,
2756+ StatusCode::NOT_FOUND
2757+ );
2758+ assert_eq!(
2759+ send(&app, "GET", "/marks/ghost", Some(&teacher), None)
2760+ .await
2761+ .status,
2762+ StatusCode::NOT_FOUND
2763+ );
1728 }2764 }
1729 2765
1730 /// Regression: the session cookie never carried the `Secure` attribute, so a2766 /// Regression: the session cookie never carried the `Secure` attribute, so a
@@ -1893,3 +2929,69 @@ async fn cors_is_credential_safe_not_wildcard() {
1893 "true",2929 "true",
1894 );2930 );
1895 }2931 }
2932+
2933+// --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ----------------
2934+
2935+/// The seed creates a ready-to-use admin: login works with the configured
2936+/// credentials and the account can reach admin-only endpoints immediately.
2937+#[tokio::test]
2938+async fn admin_seed_creates_working_admin() {
2939+ let (app, db) = app_and_db().await;
2940+ let username = Username::try_new("root").unwrap();
2941+ let password = Password::try_new("secret1").unwrap();
2942+ User::ensure_admin(username, password, &db).await.unwrap();
2943+
2944+ let creds = json!({ "username": "root", "password": "secret1" });
2945+ let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
2946+ assert_eq!(res.status, StatusCode::OK);
2947+ assert_eq!(res.body["role"], "admin");
2948+
2949+ let cookie = res.cookie.expect("session cookie");
2950+ let res = send(&app, "GET", "/users", Some(&cookie), None).await;
2951+ assert_eq!(res.status, StatusCode::OK, "admin-only listing must open");
2952+}
2953+
2954+/// Re-running the seed (every boot does) must not duplicate the account,
2955+/// demote it, or overwrite its password.
2956+#[tokio::test]
2957+async fn admin_seed_is_idempotent() {
2958+ let (app, db) = app_and_db().await;
2959+ for _ in 0..2 {
2960+ let username = Username::try_new("root").unwrap();
2961+ let password = Password::try_new("secret1").unwrap();
2962+ User::ensure_admin(username, password, &db).await.unwrap();
2963+ }
2964+
2965+ let cookie = {
2966+ let creds = json!({ "username": "root", "password": "secret1" });
2967+ let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
2968+ assert_eq!(res.status, StatusCode::OK);
2969+ res.cookie.expect("session cookie")
2970+ };
2971+ let res = send(&app, "GET", "/users", Some(&cookie), None).await;
2972+ let listed = res.body.as_array().expect("user list");
2973+ assert_eq!(listed.len(), 1, "seed must not duplicate the account");
2974+ assert_eq!(listed[0]["role"], "admin");
2975+}
2976+
2977+/// A username already registered by someone else is never promoted (or its
2978+/// password replaced) by the seed — that would be privilege escalation.
2979+#[tokio::test]
2980+async fn admin_seed_refuses_existing_non_admin() {
2981+ let (app, db) = app_and_db().await;
2982+ let cookie = login(&app, "squatter").await; // registers with password `secret1`
2983+
2984+ let username = Username::try_new("squatter").unwrap();
2985+ let password = Password::try_new("attacker-pw").unwrap();
2986+ User::ensure_admin(username, password, &db).await.unwrap();
2987+
2988+ // Still a student: the admin-only listing stays closed...
2989+ let res = send(&app, "GET", "/users", Some(&cookie), None).await;
2990+ assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted");
2991+
2992+ // ...and the original password still logs in (nothing was overwritten).
2993+ let creds = json!({ "username": "squatter", "password": "secret1" });
2994+ let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
2995+ assert_eq!(res.status, StatusCode::OK);
2996+ assert_eq!(res.body["role"], "student");
2997+}
tests/persistence.rsmodified+155 -1
@@ -7,7 +7,7 @@ mod common;
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use axum::http::StatusCode;9 use axum::http::StatusCode;
10-use common::send;10+use common::{create_course, create_exam, enroll, me_id, send, set_role};
11 use hezarfen_backend::config::Config;11 use hezarfen_backend::config::Config;
12 use hezarfen_backend::database::Database;12 use hezarfen_backend::database::Database;
13 use hezarfen_backend::rate_limit::RateLimitConfig;13 use hezarfen_backend::rate_limit::RateLimitConfig;
@@ -38,6 +38,8 @@ fn config_at(dir: &TempDir) -> Config {
38 db_name: "hezarfen".into(),38 db_name: "hezarfen".into(),
39 cookie_secure: false,39 cookie_secure: false,
40 rate_limit: RateLimitConfig::unlimited(),40 rate_limit: RateLimitConfig::unlimited(),
41+ admin_username: None,
42+ admin_password: None,
41 }43 }
42 }44 }
43 45
@@ -145,3 +147,155 @@ async fn data_survives_reopen() {
145 assert_eq!(rows[0]["title"], "persisted");147 assert_eq!(rows[0]["title"], "persisted");
146 }148 }
147 }149 }
150+
151+/// Personal info written through `PATCH /users/me` is still on the account
152+/// after a close + reopen.
153+#[tokio::test]
154+async fn profile_survives_reopen() {
155+ let dir = tempfile::tempdir().unwrap();
156+ let cfg = config_at(&dir);
157+ let creds = json!({ "username": "ali", "password": "secret1" });
158+
159+ // First boot: register and fill in the profile.
160+ {
161+ let db = database::init(&cfg).await.expect("first open");
162+ let app = build_router(state(db));
163+ assert_eq!(
164+ send(&app, "POST", "/auth/register", None, Some(creds.clone()))
165+ .await
166+ .status,
167+ StatusCode::CREATED
168+ );
169+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
170+ .await
171+ .cookie
172+ .unwrap();
173+ let res = send(
174+ &app,
175+ "PATCH",
176+ "/users/me",
177+ Some(&cookie),
178+ Some(json!({
179+ "name": "Ali",
180+ "surname": "Gümüş",
181+ "email": "ali@example.com",
182+ "phone": "+90 555 123 45 67",
183+ "birth_date": "1990-01-02",
184+ })),
185+ )
186+ .await;
187+ assert_eq!(res.status, StatusCode::OK);
188+ }
189+
190+ // Second boot: the info comes back from disk.
191+ {
192+ let db = reopen(&cfg).await;
193+ let app = build_router(state(db));
194+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
195+ .await
196+ .cookie
197+ .unwrap();
198+ let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await;
199+ assert_eq!(me.status, StatusCode::OK);
200+ assert_eq!(me.body["name"], "Ali");
201+ assert_eq!(me.body["surname"], "Gümüş");
202+ assert_eq!(me.body["email"], "ali@example.com");
203+ assert_eq!(me.body["phone"], "+90 555 123 45 67");
204+ assert_eq!(me.body["birth_date"], "1990-01-02");
205+ }
206+}
207+
208+/// A course with an enrollment, a weighted exam, and a graded mark survives a
209+/// close + reopen — the weighted report is rebuilt from disk.
210+#[tokio::test]
211+async fn course_marks_survive_reopen() {
212+ let dir = tempfile::tempdir().unwrap();
213+ let cfg = config_at(&dir);
214+ let teacher_creds = json!({ "username": "hoca", "password": "secret1" });
215+ let student_creds = json!({ "username": "ali", "password": "secret1" });
216+
217+ // First boot: teacher sets up a course, enrolls the student, grades 80.
218+ {
219+ let db = database::init(&cfg).await.expect("first open");
220+ let app = build_router(state(db.clone()));
221+ for creds in [&teacher_creds, &student_creds] {
222+ assert_eq!(
223+ send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
224+ .await
225+ .status,
226+ StatusCode::CREATED
227+ );
228+ }
229+ set_role(&db, "hoca", "teacher").await;
230+ let teacher = send(
231+ &app,
232+ "POST",
233+ "/auth/login",
234+ None,
235+ Some(teacher_creds.clone()),
236+ )
237+ .await
238+ .cookie
239+ .unwrap();
240+ let student = send(
241+ &app,
242+ "POST",
243+ "/auth/login",
244+ None,
245+ Some(student_creds.clone()),
246+ )
247+ .await
248+ .cookie
249+ .unwrap();
250+ let student_id = me_id(&app, &student).await;
251+
252+ let course_id = create_course(&app, &teacher, "algebra").await;
253+ enroll(&app, &teacher, &course_id, &student_id).await;
254+ let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm", 2).await;
255+ assert_eq!(
256+ send(
257+ &app,
258+ "POST",
259+ &format!("/exams/{exam_id}/results"),
260+ Some(&teacher),
261+ Some(json!({ "mark": 80, "user_id": student_id }))
262+ )
263+ .await
264+ .status,
265+ StatusCode::OK
266+ );
267+ }
268+
269+ // Second boot: the report, roster, and exam weight are all rebuilt from disk.
270+ {
271+ let db = reopen(&cfg).await;
272+ let app = build_router(state(db));
273+ let student = send(&app, "POST", "/auth/login", None, Some(student_creds))
274+ .await
275+ .cookie
276+ .unwrap();
277+ let report = send(&app, "GET", "/marks/me", Some(&student), None).await;
278+ assert_eq!(report.status, StatusCode::OK);
279+ let course = &report.body["courses"][0];
280+ assert_eq!(course["course"]["title"], "algebra");
281+ assert_eq!(course["average"], 80.0);
282+ assert_eq!(course["results"][0]["weight"], 2);
283+ assert_eq!(course["results"][0]["mark"], 80);
284+ assert_eq!(report.body["overall_average"], 80.0);
285+
286+ let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds))
287+ .await
288+ .cookie
289+ .unwrap();
290+ let course_id = course["course"]["id"].as_str().unwrap();
291+ let roster = send(
292+ &app,
293+ "GET",
294+ &format!("/courses/{course_id}/enrollments"),
295+ Some(&teacher),
296+ None,
297+ )
298+ .await;
299+ assert_eq!(roster.body.as_array().unwrap().len(), 1, "roster intact");
300+ }
301+}