Skip to main content

various_rust_utils/auth/
get_user_email_from_token.rs

1use crate::api_clients::rest_client;
2use crate::api_clients::rest_client::RestApiCallType;
3use crate::auth::extract_user_id::extract_user_id;
4use anyhow::{bail, Error};
5use serde::{Deserialize, Serialize};
6
7pub async fn execute(
8    user_token: Option<String>,
9    auth_service_url: &str,
10    auth_path: &str,
11    service_token: &str,
12) -> Result<String, Error> {
13    match user_token {
14        Some(user_token) => {
15            let user_id: String = extract_user_id(user_token)?;
16            check_token_against_auth_service(user_id, auth_service_url, auth_path, service_token)
17                .await
18        }
19        None => bail!("Authorization header not provided!"),
20    }
21}
22
23#[derive(Serialize, Deserialize)]
24struct UserResponse {
25    pub username: String,
26}
27
28async fn check_token_against_auth_service(
29    user_id: String,
30    auth_service_url: &str,
31    auth_path: &str,
32    service_token: &str,
33) -> Result<String, Error> {
34    let result = rest_client::execute_request::<UserResponse, UserResponse>(
35        format!("{}{}{}", auth_service_url, auth_path, user_id),
36        RestApiCallType::Get,
37        Some(service_token.to_string()),
38        None,
39        vec![],
40    );
41    match result.await {
42        Ok(response) => Ok(response.username),
43        Err(_) => bail!("Invalid JWT token!"),
44    }
45}