use potato::{HttpServer, OnceCache, SessionCache};
#[potato::controller]
pub struct AuthTestController<'a> {
pub once_cache: &'a OnceCache,
pub sess_cache: &'a SessionCache,
}
#[potato::controller("/api/auth-test")]
impl<'a> AuthTestController<'a> {
#[potato::http_get("/protected")]
pub async fn get_protected(&self) -> anyhow::Result<&'static str> {
Ok("Protected data accessed successfully")
}
#[potato::http_post("/update")]
pub async fn update_data(&mut self) -> anyhow::Result<&'static str> {
Ok("Data updated successfully")
}
#[potato::http_get("/public")]
pub async fn get_public() -> anyhow::Result<&'static str> {
Ok("Public data")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[tokio::test]
async fn test_controller_requires_auth_without_header() {
let port = 18890;
let server_addr = format!("127.0.0.1:{}", port);
let mut server = HttpServer::new(&server_addr);
server.configure(|ctx| {
ctx.use_handlers();
});
let server_handle = tokio::spawn(async move {
let _ = server.serve_http().await;
});
tokio::time::sleep(Duration::from_millis(500)).await;
let url = format!("http://{}/api/auth-test/protected", server_addr);
match potato::get(&url, vec![]).await {
Ok(res) => {
assert_eq!(
res.http_code, 401,
"Should return 401 without Authorization header"
);
println!("✅ GET /api/auth-test/protected correctly returns 401 without auth");
}
Err(e) => {
panic!("Request failed: {}", e);
}
}
let url = format!("http://{}/api/auth-test/update", server_addr);
match potato::post(&url, vec![], vec![]).await {
Ok(res) => {
assert_eq!(
res.http_code, 401,
"Should return 401 without Authorization header"
);
println!("✅ POST /api/auth-test/update correctly returns 401 without auth");
}
Err(e) => {
panic!("Request failed: {}", e);
}
}
let url = format!("http://{}/api/auth-test/public", server_addr);
match potato::get(&url, vec![]).await {
Ok(res) => {
assert_eq!(res.http_code, 200, "Public endpoint should return 200");
println!("✅ GET /api/auth-test/public correctly returns 200 (no auth required)");
}
Err(e) => {
panic!("Request failed: {}", e);
}
}
SessionCache::set_jwt_secret(b"test-secret-key-for-testing").await;
let token = SessionCache::generate_token(123, Duration::from_secs(3600))
.await
.unwrap();
let url = format!("http://{}/api/auth-test/protected", server_addr);
match potato::get!(&url, Authorization = format!("Bearer {}", token)).await {
Ok(res) => {
assert_eq!(
res.http_code, 200,
"Should return 200 with valid Authorization header"
);
println!("✅ GET /api/auth-test/protected correctly returns 200 with valid auth");
}
Err(e) => {
panic!("Request failed: {}", e);
}
}
server_handle.abort();
}
}