-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauth.rs
More file actions
223 lines (193 loc) · 7.76 KB
/
auth.rs
File metadata and controls
223 lines (193 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! Authentication handler for the Chaos application.
//!
//! This module provides HTTP request handlers for authentication, including:
//! - Google OAuth2 authentication
//! - JWT token generation
use crate::models::app::AppState;
use crate::models::auth::{AuthRequest, GoogleUserProfile};
use crate::models::error::ChaosError;
use crate::service::auth::create_or_get_user_id;
use crate::service::jwt::encode_auth_token;
use axum::extract::{Query, State};
use axum_extra::extract::cookie::{Cookie, CookieJar, Expiration};
use axum::response::{IntoResponse, Redirect};
use oauth2::reqwest::async_http_client;
use oauth2::{AuthorizationCode, TokenResponse, Scope};
use time::OffsetDateTime;
/// Handles the Google OAuth2 callback.
///
/// This handler processes the OAuth2 code received from Google after user authorization.
/// It exchanges the code for an access token, retrieves the user's profile information,
/// creates or retrieves the user in the database, and generates a JWT token for authentication.
///
/// # Arguments
///
/// * `state` - The application state
/// * `query` - The OAuth2 callback query parameters containing the authorization code
/// * `oauth_client` - The OAuth2 client for Google authentication
///
/// # Returns
///
/// * `Result<impl IntoResponse, ChaosError>` - JWT token or error
///
/// Initiates the Google OAuth2 flow.
///
/// This handler redirects users to Google's OAuth2 authorization URL to begin
/// the authentication process.
///
/// # Arguments
///
/// * `state` - The application state containing the OAuth2 client
///
/// # Returns
///
/// * `Result<impl IntoResponse, ChaosError>` - Redirect to Google OAuth or error
pub async fn google_auth_init(
State(state): State<AppState>,
) -> Result<impl IntoResponse, ChaosError> {
let (auth_url, _csrf_token) = state.oauth2_client
.authorize_url(|| oauth2::CsrfToken::new_random())
.add_scope(Scope::new("openid".to_string()))
.add_scope(Scope::new("email".to_string()))
.add_scope(Scope::new("profile".to_string()))
.url();
Ok(Redirect::to(auth_url.as_str()))
}
/// Handles the Google OAuth2 callback.
///
/// This handler processes the OAuth2 code received from Google after user authorization.
/// It exchanges the code for an access token, retrieves the user's profile information,
/// creates or retrieves the user in the database, and generates a JWT token for authentication.
///
/// # Arguments
///
/// * `state` - The application state
/// * `query` - The OAuth2 callback query parameters containing the authorization code
/// * `oauth_client` - The OAuth2 client for Google authentication
///
/// # Returns
///
/// * `Result<impl IntoResponse, ChaosError>` - JWT token or error
///
/// # Note
///
/// Currently returns the JWT token directly. TODO: Return it as a set-cookie header.
pub async fn google_callback(
State(mut state): State<AppState>,
jar: CookieJar,
Query(query): Query<AuthRequest>,
) -> Result<impl IntoResponse, ChaosError> {
let token = state.oauth2_client
.exchange_code(AuthorizationCode::new(query.code))
.request_async(async_http_client)
.await?;
let profile = state
.ctx
.get("https://openidconnect.googleapis.com/v1/userinfo")
.bearer_auth(token.access_token().secret().to_owned())
.send()
.await?;
let profile = profile.json::<GoogleUserProfile>().await?;
let user_id = create_or_get_user_id(
profile.email.clone(),
profile.name,
state.db,
&mut state.snowflake_generator,
)
.await?;
let token = encode_auth_token(
profile.email,
user_id,
&state.encoding_key,
&state.jwt_header,
);
// Create a cookie with the token
let cookie = Cookie::build(("auth_token", token))
.http_only(true) // Prevent JavaScript access
.expires(Expiration::DateTime(OffsetDateTime::now_utc() + time::Duration::days(5))) // Set an expiration time of 5 days, TODO: read from env?
.secure(!state.is_dev_env) // Send only over HTTPS, comment out for testing
.path("/"); // Available for all paths
// Redirect to the frontend dashboard after successful authentication
let redirect_url = if state.is_dev_env {
"http://localhost:3000/dashboard"
} else {
"/dashboard" // In production, this would be the full URL
};
// Add the cookie and redirect
Ok((jar.add(cookie), Redirect::to(redirect_url)))
}
pub struct DevLoginHandler;
impl DevLoginHandler {
pub async fn dev_super_admin_login(
State(state): State<AppState>,
jar: CookieJar
) -> Result<impl IntoResponse, ChaosError> {
if !state.is_dev_env {
// Disabled for non dev environment
return Err(ChaosError::ForbiddenOperation);
}
let token = encode_auth_token(
"example.superuser@chaos.devsoc.app".to_string(),
1,
&state.encoding_key,
&state.jwt_header,
);
// Create a cookie with the token
let cookie = Cookie::build(("auth_token", token))
.http_only(true) // Prevent JavaScript access
.expires(Expiration::DateTime(OffsetDateTime::now_utc() + time::Duration::days(5))) // Set an expiration time of 5 days, TODO: read from env?
.path("/"); // Available for all paths
// Redirect to the frontend dashboard after successful authentication
let redirect_url = "http://localhost:3000/dashboard";
// Add the cookie and redirect
Ok((jar.add(cookie), Redirect::to(redirect_url)))
}
pub async fn dev_org_admin_login(
State(state): State<AppState>,
jar: CookieJar
) -> Result<impl IntoResponse, ChaosError> {
if !state.is_dev_env {
// Disabled for non dev environment
return Err(ChaosError::ForbiddenOperation);
}
let token = encode_auth_token(
"example.admin@chaos.devsoc.app".to_string(),
2,
&state.encoding_key,
&state.jwt_header,
);
// Create a cookie with the token
let cookie = Cookie::build(("auth_token", token))
.http_only(true) // Prevent JavaScript access
.expires(Expiration::DateTime(OffsetDateTime::now_utc() + time::Duration::days(5))) // Set an expiration time of 5 days, TODO: read from env?
.path("/"); // Available for all paths
// Redirect to the frontend dashboard after successful authentication
let redirect_url = "http://localhost:3000/dashboard";
// Add the cookie and redirect
Ok((jar.add(cookie), Redirect::to(redirect_url)))
}
pub async fn dev_user_login(
State(state): State<AppState>,
jar: CookieJar
) -> Result<impl IntoResponse, ChaosError> {
if !state.is_dev_env {
// Disabled for non dev environment
return Err(ChaosError::ForbiddenOperation);
}
let token = encode_auth_token(
"example.user@chaos.devsoc.app".to_string(),
3,
&state.encoding_key,
&state.jwt_header,
);
// Create a cookie with the token
let cookie = Cookie::build(("auth_token", token))
.http_only(true) // Prevent JavaScript access
.expires(Expiration::DateTime(OffsetDateTime::now_utc() + time::Duration::days(5))) // Set an expiration time of 5 days, TODO: read from env?
.path("/"); // Available for all paths
// Redirect to the frontend dashboard after successful authentication
let redirect_url = "http://localhost:3000/dashboard";
// Add the cookie and redirect
Ok((jar.add(cookie), Redirect::to(redirect_url)))
}
}