From e888ef09482f51a490fd1ccf2bf6734839e0a34d Mon Sep 17 00:00:00 2001 From: AINDUSTRIES Date: Sat, 18 Jul 2026 00:30:56 -0400 Subject: [PATCH] Proper user authentication --- .../20260714035817_create_table_users.sql | 4 +- src/error.rs | 29 ++++ src/main.rs | 15 +- src/users.rs | 133 ++++++++++++------ 4 files changed, 137 insertions(+), 44 deletions(-) create mode 100644 src/error.rs diff --git a/migrations/20260714035817_create_table_users.sql b/migrations/20260714035817_create_table_users.sql index 9ddb260..2d7b15f 100644 --- a/migrations/20260714035817_create_table_users.sql +++ b/migrations/20260714035817_create_table_users.sql @@ -1,6 +1,6 @@ CREATE TABLE IF NOT EXISTS users ( id uuid DEFAULT gen_random_uuid() PRIMARY KEY, steamid char(64) NOT NULL, - name varchar(5) NOT NULL, - avatar varchar(20) NOT NULL + name varchar NOT NULL, + avatar varchar NOT NULL ); \ No newline at end of file diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..9286782 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,29 @@ +use std::error::Error; + +use axum::response::IntoResponse; +use reqwest::StatusCode; + +pub enum AppError { + InternalError(String), +} + +impl IntoResponse for AppError { + fn into_response(self) -> axum::response::Response { + let (status, message) = match self { + AppError::InternalError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg), + }; + (status, message).into_response() + } +} + +impl From> for AppError { + fn from(value: Box) -> Self { + AppError::InternalError(value.to_string()) + } +} + +impl From for AppError { + fn from(value: tower_sessions::session::Error) -> Self { + AppError::InternalError(value.to_string()) + } +} diff --git a/src/main.rs b/src/main.rs index c0d6921..cb47787 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,25 +8,38 @@ use dotenvy::dotenv; use sqlx::postgres::PgPool; use tokio::net::TcpListener; use tower_http::cors::CorsLayer; +use tower_sessions::cookie::SameSite; +use tower_sessions::{SessionManagerLayer}; +use tower_sessions_sqlx_store::PostgresStore; +use tower_sessions_sqlx_store::sqlx::PgPool as SessionPgPool; +mod error; mod users; -use users::{login, me}; +use users::{login, me, logout}; #[tokio::main] async fn main() -> Result<(), Box> { dotenv()?; let db_url = var("DATABASE_URL")?; let pool = PgPool::connect(&db_url).await?; + let session_pool = SessionPgPool::connect(&db_url).await?; + let session_store = PostgresStore::new(session_pool); + session_store.migrate().await?; + let session = SessionManagerLayer::new(session_store) + .with_secure(false) + .with_same_site(SameSite::Lax); let app = Router::new() .route("/status", get(status)) .route("/me", get(me)) .route("/login", get(login)) + .route("/logout", get(logout)) .layer( CorsLayer::new() .allow_origin("http://localhost:5173".parse::().unwrap()) .allow_methods([Method::GET]) .allow_credentials(true), ) + .layer(session) .with_state(pool); let listener = TcpListener::bind("0.0.0.0:8080").await?; Ok(serve(listener, app).await?) diff --git a/src/users.rs b/src/users.rs index 0941da0..c9b10e1 100644 --- a/src/users.rs +++ b/src/users.rs @@ -3,11 +3,12 @@ use std::error::Error; use axum::{ Json, extract::{Query, State}, - http::StatusCode, }; -use axum_extra::extract::CookieJar; use serde::{Deserialize, Serialize}; -use sqlx::{PgPool, query, types::Uuid}; +use sqlx::{PgPool, query, query_as, query_scalar, types::Uuid}; +use tower_sessions::Session; + +use crate::error::AppError; #[derive(Deserialize, Serialize)] pub struct User { @@ -30,26 +31,27 @@ impl User { } } - async fn create(self, pool: PgPool) -> Result<(), Box> { - query!( - "INSERT INTO users (steamid, name, avatar) VALUES ($1, $2, $3)", + async fn create(&mut self, pool: &PgPool) -> Result<(), Box> { + let uuid: Uuid = query_scalar!( + "INSERT INTO users (steamid, name, avatar) VALUES ($1, $2, $3) RETURNING id", self.steamid, self.name, self.avatar ) - .execute(&pool) + .fetch_one(pool) .await?; + self.id = uuid; Ok(()) } - async fn delete(self, pool: PgPool) -> Result<(), Box> { + async fn delete(&self, pool: &PgPool) -> Result<(), Box> { query!("DELETE FROM users WHERE id=$1", self.id) - .execute(&pool) + .execute(pool) .await?; Ok(()) } - async fn update(self, pool: PgPool) -> Result<(), Box> { + async fn update(&self, pool: &PgPool) -> Result<(), Box> { query!( "UPDATE users SET steamid=$1, name=$2, avatar=$3 WHERE id=$4", self.steamid, @@ -57,24 +59,46 @@ impl User { self.avatar, self.id ) - .execute(&pool) + .execute(pool) .await?; Ok(()) } -} -#[axum::debug_handler] -pub async fn me(State(pool): State, jar: CookieJar) -> Json> { - if let Some(cookie) = jar.get("token") { - println!("Cookie received: {cookie}"); - Json(Some(User::new( - "76561198840243902", - "p0rning AINDUSTRIES", - "https://avatars.steamstatic.com/c6975c06a7a7cb874c8f95ed5a10c8a25c936a6b_full.jpg", - ))) - } else { - println!("No cookie received"); - Json(None) + async fn fetch_id(pool: &PgPool, uuid: Uuid) -> Result> { + Ok(query_as!(User, "SELECT * FROM users WHERE id=$1", uuid) + .fetch_one(pool) + .await?) + } + + async fn steamid_exists(pool: &PgPool, steamid: &String) -> Result> { + match query!("SELECT id FROM users WHERE steamid=$1", steamid) + .fetch_optional(pool) + .await? + { + Some(_) => Ok(true), + None => Ok(false), + } + } + + async fn from_steamid(pool: &PgPool, steamid: String) -> Result> { + if User::steamid_exists(pool, &steamid).await? { + let user = query_as!(User, "SELECT * FROM users WHERE steamid=$1", steamid) + .fetch_one(pool) + .await?; + return Ok(user); + } + + let response = reqwest::get(format!("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=ABBFE30D7BDC1FD582DB1A2CEBD563B4&steamids={steamid}")) + .await?.bytes().await?; + let json: serde_json::Value = serde_json::from_slice(&response)?; + let raw_user = &json["response"]["players"][0]; + let mut user = User::new( + raw_user["steamid"].to_string().trim_matches('"'), + raw_user["personaname"].to_string().trim_matches('"'), + raw_user["avatarfull"].to_string().trim_matches('"'), + ); + user.create(pool).await?; + Ok(user) } } @@ -111,26 +135,53 @@ pub struct OpenId { sig: String, } +impl OpenId { + pub async fn is_valid(&mut self) -> Result> { + self.mode = "check_authentication".into(); + let url_encoded = serde_urlencoded::to_string(self)?; + + let response = reqwest::get(format!( + "https://steamcommunity.com/openid/login?{url_encoded}" + )) + .await? + .text() + .await?; + + Ok(response.contains("is_valid:true")) + } +} + #[axum::debug_handler] pub async fn login( State(pool): State, Query(mut info): Query, -) -> Result { - info.mode = "check_authentication".into(); - if let Ok(url_encoded) = serde_urlencoded::to_string(info) { - println!("https://steamcommunity.com/openid/login?{url_encoded}"); - let response = reqwest::get(format!( - "https://steamcommunity.com/openid/login?{url_encoded}" - )) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - .text() - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - println!("{response}"); - if response.contains("is_valid:true") { - return Ok("ok".to_string()); - } + session: Session, +) -> Result<&'static str, AppError> { + if !info.is_valid().await? { + return Ok("nok"); + } + let steamid = info + .identity + .replace("https://steamcommunity.com/openid/id/", ""); + let user = User::from_steamid(&pool, steamid).await?; + session.insert("uuid", user.id).await?; + Ok("ok") +} + +pub async fn logout(session: Session) -> Result<(), AppError> { + session.delete().await?; + Ok(()) +} + +#[axum::debug_handler] +pub async fn me( + State(pool): State, + session: Session, +) -> Result>, AppError> { + if let Some(uuid) = session.get("uuid").await? { + let user = User::fetch_id(&pool, uuid).await?; + Ok(Json(Some(user))) + } else { + Ok(Json(None)) } - Ok("nok".to_string()) }