Skip to content

Commit b759fe0

Browse files
committed
style: apply formatting and clean up imports in authly-flow and examples
1 parent 156f3ed commit b759fe0

6 files changed

Lines changed: 89 additions & 47 deletions

File tree

authly-flow/src/device_flow.rs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,7 @@ pub struct DeviceFlow {
3333

3434
impl DeviceFlow {
3535
/// Creates a new `DeviceFlow` instance.
36-
pub fn new(
37-
client_id: String,
38-
device_authorization_url: String,
39-
token_url: String,
40-
) -> Self {
36+
pub fn new(client_id: String, device_authorization_url: String, token_url: String) -> Self {
4137
Self {
4238
client_id,
4339
device_authorization_url,
@@ -59,10 +55,7 @@ impl DeviceFlow {
5955
.http_client
6056
.post(&self.device_authorization_url)
6157
.header("Accept", "application/json")
62-
.form(&[
63-
("client_id", &self.client_id),
64-
("scope", &scope_param),
65-
])
58+
.form(&[("client_id", &self.client_id), ("scope", &scope_param)])
6659
.send()
6760
.await
6861
.map_err(|_| AuthError::Network)?;
@@ -78,7 +71,12 @@ impl DeviceFlow {
7871
response
7972
.json::<DeviceAuthorizationResponse>()
8073
.await
81-
.map_err(|e| AuthError::Provider(format!("Failed to parse device authorization response: {}", e)))
74+
.map_err(|e| {
75+
AuthError::Provider(format!(
76+
"Failed to parse device authorization response: {}",
77+
e
78+
))
79+
})
8280
}
8381

8482
/// Polls the token endpoint until an access token is granted or an error occurs.
@@ -99,25 +97,27 @@ impl DeviceFlow {
9997
.form(&[
10098
("client_id", &self.client_id),
10199
("device_code", &device_code.to_string()),
102-
("grant_type", &"urn:ietf:params:oauth:grant-type:device_code".to_string()),
100+
(
101+
"grant_type",
102+
&"urn:ietf:params:oauth:grant-type:device_code".to_string(),
103+
),
103104
])
104105
.send()
105106
.await
106107
.map_err(|_| AuthError::Network)?;
107108

108109
let status = response.status();
109-
110+
110111
if status.is_success() {
111-
return response
112-
.json::<OAuthToken>()
113-
.await
114-
.map_err(|e| AuthError::Provider(format!("Failed to parse token response: {}", e)));
112+
return response.json::<OAuthToken>().await.map_err(|e| {
113+
AuthError::Provider(format!("Failed to parse token response: {}", e))
114+
});
115115
} else {
116116
let error_resp: serde_json::Value = response
117117
.json()
118118
.await
119119
.map_err(|_| AuthError::Provider("Failed to parse error response".into()))?;
120-
120+
121121
let error = error_resp["error"].as_str().unwrap_or("unknown_error");
122122

123123
match error {
@@ -134,7 +134,10 @@ impl DeviceFlow {
134134
return Err(AuthError::Provider("Device code expired".into()));
135135
}
136136
_ => {
137-
return Err(AuthError::Provider(format!("Token polling failed: {}", error)));
137+
return Err(AuthError::Provider(format!(
138+
"Token polling failed: {}",
139+
error
140+
)));
138141
}
139142
}
140143
}

examples/actix_github.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ async fn github_callback(
4343
}
4444

4545
#[get("/auth/logout")]
46-
async fn github_logout(req: HttpRequest, data: web::Data<AppState>) -> actix_web::Result<impl Responder> {
46+
async fn github_logout(
47+
req: HttpRequest,
48+
data: web::Data<AppState>,
49+
) -> actix_web::Result<impl Responder> {
4750
logout(
4851
req,
4952
data.session_store.clone(),
@@ -55,11 +58,13 @@ async fn github_logout(req: HttpRequest, data: web::Data<AppState>) -> actix_web
5558

5659
#[get("/protected")]
5760
async fn protected(session: AuthSession) -> impl Responder {
58-
let name = session.0.identity
61+
let name = session
62+
.0
63+
.identity
5964
.username
6065
.clone()
6166
.unwrap_or_else(|| "Unknown".to_string());
62-
67+
6368
HttpResponse::Ok().body(format!(
6469
"Hello, {}! Your ID is {}. You are authenticated via the new AuthSession extractor.",
6570
name, session.0.identity.external_id
@@ -70,14 +75,16 @@ async fn protected(session: AuthSession) -> impl Responder {
7075
async fn main() -> std::io::Result<()> {
7176
dotenvy::dotenv().ok();
7277

73-
let client_id = std::env::var("AUTHLY_GITHUB_CLIENT_ID").expect("AUTHLY_GITHUB_CLIENT_ID must be set");
74-
let client_secret = std::env::var("AUTHLY_GITHUB_CLIENT_SECRET").expect("AUTHLY_GITHUB_CLIENT_SECRET must be set");
78+
let client_id =
79+
std::env::var("AUTHLY_GITHUB_CLIENT_ID").expect("AUTHLY_GITHUB_CLIENT_ID must be set");
80+
let client_secret = std::env::var("AUTHLY_GITHUB_CLIENT_SECRET")
81+
.expect("AUTHLY_GITHUB_CLIENT_SECRET must be set");
7582
let redirect_uri = std::env::var("AUTHLY_GITHUB_REDIRECT_URI")
7683
.unwrap_or_else(|_| "http://localhost:8080/auth/github/callback".to_string());
7784

7885
let provider = GithubProvider::new(client_id, client_secret, redirect_uri);
7986
let github_flow = Arc::new(OAuth2Flow::new(provider));
80-
87+
8188
// For this example, we'll use SQLite for session persistence.
8289
let db_url = "sqlite::memory:";
8390
let pool = SqlitePool::connect(db_url)

examples/axum_oauth.rs

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,11 @@ async fn github_login(State(state): State<AppState>, cookies: Cookies) -> Respon
146146
if let Some(flow) = &state.github_flow {
147147
initiate_oauth_login(flow, &cookies, &["user:email"]).into_response()
148148
} else {
149-
(axum::http::StatusCode::NOT_IMPLEMENTED, "GitHub not configured").into_response()
149+
(
150+
axum::http::StatusCode::NOT_IMPLEMENTED,
151+
"GitHub not configured",
152+
)
153+
.into_response()
150154
}
151155
}
152156

@@ -167,7 +171,11 @@ async fn github_callback(
167171
.await
168172
.into_response()
169173
} else {
170-
(axum::http::StatusCode::NOT_IMPLEMENTED, "GitHub not configured").into_response()
174+
(
175+
axum::http::StatusCode::NOT_IMPLEMENTED,
176+
"GitHub not configured",
177+
)
178+
.into_response()
171179
}
172180
}
173181

@@ -176,7 +184,11 @@ async fn google_login(State(state): State<AppState>, cookies: Cookies) -> Respon
176184
if let Some(flow) = &state.google_flow {
177185
initiate_oauth_login(flow, &cookies, &["openid", "email", "profile"]).into_response()
178186
} else {
179-
(axum::http::StatusCode::NOT_IMPLEMENTED, "Google not configured").into_response()
187+
(
188+
axum::http::StatusCode::NOT_IMPLEMENTED,
189+
"Google not configured",
190+
)
191+
.into_response()
180192
}
181193
}
182194

@@ -197,7 +209,11 @@ async fn google_callback(
197209
.await
198210
.into_response()
199211
} else {
200-
(axum::http::StatusCode::NOT_IMPLEMENTED, "Google not configured").into_response()
212+
(
213+
axum::http::StatusCode::NOT_IMPLEMENTED,
214+
"Google not configured",
215+
)
216+
.into_response()
201217
}
202218
}
203219

@@ -206,7 +222,11 @@ async fn discord_login(State(state): State<AppState>, cookies: Cookies) -> Respo
206222
if let Some(flow) = &state.discord_flow {
207223
initiate_oauth_login(flow, &cookies, &["identify", "email"]).into_response()
208224
} else {
209-
(axum::http::StatusCode::NOT_IMPLEMENTED, "Discord not configured").into_response()
225+
(
226+
axum::http::StatusCode::NOT_IMPLEMENTED,
227+
"Discord not configured",
228+
)
229+
.into_response()
210230
}
211231
}
212232

@@ -227,7 +247,11 @@ async fn discord_callback(
227247
.await
228248
.into_response()
229249
} else {
230-
(axum::http::StatusCode::NOT_IMPLEMENTED, "Discord not configured").into_response()
250+
(
251+
axum::http::StatusCode::NOT_IMPLEMENTED,
252+
"Discord not configured",
253+
)
254+
.into_response()
231255
}
232256
}
233257

examples/client_credentials_flow.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
55
// Example using a hypothetical provider
66
// In a real scenario, you would use your OAuth2 provider's client credentials credentials
77
let client_id = std::env::var("CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string());
8-
let client_secret = std::env::var("CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string());
9-
let token_url = std::env::var("TOKEN_URL").unwrap_or_else(|_| "https://example.com/oauth/token".to_string());
8+
let client_secret =
9+
std::env::var("CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string());
10+
let token_url = std::env::var("TOKEN_URL")
11+
.unwrap_or_else(|_| "https://example.com/oauth/token".to_string());
1012

1113
println!("Starting Client Credentials Flow...");
1214

13-
let flow = ClientCredentialsFlow::new(
14-
client_id,
15-
client_secret,
16-
token_url,
17-
);
15+
let flow = ClientCredentialsFlow::new(client_id, client_secret, token_url);
1816

1917
// Request a token with optional scopes
2018
let scopes = ["read", "write"];

examples/device_flow.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use authly_flow::DeviceFlow;
33
#[tokio::main]
44
async fn main() -> Result<(), Box<dyn std::error::Error>> {
55
// GitHub's Device Authorization Flow endpoints
6-
let client_id = std::env::var("GITHUB_CLIENT_ID").unwrap_or_else(|_| "Iv1.your_client_id".to_string());
6+
let client_id =
7+
std::env::var("GITHUB_CLIENT_ID").unwrap_or_else(|_| "Iv1.your_client_id".to_string());
78
let device_auth_url = "https://github.com/login/device/code";
89
let token_url = "https://github.com/login/oauth/access_token";
910

@@ -20,17 +21,23 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
2021
.initiate_device_authorization(&["user", "repo"])
2122
.await?;
2223

23-
println!("\n1. Open your browser and go to: {}", device_resp.verification_uri);
24+
println!(
25+
"\n1. Open your browser and go to: {}",
26+
device_resp.verification_uri
27+
);
2428
println!("2. Enter the code: {}", device_resp.user_code);
25-
29+
2630
if let Some(complete_uri) = &device_resp.verification_uri_complete {
2731
println!("\nOR just open this URL directly: {}", complete_uri);
2832
}
2933

3034
println!("\nWaiting for authorization...");
3135

3236
// 2. Poll for the token
33-
match flow.poll_for_token(&device_resp.device_code, device_resp.interval).await {
37+
match flow
38+
.poll_for_token(&device_resp.device_code, device_resp.interval)
39+
.await
40+
{
3441
Ok(token) => {
3542
println!("\nAuthorization successful!");
3643
println!("Access Token: {}", token.access_token);

examples/offline_validation.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
1-
use authly_token::offline_validation::{JwksCache, validate_jwt};
2-
use jsonwebtoken::{Validation, Algorithm};
1+
use authly_token::offline_validation::{validate_jwt, JwksCache};
2+
use jsonwebtoken::{Algorithm, Validation};
33
use std::time::Duration;
44

55
#[tokio::main]
66
async fn main() -> Result<(), Box<dyn std::error::Error>> {
77
// 1. Initialize the JWKS Cache
88
// In a real scenario, this would be your OIDC provider's JWKS URI
9-
// For this example, we'll use a placeholder or a mock if we were testing,
9+
// For this example, we'll use a placeholder or a mock if we were testing,
1010
// but here we show the structure.
1111
let jwks_uri = "https://www.googleapis.com/oauth2/v3/certs".to_string();
1212
let refresh_interval = Duration::from_secs(3600); // 1 hour
1313

1414
println!("Initializing JWKS cache for: {}", jwks_uri);
15-
15+
1616
// Note: This will actually attempt to fetch the JWKS from the URI.
1717
// If you are offline or the URI is invalid, this will fail.
1818
let cache = match JwksCache::new(jwks_uri, refresh_interval).await {
1919
Ok(c) => c,
2020
Err(e) => {
21-
eprintln!("Failed to initialize JWKS cache: {}. (Expected if no network or invalid URI)", e);
21+
eprintln!(
22+
"Failed to initialize JWKS cache: {}. (Expected if no network or invalid URI)",
23+
e
24+
);
2225
return Ok(());
2326
}
2427
};
@@ -32,7 +35,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
3235

3336
// 3. Validate a Token
3437
// In a real app, you'd get this from an Authorization header
35-
let token = "your.jwt.token";
38+
let token = "your.jwt.token";
3639

3740
println!("Validating token...");
3841
match validate_jwt(token, &cache, &validation).await {

0 commit comments

Comments
 (0)