-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
53 lines (47 loc) · 1.77 KB
/
Copy pathserver.rs
File metadata and controls
53 lines (47 loc) · 1.77 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
//! Minimal Actix Web example demonstrating [`FirebaseUser`] extractor.
//!
//! This server exposes two endpoints:
//! - `/protected`: Requires a valid Firebase ID token and returns the decoded user info.
//! - `/whoami`: Returns user info if authenticated, or `"Anonymous"` otherwise.
//!
//! Firebase project ID can be set via the `FIREBASE_PROJECT_ID` environment variable,
//! otherwise it falls back to "your-project-id" for testing purposes.
use actix_firebase_auth::{FirebaseAuth, FirebaseUser};
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use std::env;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Read project ID from environment variable or fallback to a default for dev
let project_id = env::var("FIREBASE_PROJECT_ID")
.unwrap_or_else(|_| "your-project-id".to_string());
// Initialize Firebase Auth client (fetches public keys etc.)
let auth = match FirebaseAuth::new(&project_id).await {
Ok(auth) => auth,
Err(e) => {
eprintln!("Failed to initialize FirebaseAuth: {e}");
std::process::exit(1);
}
};
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(auth.clone()))
.service(protected)
.service(whoami)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
// Protected route — requires a valid Firebase ID token
#[get("/protected")]
async fn protected(user: FirebaseUser) -> impl Responder {
HttpResponse::Ok().json(user)
}
// Returns the authenticated user's info, or null if unauthenticated
#[get("/whoami")]
async fn whoami(user: Option<FirebaseUser>) -> impl Responder {
match user {
Some(u) => HttpResponse::Ok().json(u),
None => HttpResponse::Ok().body("Anonymous"),
}
}