hyprstream_core/services/oauth/
oauth2_userinfo.rs1use std::time::Duration;
7
8use anyhow::{anyhow, Context, Result};
9
10use crate::config::ClaimMapping;
11
12pub async fn fetch_oauth2_claims(
24 http_client: &reqwest::Client,
25 userinfo_endpoint: &str,
26 access_token: &str,
27 mapping: &ClaimMapping,
28) -> Result<serde_json::Value> {
29 let response = http_client
30 .get(userinfo_endpoint)
31 .header("Authorization", format!("Bearer {access_token}"))
32 .header("Accept", "application/json")
33 .header("User-Agent", "hyprstream")
34 .timeout(Duration::from_secs(10))
35 .send()
36 .await
37 .context("userinfo request failed")?;
38
39 if !response.status().is_success() {
40 let status = response.status();
41 let body = response.text().await.unwrap_or_default();
42 return Err(anyhow!("userinfo endpoint returned {status}: {body}"));
43 }
44
45 let raw: serde_json::Value = response
46 .json()
47 .await
48 .context("userinfo response is not valid JSON")?;
49
50 let sub = match &raw[&mapping.sub] {
52 serde_json::Value::String(s) => s.clone(),
53 serde_json::Value::Number(n) => n.to_string(),
54 other if other.is_null() => {
55 return Err(anyhow!("userinfo '{}' field is null", mapping.sub));
56 }
57 _ => {
58 return Err(anyhow!(
59 "userinfo '{}' field missing or wrong type",
60 mapping.sub
61 ))
62 }
63 };
64
65 let name = mapping
67 .name
68 .as_deref()
69 .map(|field| raw[field].clone())
70 .unwrap_or(serde_json::Value::Null);
71
72 let email = mapping
73 .email
74 .as_deref()
75 .map(|field| raw[field].clone())
76 .unwrap_or(serde_json::Value::Null);
77
78 let email_verified: bool = mapping
80 .email_verified
81 .as_deref()
82 .and_then(|field| {
83 let v = &raw[field];
84 match v {
85 serde_json::Value::Bool(b) => Some(*b),
86 serde_json::Value::String(s) => Some(s.eq_ignore_ascii_case("true")),
87 _ => None,
88 }
89 })
90 .unwrap_or(false);
91
92 Ok(serde_json::json!({
93 "sub": sub,
94 "name": name,
95 "email": email,
96 "email_verified": email_verified,
97 }))
98}