1use serde::{Deserialize, Serialize};
2use url::Url;
3
4use crate::error::Error;
5use crate::pkce;
6use crate::types::{Ppnum, PpnumId};
7
8const DEFAULT_AUTH_URL: &str = "https://accounts.ppoppo.com/oauth/authorize";
9const DEFAULT_TOKEN_URL: &str = "https://accounts.ppoppo.com/oauth/token";
10const DEFAULT_USERINFO_URL: &str = "https://accounts.ppoppo.com/oauth/userinfo";
11
12#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct OAuthConfig {
27 pub(crate) client_id: String,
28 pub(crate) auth_url: Url,
29 pub(crate) token_url: Url,
30 pub(crate) userinfo_url: Url,
31 pub(crate) redirect_uri: Url,
32 pub(crate) scopes: Vec<String>,
33}
34
35impl OAuthConfig {
36 #[must_use]
40 #[allow(clippy::expect_used)] pub fn new(client_id: impl Into<String>, redirect_uri: Url) -> Self {
42 Self {
43 client_id: client_id.into(),
44 redirect_uri,
45 auth_url: DEFAULT_AUTH_URL.parse().expect("valid default URL"),
46 token_url: DEFAULT_TOKEN_URL.parse().expect("valid default URL"),
47 userinfo_url: DEFAULT_USERINFO_URL.parse().expect("valid default URL"),
48 scopes: vec!["profile".into()],
49 }
50 }
51
52 #[must_use]
54 pub fn with_auth_url(mut self, url: Url) -> Self {
55 self.auth_url = url;
56 self
57 }
58
59 #[must_use]
61 pub fn with_token_url(mut self, url: Url) -> Self {
62 self.token_url = url;
63 self
64 }
65
66 #[must_use]
68 pub fn with_userinfo_url(mut self, url: Url) -> Self {
69 self.userinfo_url = url;
70 self
71 }
72
73 #[must_use]
75 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
76 self.scopes = scopes;
77 self
78 }
79
80 #[must_use]
82 pub fn client_id(&self) -> &str {
83 &self.client_id
84 }
85
86 #[must_use]
88 pub fn auth_url(&self) -> &Url {
89 &self.auth_url
90 }
91
92 #[must_use]
94 pub fn token_url(&self) -> &Url {
95 &self.token_url
96 }
97
98 #[must_use]
100 pub fn userinfo_url(&self) -> &Url {
101 &self.userinfo_url
102 }
103
104 #[must_use]
106 pub fn redirect_uri(&self) -> &Url {
107 &self.redirect_uri
108 }
109
110 #[must_use]
112 pub fn scopes(&self) -> &[String] {
113 &self.scopes
114 }
115}
116
117pub struct AuthClient {
119 config: OAuthConfig,
120 http: reqwest::Client,
121}
122
123#[non_exhaustive]
125pub struct AuthorizationRequest {
126 pub url: String,
127 pub state: String,
128 pub code_verifier: String,
129}
130
131#[derive(Debug, Clone, Deserialize)]
133#[non_exhaustive]
134pub struct TokenResponse {
135 pub access_token: String,
136 pub token_type: String,
137 #[serde(default)]
138 pub expires_in: Option<u64>,
139 #[serde(default)]
140 pub refresh_token: Option<String>,
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
145#[non_exhaustive]
146pub struct UserInfo {
147 pub sub: PpnumId,
148 #[serde(default)]
149 pub email: Option<String>,
150 pub ppnum: Ppnum,
151 #[serde(default)]
152 pub email_verified: Option<bool>,
153 #[serde(default, with = "time::serde::rfc3339::option")]
154 pub created_at: Option<time::OffsetDateTime>,
155}
156
157impl UserInfo {
158 #[must_use]
160 pub fn new(sub: PpnumId, ppnum: Ppnum) -> Self {
161 Self {
162 sub,
163 ppnum,
164 email: None,
165 email_verified: None,
166 created_at: None,
167 }
168 }
169
170 #[must_use]
172 pub fn with_email(mut self, email: impl Into<String>) -> Self {
173 self.email = Some(email.into());
174 self
175 }
176
177 #[must_use]
179 pub fn with_email_verified(mut self, verified: bool) -> Self {
180 self.email_verified = Some(verified);
181 self
182 }
183}
184
185impl AuthClient {
186 pub fn try_new(config: OAuthConfig) -> Result<Self, Error> {
198 let builder = reqwest::Client::builder();
199 #[cfg(not(target_arch = "wasm32"))]
200 let builder = builder
201 .timeout(std::time::Duration::from_secs(10))
202 .connect_timeout(std::time::Duration::from_secs(5));
203 Ok(Self {
204 config,
205 http: builder.build()?,
206 })
207 }
208
209 #[must_use]
215 pub fn with_http_client(config: OAuthConfig, client: reqwest::Client) -> Self {
216 Self {
217 config,
218 http: client,
219 }
220 }
221
222 #[must_use]
224 pub fn authorization_url(&self) -> AuthorizationRequest {
225 let state = pkce::generate_state();
226 let code_verifier = pkce::generate_code_verifier();
227 let code_challenge = pkce::generate_code_challenge(&code_verifier);
228 let scope = self.config.scopes.join(" ");
229
230 let mut url = self.config.auth_url.clone();
231 url.query_pairs_mut()
232 .append_pair("response_type", "code")
233 .append_pair("client_id", &self.config.client_id)
234 .append_pair("redirect_uri", self.config.redirect_uri.as_str())
235 .append_pair("state", &state)
236 .append_pair("code_challenge", &code_challenge)
237 .append_pair("code_challenge_method", "S256")
238 .append_pair("scope", &scope);
239
240 AuthorizationRequest {
241 url: url.into(),
242 state,
243 code_verifier,
244 }
245 }
246
247 pub async fn exchange_code(
254 &self,
255 code: &str,
256 code_verifier: &str,
257 ) -> Result<TokenResponse, Error> {
258 let params = [
259 ("grant_type", "authorization_code"),
260 ("code", code),
261 ("redirect_uri", self.config.redirect_uri.as_str()),
262 ("client_id", self.config.client_id.as_str()),
263 ("code_verifier", code_verifier),
264 ];
265
266 self.send_classified(
267 self.http.post(self.config.token_url.clone()).form(¶ms),
268 )
269 .await
270 .map_err(|f| f.into_legacy_error("token exchange"))
271 }
272
273 async fn send_classified<T: serde::de::DeserializeOwned>(
284 &self,
285 request: reqwest::RequestBuilder,
286 ) -> Result<T, crate::pas_port::PasFailure> {
287 use crate::pas_port::PasFailure;
288
289 let response = request
290 .send()
291 .await
292 .map_err(|e| PasFailure::Transport { detail: e.to_string() })?;
293
294 let status = response.status();
295 if status.is_server_error() {
296 let body = response.text().await.unwrap_or_default();
297 return Err(PasFailure::ServerError { status: status.as_u16(), detail: body });
298 }
299 if !status.is_success() {
300 let body = response.text().await.unwrap_or_default();
301 return Err(PasFailure::Rejected { status: status.as_u16(), detail: body });
302 }
303
304 response.json::<T>().await.map_err(|e| PasFailure::Transport {
305 detail: format!("response deserialization failed: {e}"),
306 })
307 }
308}
309
310impl crate::pas_port::PasAuthPort for AuthClient {
311 async fn refresh(
312 &self,
313 refresh_token: &str,
314 ) -> Result<TokenResponse, crate::pas_port::PasFailure> {
315 let params = [
316 ("grant_type", "refresh_token"),
317 ("refresh_token", refresh_token),
318 ("client_id", self.config.client_id.as_str()),
319 ];
320
321 self.send_classified(
322 self.http.post(self.config.token_url.clone()).form(¶ms),
323 )
324 .await
325 }
326
327 async fn userinfo(
328 &self,
329 access_token: &str,
330 ) -> Result<UserInfo, crate::pas_port::PasFailure> {
331 self.send_classified(
332 self.http
333 .get(self.config.userinfo_url.clone())
334 .bearer_auth(access_token),
335 )
336 .await
337 }
338}
339
340#[cfg(test)]
341#[allow(clippy::unwrap_used)]
342mod tests {
343 use super::*;
344
345 fn test_config() -> OAuthConfig {
346 OAuthConfig::new(
347 "test-client",
348 "https://example.com/callback".parse().unwrap(),
349 )
350 }
351
352 #[test]
353 fn test_authorization_url_contains_pkce() {
354 let client = AuthClient::try_new(test_config()).unwrap();
355 let req = client.authorization_url();
356
357 assert!(req.url.contains("code_challenge="));
358 assert!(req.url.contains("code_challenge_method=S256"));
359 assert!(req.url.contains("state="));
360 assert!(req.url.contains("response_type=code"));
361 assert!(req.url.contains("client_id=test-client"));
362 assert!(!req.code_verifier.is_empty());
363 assert!(!req.state.is_empty());
364 }
365
366 #[test]
367 fn test_authorization_url_unique_per_call() {
368 let client = AuthClient::try_new(test_config()).unwrap();
369 let req1 = client.authorization_url();
370 let req2 = client.authorization_url();
371
372 assert_ne!(req1.state, req2.state);
373 assert_ne!(req1.code_verifier, req2.code_verifier);
374 }
375
376 #[test]
377 fn test_config_constructor() {
378 let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap());
379
380 assert_eq!(config.client_id(), "my-app");
381 assert_eq!(
382 config.redirect_uri().as_str(),
383 "https://my-app.com/callback"
384 );
385 assert_eq!(
386 config.auth_url().as_str(),
387 "https://accounts.ppoppo.com/oauth/authorize"
388 );
389 }
390
391 #[test]
392 fn test_config_with_overrides() {
393 let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap())
394 .with_auth_url("https://custom.example.com/authorize".parse().unwrap())
395 .with_scopes(vec!["profile".into(), "email".into()]);
396
397 assert_eq!(
398 config.auth_url().as_str(),
399 "https://custom.example.com/authorize"
400 );
401 assert_eq!(config.scopes(), &["profile", "email"]);
402 }
403}