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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#![cfg(feature = "cli")]
use crate::tools::cli::config::sso::get_sso_url;
use crate::tools::cli::config::user::{clear_session_token, get_session_token, set_session_token};
use anyhow::Result;
use std::str::FromStr;
use tiny_http::{Header, Response, Server};
fn html_content_type_header() -> Result<Header> {
Header::from_str("Content-Type: text/html; charset=utf-8")
.map_err(|_| anyhow::anyhow!("Failed to build response header"))
}
/// Login command with OAuth flow
/// Opens browser to SSO page and waits for callback with session token
pub async fn login(_token: Option<String>) -> Result<()> {
use crate::tools::logger::Logger;
let logger = Logger::new();
logger.info("Starting authentication flow...");
// Find an available port starting from 7878
let mut listener_port = 7878;
let test_port_already_in_use = format!("127.0.0.1:{}", listener_port);
while std::net::TcpListener::bind(&test_port_already_in_use).is_err() {
listener_port += 1;
}
// Build OAuth URLs
let redirect_uri = format!("http://127.0.0.1:{}/callback", listener_port);
let login_url = format!(
"{}/?response_type=code&referer=cli&redirect_uri={}",
get_sso_url(),
redirect_uri
);
// Try to open browser
logger.info("Opening browser for authentication...");
if webbrowser::open(&login_url).is_ok() {
logger.success("Browser opened successfully");
logger.info(&format!(
"If the browser didn't open, visit this URL:\n {}",
login_url
));
} else {
logger.error("Could not open browser automatically");
logger.info(&format!(
"Please open this URL in your browser:\n {}",
login_url
));
}
// Start local HTTP server to receive callback
let server = Server::http(format!("127.0.0.1:{}", listener_port))
.map_err(|e| anyhow::anyhow!("Failed to start local server: {}", e))?;
logger.info(&format!(
"Waiting for authentication... (Listening on http://127.0.0.1:{})",
listener_port
));
// Wait for callback
for request in server.incoming_requests() {
let query = request.url().to_string();
// Handle callback with session token
if request.url().starts_with("/callback") {
if query.contains("session=") {
// Extract token from query string
let token = query
.split("session=")
.nth(1)
.and_then(|s| s.split('&').next())
.unwrap_or("")
.to_string();
if !token.is_empty() {
// Send success response to browser
let response_html = r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Authentication Successful</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
text-align: center;
background: white;
padding: 3rem;
border-radius: 1rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
h1 {
color: #667eea;
margin-bottom: 1rem;
font-size: 2.5rem;
}
p {
color: #666;
font-size: 1.2rem;
}
.icon {
font-size: 4rem;
margin-bottom: 1rem;
}
</style>
</head>
<body>
<div class="container">
<div class="icon">✅</div>
<h1>Authentication Successful!</h1>
<p>You can now close this window and return to the terminal.</p>
</div>
</body>
</html>
"#;
let response = Response::from_string(response_html)
.with_status_code(200)
.with_header(html_content_type_header()?);
let _ = request.respond(response);
// Save token
set_session_token(token)?;
logger.success("Authentication successful!");
logger.info("Token saved to ~/.devalang/config.json");
return Ok(());
} else {
let response_html = r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Authentication Failed</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.container {
text-align: center;
background: white;
padding: 3rem;
border-radius: 1rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
h1 {
color: #f5576c;
margin-bottom: 1rem;
font-size: 2.5rem;
}
p {
color: #666;
font-size: 1.2rem;
}
.icon {
font-size: 4rem;
margin-bottom: 1rem;
}
</style>
</head>
<body>
<div class="container">
<div class="icon">❌</div>
<h1>Authentication Failed</h1>
<p>Invalid session token. Please try again.</p>
</div>
</body>
</html>
"#;
let response = Response::from_string(response_html)
.with_status_code(400)
.with_header(html_content_type_header()?);
let _ = request.respond(response);
return Err(anyhow::anyhow!("Invalid session token received from SSO"));
}
} else if query.contains("error=") {
let error = query
.split("error=")
.nth(1)
.and_then(|s| s.split('&').next())
.unwrap_or("unknown")
.to_string();
let response_html = format!(
r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Authentication Error</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}}
.container {{
text-align: center;
background: white;
padding: 3rem;
border-radius: 1rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}}
h1 {{
color: #f5576c;
margin-bottom: 1rem;
font-size: 2.5rem;
}}
p {{
color: #666;
font-size: 1.2rem;
}}
.icon {{
font-size: 4rem;
margin-bottom: 1rem;
}}
.error {{
background: #ffe0e0;
padding: 1rem;
border-radius: 0.5rem;
margin-top: 1rem;
color: #c00;
}}
</style>
</head>
<body>
<div class="container">
<div class="icon">⚠️</div>
<h1>Authentication Error</h1>
<p>An error occurred during authentication.</p>
<div class="error">{}</div>
</div>
</body>
</html>
"#,
error
);
let response = Response::from_string(response_html)
.with_status_code(400)
.with_header(html_content_type_header()?);
let _ = request.respond(response);
return Err(anyhow::anyhow!("Authentication error: {}", error));
} else {
let response_html = r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Invalid Callback</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.container {
text-align: center;
background: white;
padding: 3rem;
border-radius: 1rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
h1 {
color: #f5576c;
margin-bottom: 1rem;
font-size: 2.5rem;
}
p {
color: #666;
font-size: 1.2rem;
}
.icon {
font-size: 4rem;
margin-bottom: 1rem;
}
</style>
</head>
<body>
<div class="container">
<div class="icon">❌</div>
<h1>Invalid Callback</h1>
<p>The authentication callback is invalid.</p>
</div>
</body>
</html>
"#;
let response = Response::from_string(response_html)
.with_status_code(400)
.with_header(html_content_type_header()?);
let _ = request.respond(response);
return Err(anyhow::anyhow!("Invalid callback received"));
}
}
// Ignore favicon requests
else if request.url().starts_with("/favicon.ico") {
let response = Response::from_string("").with_status_code(404);
let _ = request.respond(response);
}
// Handle any other invalid requests
else {
let response = Response::from_string("Invalid request").with_status_code(400);
let _ = request.respond(response);
}
}
Err(anyhow::anyhow!("Authentication flow interrupted"))
}
/// Logout command
pub async fn logout() -> Result<()> {
use crate::tools::logger::Logger;
let logger = Logger::new();
if get_session_token().is_none() {
logger.info("You are not logged in.");
return Ok(());
}
clear_session_token()?;
logger.success("Successfully logged out!");
logger.info("Token removed from ~/.devalang/config.json");
Ok(())
}
/// Command to check authentication status
pub async fn check_auth_status() -> Result<()> {
use crate::tools::logger::Logger;
let logger = Logger::new();
if let Some(token) = get_session_token() {
logger.success("You are logged in.");
logger.info(&format!("Token: {}...", &token[..token.len().min(10)]));
} else {
logger.error("You are not logged in.");
logger.info("Run 'devalang login' to authenticate.");
}
Ok(())
}