Update to newest versions of all crates

This commit is contained in:
Chris Jean-Marie 2024-09-18 23:42:50 -04:00
parent da8582a02f
commit 00225a2f09
8 changed files with 1086 additions and 1296 deletions

57
.vscode/launch.json vendored
View File

@ -5,40 +5,41 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "Debug Game",
"preLaunchTask": "godot-rust: Build Debug",
"type": "lldb", "type": "lldb",
"request": "launch", "request": "launch",
"program": "${config:godot-rust.environment.godotEditorPath}", "name": "Debug executable 'jean-marie'",
"cwd": "${config:godot-rust.environment.godotProjectPath}", "cargo": {
"presentation": { "args": [
"group": "Debug", "build",
"order": 1 "--bin=jean-marie",
} "--package=jean-marie"
],
"filter": {
"name": "jean-marie",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}, },
{ {
"name": "Release Game",
"preLaunchTask": "godot-rust: Build Release",
"type": "lldb", "type": "lldb",
"request": "launch", "request": "launch",
"program": "${config:godot-rust.environment.godotEditorPath}", "name": "Debug unit tests in executable 'jean-marie'",
"cwd": "${config:godot-rust.environment.godotProjectPath}", "cargo": {
"presentation": { "args": [
"group": "Debug", "test",
"order": 2 "--no-run",
} "--bin=jean-marie",
}, "--package=jean-marie"
{ ],
"name": "Attach to Game", "filter": {
"pid": "${command:pickMyProcess}", "name": "jean-marie",
"type": "lldb", "kind": "bin"
"request": "attach", }
"program": "${config:godot-rust.environment.godotEditorPath}", },
"port": 6007, "args": [],
"presentation": { "cwd": "${workspaceFolder}"
"group": "Debug",
"order": 3
}
} }
] ]
} }

2155
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +1,27 @@
[package] [package]
name = "jean-marie" name = "jean-marie"
version = "0.1.0" version = "0.1.1"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# Update all dependencies with `cargo upgrade -i allow && cargo update`
[dependencies] [dependencies]
axum = { version = "0.5.16", features = ["headers"] } axum = { version = "0.7.5" }
axum_database_sessions = { version = "4.1.0", features = [ "postgres-rustls"] } axum_session = { version = "0.14.2" }
axum-server = { version = "0.7.1" }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.68" #serde_json = "1.0.68"
tokio = { version = "1.0", features = ["full"] } tokio = { version = "1.40", features = ["full"] }
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version="0.3", features = ["env-filter"] } tracing-subscriber = { version="0.3", features = ["env-filter"] }
uuid = { version = "1.1.2", features = ["v4", "serde"] } #uuid = { version = "1.1.2", features = ["v4", "serde"] }
async-session = "3.0.0" #async-session = "3.0.0"
askama = "0.11" askama = "0.12"
oauth2 = "4.1" oauth2 = "4.4"
reqwest = { version = "0.11", default-features = false, features = ["rustls-tls", "json"] } #reqwest = { version = "0.11", default-features = false, features = ["rustls-tls", "json"] }
headers = "0.3" #headers = "0.3"
http = "0.2" http = "1.1"
tower-http = { version = "0.3.4", features = ["full"] } tower-http = { version = "0.5.2", features = ["full"] }
sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "postgres", "macros", "migrate", "chrono", "json"]} #sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "postgres", "macros", "migrate", "chrono", "json"]}
anyhow = "1.0" #anyhow = "1.0"

0
run.sh Executable file → Normal file
View File

0
runprod.sh Executable file → Normal file
View File

View File

