feat: with clap example

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2023-10-22 22:33:47 +02:00
parent 32d8030f24
commit 89acf8c343
7 changed files with 162 additions and 32 deletions

16
examples/clap/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "clap"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nefarious-login.workspace = true
tokio.workspace = true
anyhow.workspace = true
axum.workspace = true
clap.workspace = true
tracing-subscriber.workspace = true

88
examples/clap/src/main.rs Normal file
View File

@@ -0,0 +1,88 @@
use std::net::SocketAddr;
use axum::{
extract::{FromRef, State},
response::IntoResponse,
routing::get,
Router,
};
use clap::Parser;
use nefarious_login::{
auth::AuthService,
axum::{AuthController, UserFromSession},
login::AuthClap,
session::SessionService,
};
use tracing_subscriber::EnvFilter;
#[derive(Clone)]
struct AppState {
auth: AuthService,
}
#[derive(Debug, Clone, Parser)]
struct Command {
#[clap(flatten)]
auth: AuthClap,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.init();
let cmd = Command::parse_from(vec![
"base",
"--auth-engine=zitadel",
"--zitadel-authority-url=https://personal-wxuujs.zitadel.cloud",
"--zitadel-redirect-url=http://localhost:3001/auth/authorized",
"--zitadel-client-id=237412977047895154@nefarious-test",
"--zitadel-client-secret=rWwDi8gjNOyuMFKoOjNSlhjcVZ1B25wDh6HsDL27f0g2Hb0xGbvEf0WXFY2akOlL",
"--session-backend=postgresql",
"--session-postgres-conn=postgres://como:somenotverysecurepassword@localhost:5432/como",
]);
let auth = cmd.auth;
let session_service = SessionService::new(&auth).await?;
let auth_service = AuthService::new(&auth, session_service).await?;
let state = AppState {
auth: auth_service.clone(),
};
let app = Router::new()
.route("/unauthed", get(unauthed))
.route("/authed", get(authed))
.with_state(state)
.nest("/auth", AuthController::new_router(auth_service).await?);
let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
println!("listening on: {addr}");
println!("open browser at: http://localhost:3001/auth/zitadel");
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
Ok(())
}
impl FromRef<AppState> for AuthService {
fn from_ref(input: &AppState) -> Self {
input.auth.clone()
}
}
async fn unauthed() -> String {
"Hello Unauthorized User".into()
}
#[axum::debug_handler()]
async fn authed(
user: UserFromSession,
State(_auth_service): State<AuthService>,
) -> impl IntoResponse {
format!("Hello authorized user: {:?}", user.user.id)
}