headless_lms_server/controllers/
other_domain_redirects.rs

1/*!
2Handlers for HTTP requests to `/api/v0/other-domain-redirects`.
3*/
4
5use actix_web::http::header;
6
7use crate::{domain::authorization::skip_authorize, prelude::*};
8/**
9GET `/api/v0/other-domain-redirects/.*` Redirects a domain that is not a main domain to the correct course.
10
11For example <https://example-course.mooc.fi> could redirect one to <https://courses.mooc.fi/org/uh-cs/courses/example-course>.
12Paths after the domain are supported, too. For example, <https://example-course.mooc.fi/a/b> would redirect one to <https://courses.mooc.fi/org/uh-cs/courses/example-course/a/b>.
13The request url is rewritten by the other domain ingress so that right requests end up here.
14**/
15pub async fn redirect_other_domain(
16    pool: web::Data<PgPool>,
17    req: HttpRequest,
18    params: web::Path<String>,
19    app_conf: web::Data<ApplicationConfiguration>,
20) -> ControllerResult<HttpResponse> {
21    let path = params.into_inner();
22    if let Some(host) = req.headers().get(header::HOST) {
23        let domain = host.to_str().map_err(|e| {
24            ControllerError::new(
25                ControllerErrorType::BadRequest,
26                "HOST is not a valid string".to_string(),
27                Some(e.into()),
28            )
29        })?;
30
31        let mut conn = pool.acquire().await?;
32        let redirection =
33            models::other_domain_to_course_redirections::get_by_domain(&mut conn, domain).await?;
34        let course = models::courses::get_course(&mut conn, redirection.course_id).await?;
35        let organization =
36            models::organizations::get_organization(&mut conn, course.organization_id).await?;
37        let token = skip_authorize();
38        return token.authorized_ok(
39            HttpResponse::TemporaryRedirect()
40                .insert_header((
41                    header::LOCATION,
42                    format!(
43                        "{}/org/{}/courses/{}/{}",
44                        app_conf.base_url, organization.slug, course.slug, path
45                    ),
46                ))
47                .finish(),
48        );
49    }
50
51    Err(ControllerError::new(
52        ControllerErrorType::BadRequest,
53        "No HOST header provided. Don't know where the request is supposed to be directed."
54            .to_string(),
55        None,
56    ))
57}
58pub fn _add_routes(cfg: &mut ServiceConfig) {
59    cfg.route("{url_path:.*}", web::get().to(redirect_other_domain));
60}