agent_server/auth/
routes.rs1use actix_web::{
4 HttpRequest, HttpResponse, Responder, Scope, get, post,
5 web::{self, Data},
6};
7use serde::{Deserialize, Serialize};
8
9use super::telegram_auth::{LOGIN_TTL, SESSION_TTL, TelegramAuth};
10
11#[derive(Deserialize)]
12struct LoginStatusRequest {
13 token: String,
14}
15
16#[derive(Serialize)]
17struct StartLoginResponse {
18 token: String,
19 bot_url: Option<String>,
20 expires_in_seconds: u64,
21}
22
23#[derive(Serialize)]
24struct SessionResponse {
25 owner: String,
26}
27
28#[post("/telegram/start")]
29async fn start_login(auth: Data<TelegramAuth>) -> impl Responder {
30 let (token, bot_url) = auth.create_login();
31 HttpResponse::Created().json(StartLoginResponse {
32 token,
33 bot_url,
34 expires_in_seconds: LOGIN_TTL.as_secs(),
35 })
36}
37
38#[post("/telegram/status")]
39async fn login_status(
40 auth: Data<TelegramAuth>,
41 request: web::Json<LoginStatusRequest>,
42) -> impl Responder {
43 match auth.poll_login(&request.token) {
44 Some(session) => HttpResponse::Ok()
45 .insert_header((
46 actix_web::http::header::SET_COOKIE,
47 auth.cookie(&session, SESSION_TTL.as_secs()),
48 ))
49 .json(serde_json::json!({ "authenticated": true })),
50 None => HttpResponse::Accepted().json(serde_json::json!({ "authenticated": false })),
51 }
52}
53
54#[get("/session")]
55async fn current_session(request: HttpRequest, auth: Data<TelegramAuth>) -> impl Responder {
56 match auth.owner_for_request(&request) {
57 Some(owner) => HttpResponse::Ok().json(SessionResponse { owner }),
58 None => HttpResponse::Unauthorized().finish(),
59 }
60}
61
62#[post("/logout")]
63async fn logout(request: HttpRequest, auth: Data<TelegramAuth>) -> impl Responder {
64 auth.logout(&request);
65 HttpResponse::NoContent()
66 .insert_header((actix_web::http::header::SET_COOKIE, auth.clear_cookie()))
67 .finish()
68}
69
70pub fn auth_api() -> Scope {
71 web::scope("/auth")
72 .service(start_login)
73 .service(login_status)
74 .service(current_session)
75 .service(logout)
76}