headless_lms_server/controllers/tmc_server/
users_by_upstream_id.rs

1/*!
2Handlers for HTTP requests to `/api/v0/tmc-server/users-by-upstream-id`.
3
4These endpoints are used by the TMC server so that it can integrate with this system.
5*/
6
7use crate::{
8    domain::authorization::{
9        authorize_access_from_tmc_server_to_course_mooc_fi,
10        get_or_create_user_from_tmc_mooc_fi_response,
11    },
12    prelude::*,
13};
14use headless_lms_utils::tmc::TmcClient;
15use models::users::User;
16
17/**
18GET `/api/v0/tmc-server/users-by-upstream-id/:id` Endpoint that TMC server uses to get user information by using its own ids.
19
20Only works if the authorization header is set to a secret value.
21*/
22#[instrument(skip(pool))]
23pub async fn get_user_by_upstream_id(
24    upstream_id: web::Path<i32>,
25    pool: web::Data<PgPool>,
26    request: HttpRequest,
27    tmc_client: web::Data<TmcClient>,
28) -> ControllerResult<web::Json<User>> {
29    let mut conn = pool.acquire().await?;
30    let token = authorize_access_from_tmc_server_to_course_mooc_fi(&request).await?;
31    let tmc_user = tmc_client
32        .get_user_from_tmc_mooc_fi_by_tmc_access_token_and_upstream_id(&upstream_id)
33        .await?;
34
35    debug!(
36        "Creating or fetching user with TMC id {} and mooc.fi UUID {}",
37        tmc_user.id,
38        tmc_user
39            .courses_mooc_fi_user_id
40            .map(|uuid| uuid.to_string())
41            .unwrap_or_else(|| "None (will generate new UUID)".to_string())
42    );
43    let user = get_or_create_user_from_tmc_mooc_fi_response(&mut conn, tmc_user).await?;
44    info!(
45        "Successfully got user details from mooc.fi for user {}",
46        user.id
47    );
48
49    token.authorized_ok(web::Json(user))
50}
51
52pub fn _add_routes(cfg: &mut ServiceConfig) {
53    cfg.route("/{user_id}", web::get().to(get_user_by_upstream_id));
54}