@ -1,9 +1,10 @@
use async_session::{MemoryStore, Session, SessionStore as _}; use axum_session::{Session, SessionAnyPool, SessionConfig, SessionStore, SessionLayer};
use axum::{ use axum::{
extract::{Extension, Query}, extract::{Extension, Query},
http::header::{HeaderMap, SET_COOKIE}, http::header::{HeaderMap, SET_COOKIE},
response::{IntoResponse, Redirect}, response::{IntoResponse, Redirect},
}; };
use axum_server;
use oauth2::{ use oauth2::{
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId, basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenUrl, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenUrl,
@ -11,9 +12,6 @@ use oauth2::{
use serde::Deserialize; use serde::Deserialize;
use std::{collections::HashMap, env}; use std::{collections::HashMap, env};
// use crate::User;
use crate::COOKIE_NAME;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[allow(dead_code)] #[allow(dead_code)]
pub struct AuthRequest { pub struct AuthRequest {
@ -40,22 +38,23 @@ pub async fn google_auth() -> impl IntoResponse {
Redirect::to(&auth_url.to_string()) Redirect::to(&auth_url.to_string())
} }
pub async fn google_authorized( pub async fn google_authorized(session: Session<SessionAnyPool>,
Query(query): Query<AuthRequest>, Query(query): Query<AuthRequest>,
Extension(store): Extension<MemoryStore>, // Extension(oauth_clients): Extension<HashMap<&str, BasicClient>>,
Extension(oauth_clients): Extension<HashMap<&str, BasicClient>>,
) -> impl IntoResponse { ) -> impl IntoResponse {
// Check for Google client // Check for Google client
if oauth_clients.contains_key("Google") { // if oauth_clients.contains_key("Google") {
// Get Google client
let google_oauth_client = oauth_clients.get(&"Google").unwrap(); println!("{:?}", query);
// Get an auth token // Get an auth token
let token = google_oauth_client //let token = match google_oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone())) //.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(async_http_client) //.request_async(async_http_client)
.await //.await {
.unwrap(); // Ok(token) => token,
// Err(_) => panic!("Didn't get a token"),
// };
/* /*
// Fetch user data from google // Fetch user data from google
let client = reqwest::Client::new(); let client = reqwest::Client::new();
@ -71,22 +70,8 @@ pub async fn google_authorized(
.unwrap(); .unwrap();
*/ */
// Create a new session filled with user data
let session = Session::new();
//session.insert("user", &user_data).unwrap();
// Store session and get corresponding cookie
let cookie = store.store_session(session).await.unwrap().unwrap();
// Build the cookie
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
// Set cookie
let mut headers = HeaderMap::new();
headers.insert(SET_COOKIE, cookie.parse().unwrap());
//(headers, Redirect::to("/dashboard".parse().unwrap())) //(headers, Redirect::to("/dashboard".parse().unwrap()))
} // }
let mut page = String::new(); let mut page = String::new();
page.push_str(&"Display the data returned by Google\n".to_string()); page.push_str(&"Display the data returned by Google\n".to_string());
@ -100,6 +85,13 @@ pub async fn google_authorized(
} }
pub fn google_oauth_client() -> BasicClient { pub fn google_oauth_client() -> BasicClient {
if std::env::var_os("GOOGLE_CLIENT_ID").is_none() {
std::env::set_var("GOOGLE_CLIENT_ID", "735264084619-clsmvgdqdmum4rvrcj0kuk28k9agir1c.apps.googleusercontent.com")
}
if std::env::var_os("GOOGLE_CLIENT_SECRET").is_none() {
std::env::set_var("GOOGLE_CLIENT_SECRET", "L6uI7FQGoMJd-ay1HO_iGJ6M")
}
let redirect_url = env::var("REDIRECT_URL") let redirect_url = env::var("REDIRECT_URL")
.unwrap_or_else(|_| "http://localhost:40192/auth/google".to_string()); .unwrap_or_else(|_| "http://localhost:40192/auth/google".to_string());
// .unwrap_or_else(|_| "https://www.jean-marie.ca/auth/google".to_string()); // .unwrap_or_else(|_| "https://www.jean-marie.ca/auth/google".to_string());

View File

@ -1,14 +1,18 @@
use std::net::SocketAddr; use std::{net::SocketAddr, collections::HashMap};
use askama::Template; use askama::Template;
use axum_database_sessions::{AxumSession, AxumPgPool, AxumSessionConfig, AxumSessionStore, AxumSessionLayer}; use axum_session::{Session, SessionAnyPool, SessionConfig, SessionStore, SessionLayer};
use axum::{ use axum::{
Router, Router,
routing::{get, get_service}, response::{Html, IntoResponse, Response} routing::{get, get_service}, response::{Html, IntoResponse, Response}, Extension
}; };
use http::StatusCode; use http::StatusCode;
use oauth2::basic::BasicClient;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
mod google_oauth;
use google_oauth::*;
struct HtmlTemplate<T>(T); struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T> impl<T> IntoResponse for HtmlTemplate<T>
@ -54,64 +58,70 @@ async fn main() {
// initialize tracing // initialize tracing
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
let session_config = AxumSessionConfig::default() let session_config = SessionConfig::default()
.with_table_name("sessions"); .with_table_name("sessions");
let session_store = AxumSessionStore::<AxumPgPool>::new(None, session_config); let session_store = SessionStore::<SessionAnyPool>::new(None, session_config).await.unwrap();
session_store.initiate().await.unwrap();
// Create HashMap to store oauth configurations
// let mut oauth_clients = HashMap::<&str, BasicClient>::new();
// Get the client structures
// let facebook_oauth_client = facebook_oauth_client();
// let discord_oauth_client = discord_oauth_client();
// let google_oauth_client = google_oauth_client();
// Get oauth clients for the hashmap
// oauth_clients.insert("Facebook", facebook_oauth_client);
// oauth_clients.insert("Discord", discord_oauth_client);
// oauth_clients.insert("Google", google_oauth_client);
// build our application with some routes // build our application with some routes
let app = Router::new() let app = Router::new()
.nest( .route("/assets", get_service(ServeDir::new("templates/assets"))
"/assets", // .handle_error(
get_service(ServeDir::new("templates/assets")).handle_error( // |error: std::io::Error| async move {
|error: std::io::Error| async move { // (
( // StatusCode::INTERNAL_SERVER_ERROR,
StatusCode::INTERNAL_SERVER_ERROR, // format!("Unhandled internal error: {}", error),
format!("Unhandled internal error: {}", error), // )
) // },
}, // ),
),
) )
.route("/", get(index)) .route("/", get(index))
.route("/login", get(login)) .route("/login", get(login))
.layer(AxumSessionLayer::new(session_store)); .route("/google_auth", get(google_auth))
.route("/auth/google", get(google_authorized))
.layer(SessionLayer::new(session_store))
// .layer(Extension(oauth_clients));
;
// run it // run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let addr = SocketAddr::from(([127, 0, 0, 1], 40192));
tracing::debug!("listening on {}", addr); tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr) axum_server::bind(addr)
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
.unwrap(); .unwrap();
} }
async fn index(session: AxumSession<AxumPgPool>) -> impl IntoResponse { async fn index(session: Session<SessionAnyPool>) -> impl IntoResponse {
let logged_in = session.get("logged_in").await.unwrap_or(false); let logged_in = session.get("logged_in").unwrap_or(false);
let name = session.get("name").await.unwrap_or("You're not logged in.".to_string()); let name = session.get("name").unwrap_or("You're not logged in.".to_string());
let template = IndexTemplate { logged_in, name}; let template = IndexTemplate { logged_in, name};
HtmlTemplate(template) HtmlTemplate(template)
} }
async fn login(session: AxumSession<AxumPgPool>) -> impl IntoResponse { async fn login(session: Session<SessionAnyPool>) -> impl IntoResponse {
let logged_in = session.get("logged_in").await.unwrap_or(false); let logged_in = session.get("logged_in").unwrap_or(false);
let name = session.get("name").await.unwrap_or("".to_string()); let name = session.get("name").unwrap_or("".to_string());
session.set_store(true).await; session.set_store(true);
session.set("logged_in", logged_in);
session.set("name", &name);
let template = LoginTemplate { logged_in, name }; let template = LoginTemplate { logged_in, name };
HtmlTemplate(template) HtmlTemplate(template)
} }
//No need to set the sessions accepted or not with gdpr mode disabled
async fn greet(session: AxumSession<AxumPgPool>) -> String {
let mut count: usize = session.get("count").await.unwrap_or(0);
// Allow the Session data to be keep in memory and the database for the lifetime.
session.set_store(true).await;
count += 1;
session.set("count", count).await;
count.to_string()
}