| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use axum::Json; |
| 18 | use axum::extract::{Path, Query, Request, State}; |
| 19 | use axum::http::StatusCode; |
| 20 | use axum::middleware::{self, Next}; |
| 21 | use axum_extra::extract::CookieJar; |
| 22 | use axum_extra::extract::cookie::Cookie; |
| 23 | use serde::{Deserialize, Serialize}; |
| 24 | use utoipa::ToSchema; |
| 25 | use utoipa_axum::router::OpenApiRouter; |
| 26 | use utoipa_axum::routes; |
| 27 | |
| 28 | use crate::constant::MAX_SCHOOL_NAME_LEN; |
| 29 | use crate::domain::builder::Builder; |
| 30 | use crate::domain::role::Role; |
| 31 | use crate::domain::user::{Password, PasswordHash, User, Username}; |
| 32 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 33 | use crate::module::{Module, ModuleSet, Package}; |
| 34 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 35 | use crate::service; |
| 36 | use crate::state::AppState; |
| 37 | use crate::tenant::{School, SchoolStatus, Slug}; |
| 38 | use crate::validate::validate_required; |
| 39 | use crate::web::tenant_state::school_files_path; |
| 40 | |
| 41 | use super::auth::session_cookie; |
| 42 | use super::modules::ModulesResponse; |
| 43 | use super::{BUILDER_COOKIE_PREFIX, Page, PageParams, RequireBuilder, UserResponse}; |
| 44 | |
| 45 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 46 | |
| 47 | |
| 48 | |
| 49 | let rate_limit: &RateLimitConfig = &state.rate_limit; |
| 50 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 51 | limiter.share("builder", state.db.clone(), state.db_up.clone()); |
| 52 | OpenApiRouter::new() |
| 53 | .routes(routes!(builder_login)) |
| 54 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { |
| 55 | let limiter = limiter.clone(); |
| 56 | async move { limiter.enforce(req, next).await } |
| 57 | })) |
| 58 | .routes(routes!(builder_logout)) |
| 59 | .routes(routes!(builder_me)) |
| 60 | .routes(routes!(create_school, list_schools)) |
| 61 | .routes(routes!(get_school, update_school, delete_school)) |
| 62 | .routes(routes!(list_school_modules, patch_school_modules)) |
| 63 | .routes(routes!(enable_school_module, disable_school_module)) |
| 64 | .routes(routes!(reset_admin_password)) |
| 65 | .routes(routes!(enter_school)) |
| 66 | } |
| 67 | |
| 68 | #[derive(Deserialize, ToSchema)] |
| 69 | struct BuilderCredentials { |
| 70 | #[schema(example = "operator", min_length = 3, max_length = 32)] |
| 71 | username: String, |
| 72 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 73 | password: String, |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | #[derive(Serialize, ToSchema)] |
| 79 | struct BuilderResponse { |
| 80 | id: String, |
| 81 | #[schema(example = "operator")] |
| 82 | username: String, |
| 83 | } |
| 84 | |
| 85 | impl BuilderResponse { |
| 86 | fn new(builder: &Builder) -> Self { |
| 87 | Self { |
| 88 | id: builder.get_id().key().to_string(), |
| 89 | username: builder.get_username().as_str().to_string(), |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | #[derive(Serialize, ToSchema)] |
| 95 | struct SchoolResponse { |
| 96 | #[schema(example = "ata-koleji")] |
| 97 | slug: String, |
| 98 | #[schema(example = "Ata Koleji")] |
| 99 | name: String, |
| 100 | |
| 101 | |
| 102 | #[schema(example = "active")] |
| 103 | status: String, |
| 104 | |
| 105 | created_at: i64, |
| 106 | |
| 107 | |
| 108 | #[schema(example = json!(["courses", "meals", "notes"]))] |
| 109 | modules: Vec<String>, |
| 110 | } |
| 111 | |
| 112 | impl SchoolResponse { |
| 113 | fn new(school: &School) -> Self { |
| 114 | Self { |
| 115 | slug: school.slug().as_str().to_string(), |
| 116 | name: school.name().to_string(), |
| 117 | status: school.status().as_str().to_string(), |
| 118 | created_at: school.created_at().as_millis(), |
| 119 | modules: school.modules().names(), |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | #[derive(Deserialize, ToSchema)] |
| 125 | struct CreateSchool { |
| 126 | |
| 127 | |
| 128 | |
| 129 | #[schema(example = "ata-koleji", min_length = 2, max_length = 32)] |
| 130 | slug: String, |
| 131 | #[schema(example = "Ata Koleji", max_length = 120)] |
| 132 | name: String, |
| 133 | |
| 134 | #[schema(example = "admin", min_length = 3, max_length = 32)] |
| 135 | admin_username: String, |
| 136 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 137 | admin_password: String, |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | #[schema(example = json!(["courses", "subjects", "exams"]))] |
| 143 | modules: Option<Vec<String>>, |
| 144 | } |
| 145 | |
| 146 | #[derive(Deserialize, ToSchema)] |
| 147 | struct UpdateSchool { |
| 148 | #[schema(example = "Ata Koleji", max_length = 120)] |
| 149 | name: Option<String>, |
| 150 | |
| 151 | #[schema(example = "suspended")] |
| 152 | status: Option<String>, |
| 153 | } |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | #[derive(Deserialize, ToSchema)] |
| 159 | struct PatchModules { |
| 160 | |
| 161 | #[schema(example = json!(["exams", "subjects"]))] |
| 162 | enable: Option<Vec<String>>, |
| 163 | |
| 164 | #[schema(example = json!(["payments"]))] |
| 165 | disable: Option<Vec<String>>, |
| 166 | |
| 167 | #[schema(example = json!(["academics"]))] |
| 168 | enable_packages: Option<Vec<String>>, |
| 169 | |
| 170 | #[schema(example = json!(["ai"]))] |
| 171 | disable_packages: Option<Vec<String>>, |
| 172 | } |
| 173 | |
| 174 | impl PatchModules { |
| 175 | |
| 176 | |
| 177 | |
| 178 | fn side( |
| 179 | &self, |
| 180 | modules: Option<&[String]>, |
| 181 | packages: Option<&[String]>, |
| 182 | ) -> Result<ModuleSet, AppError> { |
| 183 | let mut set = ModuleSet::from_names(modules.unwrap_or_default())?; |
| 184 | for name in packages.unwrap_or_default() { |
| 185 | for module in Package::try_from_str(name)?.modules() { |
| 186 | set.insert(module); |
| 187 | } |
| 188 | } |
| 189 | Ok(set) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[derive(Deserialize, ToSchema)] |
| 194 | struct AdminPassword { |
| 195 | |
| 196 | #[schema(example = "admin", min_length = 3, max_length = 32)] |
| 197 | username: String, |
| 198 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 199 | password: String, |
| 200 | } |
| 201 | |
| 202 | #[derive(Deserialize, ToSchema)] |
| 203 | struct EnterSchool { |
| 204 | |
| 205 | #[schema(example = "admin", min_length = 3, max_length = 32)] |
| 206 | username: String, |
| 207 | } |
| 208 | |
| 209 | |
| 210 | fn school_name(value: &str) -> Result<String, AppError> { |
| 211 | validate_required("name", value, MAX_SCHOOL_NAME_LEN)?; |
| 212 | Ok(value.trim().to_string()) |
| 213 | } |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | fn path_slug(raw: &str) -> Result<Slug, AppError> { |
| 220 | Slug::try_new(raw).map_err(|_| AppError::NotFound) |
| 221 | } |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | async fn school_admin(username: &str, db: &crate::database::Database) -> Result<User, AppError> { |
| 228 | let user = crate::service::user::find_by_username(db, username.trim()) |
| 229 | .await? |
| 230 | .ok_or(AppError::NotFound)?; |
| 231 | if user.get_role() != Role::Admin { |
| 232 | return Err(AppError::Conflict( |
| 233 | "that account is not an admin of this school", |
| 234 | )); |
| 235 | } |
| 236 | Ok(user) |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | #[utoipa::path( |
| 242 | post, |
| 243 | path = "/builder/login", |
| 244 | tag = "builder", |
| 245 | request_body = BuilderCredentials, |
| 246 | responses( |
| 247 | (status = 200, description = "Logged in; builder session cookie set", body = BuilderResponse), |
| 248 | (status = 401, description = "Bad credentials", body = ErrorResponse), |
| 249 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 250 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 251 | ), |
| 252 | )] |
| 253 | async fn builder_login( |
| 254 | State(st): State<AppState>, |
| 255 | jar: CookieJar, |
| 256 | Json(req): Json<BuilderCredentials>, |
| 257 | ) -> Result<(CookieJar, Json<BuilderResponse>), AppError> { |
| 258 | let control = st.tenants.control(); |
| 259 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 260 | let builder = |
| 261 | match crate::service::builder::find_by_username(control, req.username.trim()).await? { |
| 262 | Some(builder) => { |
| 263 | if !builder.get_password_hash().verify_async(&password).await { |
| 264 | return Err(AppError::Unauthorized); |
| 265 | } |
| 266 | builder |
| 267 | } |
| 268 | None => { |
| 269 | |
| 270 | |
| 271 | |
| 272 | PasswordHash::verify_decoy_async(&password).await; |
| 273 | return Err(AppError::Unauthorized); |
| 274 | } |
| 275 | }; |
| 276 | |
| 277 | let session = crate::service::builder::create_session(control, builder.get_id()).await?; |
| 278 | let cookie = session_cookie( |
| 279 | format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()), |
| 280 | st.cookie_secure, |
| 281 | ); |
| 282 | Ok((jar.add(cookie), Json(BuilderResponse::new(&builder)))) |
| 283 | } |
| 284 | |
| 285 | |
| 286 | |
| 287 | #[utoipa::path( |
| 288 | post, |
| 289 | path = "/builder/logout", |
| 290 | tag = "builder", |
| 291 | responses((status = 204, description = "Logged out (no-op without a builder session)")), |
| 292 | )] |
| 293 | async fn builder_logout( |
| 294 | State(st): State<AppState>, |
| 295 | jar: CookieJar, |
| 296 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 297 | if let Some((BUILDER_COOKIE_PREFIX, token)) = jar |
| 298 | .get("session") |
| 299 | .and_then(|cookie| super::tenant_state::split_cookie(cookie.value())) |
| 300 | { |
| 301 | crate::service::builder::delete_by_token(st.tenants.control(), token).await?; |
| 302 | } |
| 303 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 304 | Ok((jar, StatusCode::NO_CONTENT)) |
| 305 | } |
| 306 | |
| 307 | |
| 308 | #[utoipa::path( |
| 309 | get, |
| 310 | path = "/builder/me", |
| 311 | tag = "builder", |
| 312 | security(("session_cookie" = [])), |
| 313 | responses( |
| 314 | (status = 200, description = "The current builder", body = BuilderResponse), |
| 315 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 316 | ), |
| 317 | )] |
| 318 | async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json<BuilderResponse> { |
| 319 | Json(BuilderResponse::new(&builder)) |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | #[utoipa::path( |
| 325 | post, |
| 326 | path = "/schools", |
| 327 | tag = "builder", |
| 328 | security(("session_cookie" = [])), |
| 329 | request_body = CreateSchool, |
| 330 | responses( |
| 331 | (status = 201, description = "School created, with its first admin", body = SchoolResponse), |
| 332 | (status = 400, description = "Invalid slug, name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})), |
| 333 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 334 | (status = 409, description = "That slug is already taken, or the module set is unsatisfiable", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})), |
| 335 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 336 | ), |
| 337 | )] |
| 338 | async fn create_school( |
| 339 | State(st): State<AppState>, |
| 340 | RequireBuilder(_builder): RequireBuilder, |
| 341 | Json(req): Json<CreateSchool>, |
| 342 | ) -> Result<(StatusCode, Json<SchoolResponse>), AppError> { |
| 343 | |
| 344 | |
| 345 | |
| 346 | let slug = Slug::try_new(&req.slug)?; |
| 347 | let name = school_name(&req.name)?; |
| 348 | let username = Username::try_new(&req.admin_username)?; |
| 349 | let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; |
| 350 | |
| 351 | let modules = match req.modules.as_deref() { |
| 352 | Some(names) => ModuleSet::from_names(names)?, |
| 353 | None => ModuleSet::all(), |
| 354 | }; |
| 355 | |
| 356 | |
| 357 | modules.validate()?; |
| 358 | |
| 359 | let db = st.tenants.create(&slug, &name, modules).await?; |
| 360 | if let Err(err) = |
| 361 | crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await |
| 362 | { |
| 363 | |
| 364 | |
| 365 | if let Err(cleanup) = st.tenants.drop(&slug).await { |
| 366 | tracing::error!("failed to drop {slug} after its admin seed failed: {cleanup}"); |
| 367 | } |
| 368 | return Err(err); |
| 369 | } |
| 370 | |
| 371 | let school = School::read(&slug, st.tenants.control()) |
| 372 | .await? |
| 373 | .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?; |
| 374 | Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school)))) |
| 375 | } |
| 376 | |
| 377 | |
| 378 | |
| 379 | #[utoipa::path( |
| 380 | get, |
| 381 | path = "/schools", |
| 382 | tag = "builder", |
| 383 | security(("session_cookie" = [])), |
| 384 | params(PageParams), |
| 385 | responses( |
| 386 | (status = 200, description = "A page of schools (the full list when unpaged)", body = Page<SchoolResponse>), |
| 387 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 388 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 389 | ), |
| 390 | )] |
| 391 | async fn list_schools( |
| 392 | State(st): State<AppState>, |
| 393 | RequireBuilder(_builder): RequireBuilder, |
| 394 | Query(page): Query<PageParams>, |
| 395 | ) -> Result<Json<Page<SchoolResponse>>, AppError> { |
| 396 | let (limit, offset) = page.resolve()?; |
| 397 | let (schools, total) = School::list(limit, offset, st.tenants.control()).await?; |
| 398 | let items = schools.iter().map(SchoolResponse::new).collect(); |
| 399 | Ok(Json(Page::new(items, total, limit, offset))) |
| 400 | } |
| 401 | |
| 402 | |
| 403 | #[utoipa::path( |
| 404 | get, |
| 405 | path = "/schools/{slug}", |
| 406 | tag = "builder", |
| 407 | security(("session_cookie" = [])), |
| 408 | params(("slug" = String, Path, description = "School slug")), |
| 409 | responses( |
| 410 | (status = 200, description = "The school", body = SchoolResponse), |
| 411 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 412 | (status = 404, description = "No such school", body = ErrorResponse), |
| 413 | ), |
| 414 | )] |
| 415 | async fn get_school( |
| 416 | State(st): State<AppState>, |
| 417 | RequireBuilder(_builder): RequireBuilder, |
| 418 | Path(slug): Path<String>, |
| 419 | ) -> Result<Json<SchoolResponse>, AppError> { |
| 420 | let school = School::read(&path_slug(&slug)?, st.tenants.control()) |
| 421 | .await? |
| 422 | .ok_or(AppError::NotFound)?; |
| 423 | Ok(Json(SchoolResponse::new(&school))) |
| 424 | } |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | #[utoipa::path( |
| 433 | patch, |
| 434 | path = "/schools/{slug}", |
| 435 | tag = "builder", |
| 436 | security(("session_cookie" = [])), |
| 437 | params(("slug" = String, Path, description = "School slug")), |
| 438 | request_body = UpdateSchool, |
| 439 | responses( |
| 440 | (status = 200, description = "The updated school", body = SchoolResponse), |
| 441 | (status = 400, description = "Invalid name or status", body = ErrorResponse), |
| 442 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 443 | (status = 404, description = "No such school", body = ErrorResponse), |
| 444 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 445 | ), |
| 446 | )] |
| 447 | async fn update_school( |
| 448 | State(st): State<AppState>, |
| 449 | RequireBuilder(_builder): RequireBuilder, |
| 450 | Path(slug): Path<String>, |
| 451 | Json(req): Json<UpdateSchool>, |
| 452 | ) -> Result<Json<SchoolResponse>, AppError> { |
| 453 | let slug = path_slug(&slug)?; |
| 454 | let name = req.name.as_deref().map(school_name).transpose()?; |
| 455 | let status = req |
| 456 | .status |
| 457 | .as_deref() |
| 458 | .map(SchoolStatus::try_from_str) |
| 459 | .transpose()?; |
| 460 | |
| 461 | let control = st.tenants.control(); |
| 462 | |
| 463 | |
| 464 | School::read(&slug, control) |
| 465 | .await? |
| 466 | .ok_or(AppError::NotFound)?; |
| 467 | if let Some(name) = name { |
| 468 | School::update_name(&slug, &name, control).await?; |
| 469 | } |
| 470 | if let Some(status) = status { |
| 471 | st.tenants.set_status(&slug, status).await?; |
| 472 | } |
| 473 | let school = School::read(&slug, control) |
| 474 | .await? |
| 475 | .ok_or(AppError::NotFound)?; |
| 476 | Ok(Json(SchoolResponse::new(&school))) |
| 477 | } |
| 478 | |
| 479 | |
| 480 | |
| 481 | #[utoipa::path( |
| 482 | delete, |
| 483 | path = "/schools/{slug}", |
| 484 | tag = "builder", |
| 485 | security(("session_cookie" = [])), |
| 486 | params(("slug" = String, Path, description = "School slug")), |
| 487 | responses( |
| 488 | (status = 204, description = "Deleted"), |
| 489 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 490 | (status = 404, description = "No such school", body = ErrorResponse), |
| 491 | ), |
| 492 | )] |
| 493 | async fn delete_school( |
| 494 | State(st): State<AppState>, |
| 495 | RequireBuilder(_builder): RequireBuilder, |
| 496 | Path(slug): Path<String>, |
| 497 | ) -> Result<StatusCode, AppError> { |
| 498 | let slug = path_slug(&slug)?; |
| 499 | School::read(&slug, st.tenants.control()) |
| 500 | .await? |
| 501 | .ok_or(AppError::NotFound)?; |
| 502 | st.tenants.drop(&slug).await?; |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | let dir = school_files_path(&st.files_path, &slug); |
| 509 | if let Err(err) = tokio::fs::remove_dir_all(&dir).await |
| 510 | && err.kind() != std::io::ErrorKind::NotFound |
| 511 | { |
| 512 | tracing::warn!( |
| 513 | "failed to remove the files of {slug} at {}: {err}", |
| 514 | dir.display() |
| 515 | ); |
| 516 | } |
| 517 | Ok(StatusCode::NO_CONTENT) |
| 518 | } |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | fn path_module(raw: &str) -> Result<Module, AppError> { |
| 525 | Module::try_from_str(raw).map_err(|_| AppError::NotFound) |
| 526 | } |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | async fn school_modules( |
| 532 | slug: &Slug, |
| 533 | control: &crate::database::Database, |
| 534 | ) -> Result<ModuleSet, AppError> { |
| 535 | Ok(School::read(slug, control) |
| 536 | .await? |
| 537 | .ok_or(AppError::NotFound)? |
| 538 | .modules()) |
| 539 | } |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | fn refuse_if_needed(module: Module, set: &ModuleSet) -> Result<(), AppError> { |
| 545 | let needed_by: Vec<String> = module |
| 546 | .dependents() |
| 547 | .into_iter() |
| 548 | .filter(|dependent| set.contains(*dependent)) |
| 549 | .map(|dependent| dependent.as_str().to_string()) |
| 550 | .collect(); |
| 551 | if needed_by.is_empty() { |
| 552 | return Ok(()); |
| 553 | } |
| 554 | Err(AppError::ConflictOwned(format!( |
| 555 | "{module} is required by {}", |
| 556 | needed_by.join(", ") |
| 557 | ))) |
| 558 | } |
| 559 | |
| 560 | |
| 561 | |
| 562 | async fn store_modules( |
| 563 | st: &AppState, |
| 564 | slug: &Slug, |
| 565 | modules: ModuleSet, |
| 566 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 567 | st.tenants.set_modules(slug, &modules).await?; |
| 568 | Ok(Json(ModulesResponse::new(&modules))) |
| 569 | } |
| 570 | |
| 571 | |
| 572 | |
| 573 | #[utoipa::path( |
| 574 | get, |
| 575 | path = "/schools/{slug}/modules", |
| 576 | tag = "builder", |
| 577 | security(("session_cookie" = [])), |
| 578 | params(("slug" = String, Path, description = "School slug")), |
| 579 | responses( |
| 580 | (status = 200, description = "The school's enabled and disabled modules", body = ModulesResponse), |
| 581 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 582 | (status = 404, description = "No such school", body = ErrorResponse), |
| 583 | ), |
| 584 | )] |
| 585 | async fn list_school_modules( |
| 586 | State(st): State<AppState>, |
| 587 | RequireBuilder(_builder): RequireBuilder, |
| 588 | Path(slug): Path<String>, |
| 589 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 590 | let modules = school_modules(&path_slug(&slug)?, st.tenants.control()).await?; |
| 591 | Ok(Json(ModulesResponse::new(&modules))) |
| 592 | } |
| 593 | |
| 594 | |
| 595 | |
| 596 | |
| 597 | #[utoipa::path( |
| 598 | post, |
| 599 | path = "/schools/{slug}/modules/{module}", |
| 600 | tag = "builder", |
| 601 | security(("session_cookie" = [])), |
| 602 | params( |
| 603 | ("slug" = String, Path, description = "School slug"), |
| 604 | ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"), |
| 605 | ), |
| 606 | responses( |
| 607 | (status = 200, description = "The school's modules after the change", body = ModulesResponse), |
| 608 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 609 | (status = 404, description = "No such school, or no such module", body = ErrorResponse, example = json!({"error": "not found"})), |
| 610 | (status = 409, description = "That module needs another this school does not have", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})), |
| 611 | ), |
| 612 | )] |
| 613 | async fn enable_school_module( |
| 614 | State(st): State<AppState>, |
| 615 | RequireBuilder(_builder): RequireBuilder, |
| 616 | Path((slug, module)): Path<(String, String)>, |
| 617 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 618 | let slug = path_slug(&slug)?; |
| 619 | let module = path_module(&module)?; |
| 620 | let mut modules = school_modules(&slug, st.tenants.control()).await?; |
| 621 | if modules.contains(module) { |
| 622 | return Ok(Json(ModulesResponse::new(&modules))); |
| 623 | } |
| 624 | modules.insert(module); |
| 625 | modules.validate()?; |
| 626 | store_modules(&st, &slug, modules).await |
| 627 | } |
| 628 | |
| 629 | |
| 630 | |
| 631 | |
| 632 | |
| 633 | |
| 634 | #[utoipa::path( |
| 635 | delete, |
| 636 | path = "/schools/{slug}/modules/{module}", |
| 637 | tag = "builder", |
| 638 | security(("session_cookie" = [])), |
| 639 | params( |
| 640 | ("slug" = String, Path, description = "School slug"), |
| 641 | ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"), |
| 642 | ), |
| 643 | responses( |
| 644 | (status = 200, description = "The school's modules after the change", body = ModulesResponse), |
| 645 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 646 | (status = 404, description = "No such school, or no such module", body = ErrorResponse, example = json!({"error": "not found"})), |
| 647 | (status = 409, description = "Another module the school has requires this one", body = ErrorResponse, example = json!({"error": "conflict: courses is required by exams, subjects"})), |
| 648 | ), |
| 649 | )] |
| 650 | async fn disable_school_module( |
| 651 | State(st): State<AppState>, |
| 652 | RequireBuilder(_builder): RequireBuilder, |
| 653 | Path((slug, module)): Path<(String, String)>, |
| 654 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 655 | let slug = path_slug(&slug)?; |
| 656 | let module = path_module(&module)?; |
| 657 | let mut modules = school_modules(&slug, st.tenants.control()).await?; |
| 658 | if !modules.contains(module) { |
| 659 | return Ok(Json(ModulesResponse::new(&modules))); |
| 660 | } |
| 661 | refuse_if_needed(module, &modules)?; |
| 662 | modules.remove(module); |
| 663 | store_modules(&st, &slug, modules).await |
| 664 | } |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | #[utoipa::path( |
| 675 | patch, |
| 676 | path = "/schools/{slug}/modules", |
| 677 | tag = "builder", |
| 678 | security(("session_cookie" = [])), |
| 679 | params(("slug" = String, Path, description = "School slug")), |
| 680 | request_body = PatchModules, |
| 681 | responses( |
| 682 | (status = 200, description = "The school's modules after the change", body = ModulesResponse), |
| 683 | (status = 400, description = "An unknown module or package name, or one asked for in both directions", body = ErrorResponse, example = json!({"error": "package: `kantin` is not a known package"})), |
| 684 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 685 | (status = 404, description = "No such school", body = ErrorResponse), |
| 686 | (status = 409, description = "The resulting set breaks a dependency", body = ErrorResponse, example = json!({"error": "conflict: marks requires exams, which is not enabled"})), |
| 687 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 688 | ), |
| 689 | )] |
| 690 | async fn patch_school_modules( |
| 691 | State(st): State<AppState>, |
| 692 | RequireBuilder(_builder): RequireBuilder, |
| 693 | Path(slug): Path<String>, |
| 694 | Json(req): Json<PatchModules>, |
| 695 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 696 | let slug = path_slug(&slug)?; |
| 697 | let enable = req.side(req.enable.as_deref(), req.enable_packages.as_deref())?; |
| 698 | let disable = req.side(req.disable.as_deref(), req.disable_packages.as_deref())?; |
| 699 | |
| 700 | |
| 701 | |
| 702 | if let Some(module) = enable.iter().find(|module| disable.contains(*module)) { |
| 703 | return Err(ValidationError::Contradictory { |
| 704 | field: "module", |
| 705 | value: module.as_str().to_string(), |
| 706 | } |
| 707 | .into()); |
| 708 | } |
| 709 | |
| 710 | let current = school_modules(&slug, st.tenants.control()).await?; |
| 711 | let mut result = current.clone(); |
| 712 | for module in enable.iter() { |
| 713 | result.insert(module); |
| 714 | } |
| 715 | for module in disable.iter() { |
| 716 | result.remove(module); |
| 717 | } |
| 718 | |
| 719 | |
| 720 | result.validate()?; |
| 721 | |
| 722 | if result == current { |
| 723 | return Ok(Json(ModulesResponse::new(¤t))); |
| 724 | } |
| 725 | store_modules(&st, &slug, result).await |
| 726 | } |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | #[utoipa::path( |
| 732 | post, |
| 733 | path = "/schools/{slug}/admin-password", |
| 734 | tag = "builder", |
| 735 | security(("session_cookie" = [])), |
| 736 | params(("slug" = String, Path, description = "School slug")), |
| 737 | request_body = AdminPassword, |
| 738 | responses( |
| 739 | (status = 204, description = "Password reset; that account's sessions are revoked"), |
| 740 | (status = 400, description = "Invalid password", body = ErrorResponse), |
| 741 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 742 | (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), |
| 743 | (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), |
| 744 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 745 | ), |
| 746 | )] |
| 747 | async fn reset_admin_password( |
| 748 | State(st): State<AppState>, |
| 749 | RequireBuilder(_builder): RequireBuilder, |
| 750 | Path(slug): Path<String>, |
| 751 | Json(req): Json<AdminPassword>, |
| 752 | ) -> Result<StatusCode, AppError> { |
| 753 | let slug = path_slug(&slug)?; |
| 754 | |
| 755 | |
| 756 | let (db, _status) = st.tenants.get_any_status(&slug).await?; |
| 757 | let user = school_admin(&req.username, &db).await?; |
| 758 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 759 | |
| 760 | crate::service::user::set_password_hash(&db, user.get_id(), password_hash) |
| 761 | .await? |
| 762 | .ok_or(AppError::NotFound)?; |
| 763 | |
| 764 | |
| 765 | service::session::delete_by_user(&db, user.get_id()).await?; |
| 766 | Ok(StatusCode::NO_CONTENT) |
| 767 | } |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | #[utoipa::path( |
| 775 | post, |
| 776 | path = "/schools/{slug}/enter", |
| 777 | tag = "builder", |
| 778 | security(("session_cookie" = [])), |
| 779 | params(("slug" = String, Path, description = "School slug")), |
| 780 | request_body = EnterSchool, |
| 781 | responses( |
| 782 | (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse), |
| 783 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 784 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 785 | (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), |
| 786 | (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), |
| 787 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 788 | ), |
| 789 | )] |
| 790 | async fn enter_school( |
| 791 | State(st): State<AppState>, |
| 792 | RequireBuilder(_builder): RequireBuilder, |
| 793 | jar: CookieJar, |
| 794 | Path(slug): Path<String>, |
| 795 | Json(req): Json<EnterSchool>, |
| 796 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 797 | let slug = path_slug(&slug)?; |
| 798 | let (db, status) = st.tenants.get_any_status(&slug).await?; |
| 799 | if status == SchoolStatus::Suspended { |
| 800 | return Err(AppError::Forbidden("school is suspended")); |
| 801 | } |
| 802 | let user = school_admin(&req.username, &db).await?; |
| 803 | |
| 804 | let session = service::session::create(&db, user.get_id()).await?; |
| 805 | let cookie = session_cookie( |
| 806 | format!("{slug}.{}", session.token().as_str()), |
| 807 | st.cookie_secure, |
| 808 | ); |
| 809 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 810 | } |