use std::{
net::{Ipv4Addr, SocketAddrV4},
sync::Arc,
time::Duration,
};
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;
use redis::aio::ConnectionManager;
use router::Router;
use tiny_google_oidc::config::ConfigBuilder;
use tracing::{error, info};
mod login_service;
mod protected;
mod router;
static REDIS_URL: &str = "redis://localhost:6379";
static AUTH_ENDPOINT: &str = "https://accounts.google.com/o/oauth2/auth";
static CLIENT_ID: &str = "your_client_id";
static CLIENT_SECRET: &str = "your_client_secret";
static REDIRECT_URL: &str = "http://localhost/auth/callback";
static TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
let redis_client = redis::Client::open(REDIS_URL).expect("Failed to open redis client");
let redis_conn = ConnectionManager::new(redis_client)
.await
.expect("Failed to establish redis connection");
let addr = SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 80);
let listener = tokio::net::TcpListener::bind(addr)
.await
.expect("Failed to bind tcp listener");
info!("Server is running");
let config = Arc::new(
ConfigBuilder::new()
.auth_endpoint(AUTH_ENDPOINT)
.client_id(CLIENT_ID)
.client_secret(CLIENT_SECRET)
.redirect_uri(REDIRECT_URL)
.token_endpoint(TOKEN_ENDPOINT)
.build(),
);
let service = Router::new(config.clone(), redis_conn);
info!("Listening on {:?}", addr);
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
let service = service.clone();
tokio::task::spawn(async move {
let conn = http1::Builder::new().serve_connection(io, service);
tokio::pin!(conn);
tokio::select! {
res = conn.as_mut() => match res {
Ok(()) => {},
Err(e) => error!("error: {:?}", e),
},
_ = tokio::time::sleep(Duration::from_secs(5)) => {
conn.graceful_shutdown();
}
}
});
}
}