Skip to main content

auth0_integration/services/
auth0_client.rs

1use crate::config::Auth0Config;
2use crate::error::AppError;
3use crate::models::{Auth0User, CreateUserRequest, UpdateUserRequest};
4use crate::services::HttpClient;
5
6pub struct Auth0Client {
7    http: HttpClient,
8    token: String,
9}
10
11impl Auth0Client {
12    pub fn new(config: &Auth0Config, token: String) -> Self {
13        Self {
14            http: HttpClient::new(config),
15            token,
16        }
17    }
18
19    pub async fn get_user_by_email(&self, email: &str) -> Result<Vec<Auth0User>, AppError> {
20        let path = format!("/api/v2/users-by-email?email={}", email);
21        let res = self.http.get_authorized(&path, &self.token).await?;
22
23        if !res.status().is_success() {
24            let text = res.text().await.unwrap_or_default();
25            return Err(AppError::Auth0(text));
26        }
27
28        Ok(res.json::<Vec<Auth0User>>().await?)
29    }
30
31    pub async fn get_or_create_user(&self, name: &str, email: &str) -> Result<Auth0User, AppError> {
32        let body = CreateUserRequest::new("Username-Password-Authentication", email, name);
33
34        let res = self
35            .http
36            .post_authorized("/api/v2/users", &body, &self.token)
37            .await?;
38
39        if res.status().is_success() {
40            return Ok(res.json::<Auth0User>().await?);
41        }
42
43        // Creation failed (e.g. user already exists) — fall back to lookup
44        let users = self.get_user_by_email(email).await?;
45        users.into_iter().next().ok_or_else(|| AppError::Auth0(format!("User not found: {email}")))
46    }
47
48    pub async fn update_user(&self, user_id: &str, req: UpdateUserRequest) -> Result<Auth0User, AppError> {
49        let path = format!("/api/v2/users/{}", user_id);
50        let res = self
51            .http
52            .patch_authorized(&path, &req, &self.token)
53            .await?;
54
55        if !res.status().is_success() {
56            let text = res.text().await.unwrap_or_default();
57            return Err(AppError::Auth0(text));
58        }
59
60        Ok(res.json::<Auth0User>().await?)
61    }
62}