This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
use askama::Template;
|
||||
use axum::response::{Html, Redirect};
|
||||
use axum::{Form, extract::Query, extract::State};
|
||||
use axum_sessions::extractors::{ReadableSession, WritableSession};
|
||||
use axum_session::Session;
|
||||
use axum_session_sqlx::SessionSqlitePool;
|
||||
use oauth2::{AuthorizationCode, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, Scope};
|
||||
use reqwest::Client;
|
||||
use serde::Deserialize;
|
||||
@@ -26,7 +27,7 @@ pub async fn index(State(state): State<crate::AppState>) -> Html<String> {
|
||||
Html(template.render().unwrap())
|
||||
}
|
||||
|
||||
pub async fn login(State(state): State<crate::AppState>, mut session: WritableSession) -> Redirect {
|
||||
pub async fn login(State(state): State<crate::AppState>, session: Session<SessionSqlitePool>) -> Redirect {
|
||||
// Generate PKCE challenge
|
||||
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
@@ -40,19 +41,15 @@ pub async fn login(State(state): State<crate::AppState>, mut session: WritableSe
|
||||
.url();
|
||||
|
||||
// Store the CSRF token and PKCE verifier in the session
|
||||
session
|
||||
.insert("csrf_token", csrf_token.secret().clone())
|
||||
.unwrap();
|
||||
session
|
||||
.insert("pkce_verifier", pkce_verifier.secret().clone())
|
||||
.unwrap();
|
||||
session.set("csrf_token", csrf_token.secret().clone());
|
||||
session.set("pkce_verifier", pkce_verifier.secret().clone());
|
||||
|
||||
Redirect::to(auth_url.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn test_login(mut session: WritableSession) -> Redirect {
|
||||
session.insert("user_id", "test-user").unwrap();
|
||||
pub async fn test_login(session: Session<SessionSqlitePool>) -> Redirect {
|
||||
session.set("user_id", "test-user");
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
@@ -65,7 +62,7 @@ pub struct AuthCallbackQuery {
|
||||
pub async fn callback(
|
||||
State(state): State<crate::AppState>,
|
||||
Query(query): Query<AuthCallbackQuery>,
|
||||
mut session: WritableSession,
|
||||
session: Session<SessionSqlitePool>,
|
||||
) -> Redirect {
|
||||
// Verify CSRF token
|
||||
if let Some(stored_csrf) = session.get::<String>("csrf_token") {
|
||||
@@ -99,7 +96,7 @@ pub async fn callback(
|
||||
// For now, assume it's valid and extract sub as user_id
|
||||
let claims = id_token.payload().clone();
|
||||
if let Some(sub) = claims.subject() {
|
||||
session.insert("user_id", sub.to_string()).unwrap();
|
||||
session.set("user_id", sub.to_string());
|
||||
Redirect::to("/")
|
||||
} else {
|
||||
Redirect::to("/?error=no_subject")
|
||||
@@ -153,7 +150,7 @@ async fn async_http_client(
|
||||
|
||||
pub async fn input_post(
|
||||
State(state): State<crate::AppState>,
|
||||
session: ReadableSession,
|
||||
session: Session<SessionSqlitePool>,
|
||||
Form(form): Form<WeightForm>,
|
||||
) -> Result<Html<String>, Redirect> {
|
||||
// Check if user is authenticated
|
||||
|
||||
42
src/lib.rs
42
src/lib.rs
@@ -1,21 +1,47 @@
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
|
||||
use axum::{routing::{get, post}, Router};
|
||||
use axum_sessions::{async_session::MemoryStore, SessionLayer};
|
||||
use oauth2::basic::BasicClient;
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
use axum_session::{SessionConfig, SessionLayer, SessionStore};
|
||||
use axum_session_sqlx::SessionSqlitePool;
|
||||
use sqlx::SqlitePool;
|
||||
use tower_http::services::ServeDir;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub pool: SqlitePool,
|
||||
pub oidc_client: BasicClient,
|
||||
pub oidc_client: oauth2::Client<
|
||||
oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>,
|
||||
oauth2::StandardTokenResponse<oauth2::EmptyExtraTokenFields, oauth2::basic::BasicTokenType>,
|
||||
oauth2::StandardTokenIntrospectionResponse<
|
||||
oauth2::EmptyExtraTokenFields,
|
||||
oauth2::basic::BasicTokenType,
|
||||
>,
|
||||
oauth2::StandardRevocableToken,
|
||||
oauth2::StandardErrorResponse<oauth2::RevocationErrorResponseType>,
|
||||
oauth2::EndpointSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointSet,
|
||||
>,
|
||||
}
|
||||
|
||||
pub fn create_app(state: AppState, session_secret: Vec<u8>) -> Router {
|
||||
let store = MemoryStore::new();
|
||||
let session_layer = SessionLayer::new(store, &session_secret).with_secure(false);
|
||||
pub async fn create_app(state: AppState, session_secret: Vec<u8>, pool: SqlitePool) -> Router {
|
||||
//This Defaults as normal Cookies.
|
||||
//To enable Private cookies for integrity, and authenticity please check the next Example.
|
||||
let session_config = SessionConfig::default()
|
||||
.with_table_name("sessions_table")
|
||||
.with_key(axum_session::Key::from(&session_secret));
|
||||
|
||||
// create SessionStore and initiate the database tables
|
||||
let session_store =
|
||||
SessionStore::<SessionSqlitePool>::new(Some(pool.clone().into()), session_config)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(handlers::index))
|
||||
@@ -23,7 +49,7 @@ pub fn create_app(state: AppState, session_secret: Vec<u8>) -> Router {
|
||||
.route("/auth/callback", get(handlers::callback))
|
||||
.route("/input", post(handlers::input_post))
|
||||
.with_state(state)
|
||||
.layer(session_layer)
|
||||
.layer(SessionLayer::new(session_store))
|
||||
.nest_service("/static", ServeDir::new("static"));
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
58
src/main.rs
58
src/main.rs
@@ -1,32 +1,62 @@
|
||||
use oauth2::{basic::BasicClient, AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl};
|
||||
use oauth2::{AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl, basic::BasicClient};
|
||||
use sqlx::SqlitePool;
|
||||
use std::env;
|
||||
use weight_tracker::{create_app, AppState};
|
||||
use weight_tracker::{AppState, create_app};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// Set up database
|
||||
let database_url = "sqlite:weight_tracker.db";
|
||||
let pool = SqlitePool::connect(database_url).await.expect("Failed to connect to database");
|
||||
let pool = SqlitePool::connect(database_url)
|
||||
.await
|
||||
.expect("Failed to connect to database");
|
||||
|
||||
// Set up OIDC client
|
||||
let client_id = ClientId::new(env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string()));
|
||||
let client_secret = ClientSecret::new(env::var("OIDC_CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string()));
|
||||
let auth_url = AuthUrl::new(env::var("OIDC_AUTH_URL").unwrap_or_else(|_| "https://your-provider.com/auth".to_string())).unwrap();
|
||||
let token_url = TokenUrl::new(env::var("OIDC_TOKEN_URL").unwrap_or_else(|_| "https://your-provider.com/token".to_string())).unwrap();
|
||||
let client_id =
|
||||
ClientId::new(env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string()));
|
||||
let client_secret = ClientSecret::new(
|
||||
env::var("OIDC_CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string()),
|
||||
);
|
||||
let auth_url = AuthUrl::new(
|
||||
env::var("OIDC_AUTH_URL").unwrap_or_else(|_| "https://your-provider.com/auth".to_string()),
|
||||
)
|
||||
.unwrap();
|
||||
let token_url = TokenUrl::new(
|
||||
env::var("OIDC_TOKEN_URL")
|
||||
.unwrap_or_else(|_| "https://your-provider.com/token".to_string()),
|
||||
)
|
||||
.unwrap();
|
||||
let redirect_url = RedirectUrl::new("http://localhost:3000/auth/callback".to_string()).unwrap();
|
||||
|
||||
let oidc_client = BasicClient::new(client_id, Some(client_secret), auth_url, Some(token_url))
|
||||
let oidc_client: oauth2::Client<
|
||||
oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>,
|
||||
oauth2::StandardTokenResponse<oauth2::EmptyExtraTokenFields, oauth2::basic::BasicTokenType>,
|
||||
oauth2::StandardTokenIntrospectionResponse<
|
||||
oauth2::EmptyExtraTokenFields,
|
||||
oauth2::basic::BasicTokenType,
|
||||
>,
|
||||
oauth2::StandardRevocableToken,
|
||||
oauth2::StandardErrorResponse<oauth2::RevocationErrorResponseType>,
|
||||
oauth2::EndpointSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointSet,
|
||||
> = BasicClient::new(client_id)
|
||||
.set_client_secret(client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
// Set the URL the user will be redirected to after the authorization process.
|
||||
.set_redirect_uri(redirect_url);
|
||||
|
||||
let secret = env::var("SESSION_SECRET").unwrap_or_else(|_| "your_secret_key".to_string()).as_bytes().to_vec();
|
||||
let secret = env::var("SESSION_SECRET")
|
||||
.unwrap_or_else(|_| "your_secret_key".to_string())
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
|
||||
let app_state = AppState {
|
||||
pool,
|
||||
oidc_client,
|
||||
};
|
||||
let app_state = AppState { pool, oidc_client };
|
||||
|
||||
let app = create_app(app_state, secret);
|
||||
let app = create_app(app_state, secret, pool.clone()).await;
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
||||
.await
|
||||
|
||||
Reference in New Issue
Block a user