Compare commits
20 Commits
82077a2e09
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e7f5f393a5 | |||
| 746b01000c | |||
| 84d44f9535 | |||
| 6df96285a2 | |||
| 464fbde1b9 | |||
| 74449fd78b | |||
| a8434a5c9b | |||
| a387718b57 | |||
| 3b63fe94a7 | |||
| 404031f771 | |||
| 8aac11e370 | |||
| 7ef7983ee8 | |||
| ea4dffbdc6 | |||
| e1652f4b07 | |||
| d78de75c5e | |||
| 2a029709b8 | |||
| 27b954a5ec | |||
| d18d59054a | |||
| abfc02b972 | |||
| e888ef0948 |
720
Cargo.lock
generated
720
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sqlx = {version = "0.9.0", features = ["runtime-tokio", "postgres", "macros", "uuid"]}
|
sqlx = {version = "0.8.6", features = ["runtime-tokio", "postgres", "macros", "uuid"]}
|
||||||
axum = {version = "0.8.9", features = ["macros"]}
|
axum = {version = "0.8.9", features = ["macros"]}
|
||||||
tokio = {version = "1.52.3", features = ["full"]}
|
tokio = {version = "1.52.3", features = ["full"]}
|
||||||
tower = "0.5.3"
|
tower = "0.5.3"
|
||||||
@@ -15,3 +15,7 @@ uuid = {version = "1.23.5", features = ["serde"]}
|
|||||||
tower-http = {version = "0.7.0", features = ["cors"]}
|
tower-http = {version = "0.7.0", features = ["cors"]}
|
||||||
reqwest = "0.13.4"
|
reqwest = "0.13.4"
|
||||||
serde_urlencoded = "0.7.1"
|
serde_urlencoded = "0.7.1"
|
||||||
|
serde_json = "1.0.150"
|
||||||
|
tower-sessions = "0.14.0"
|
||||||
|
tower-sessions-sqlx-store = {version = "0.15.0", features = ["postgres"]}
|
||||||
|
http = "1.5.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
steamid char(64) NOT NULL,
|
steamid char(64) NOT NULL,
|
||||||
name varchar(5) NOT NULL,
|
name varchar NOT NULL,
|
||||||
avatar varchar(20) NOT NULL
|
avatar varchar NOT NULL
|
||||||
);
|
);
|
||||||
37
migrations/20260831172036_create_table_skins.sql
Normal file
37
migrations/20260831172036_create_table_skins.sql
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS weapons (
|
||||||
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
name varchar NOT NULL,
|
||||||
|
display varchar NOT NULL,
|
||||||
|
def_index integer NOT NULL,
|
||||||
|
category varchar NOT NULL,
|
||||||
|
team integer NOT NULL -- 0 = CT, 1 = T, 2 = BOTH
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS rarity (
|
||||||
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
display varchar NOT NULL,
|
||||||
|
color varchar NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS skins (
|
||||||
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
weapon uuid REFERENCES weapons(id) NOT NULL,
|
||||||
|
rarity uuid REFERENCES rarity(id) NOT NULL,
|
||||||
|
paint_index integer NOT NULL,
|
||||||
|
display varchar NOT NULL,
|
||||||
|
min_float float NOT NULL,
|
||||||
|
max_float float NOT NULL,
|
||||||
|
legacy boolean NOT NULL,
|
||||||
|
"default" boolean DEFAULT false NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS agents (
|
||||||
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
rarity uuid REFERENCES rarity(id) NOT NULL,
|
||||||
|
name varchar NOT NULL,
|
||||||
|
display varchar NOT NULL,
|
||||||
|
def_index integer NOT NULL,
|
||||||
|
team integer NOT NULL, -- 0 = CT, 1 = T, 2 = BOTH
|
||||||
|
model_player varchar NOT NULL,
|
||||||
|
"default" boolean DEFAULT false NOT NULL
|
||||||
|
);
|
||||||
9
migrations/20260901220106_create_table_user-skins.sql
Normal file
9
migrations/20260901220106_create_table_user-skins.sql
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS user_skins (
|
||||||
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
user_id uuid REFERENCES users(id) NOT NULL,
|
||||||
|
skin_id uuid REFERENCES skins(id),
|
||||||
|
agent_id uuid REFERENCES agents(id),
|
||||||
|
float float DEFAULT 0 NOT NULL,
|
||||||
|
pattern integer DEFAULT 0 NOT NULL,
|
||||||
|
team integer NOT NULL -- 0 = CT, 1 = T, 2 = BOTH
|
||||||
|
);
|
||||||
42
src/error.rs
Normal file
42
src/error.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use reqwest::StatusCode;
|
||||||
|
|
||||||
|
pub enum AppError {
|
||||||
|
InternalError(String),
|
||||||
|
OpenIdError(String),
|
||||||
|
Unauthorised,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for AppError {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let (status, message) = match self {
|
||||||
|
AppError::InternalError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg),
|
||||||
|
AppError::OpenIdError(msg) => (StatusCode::UNPROCESSABLE_ENTITY, msg),
|
||||||
|
AppError::Unauthorised => (
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
"Unauthorised (did you login?)".into(),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
(status, message).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Box<dyn Error>> for AppError {
|
||||||
|
fn from(value: Box<dyn Error>) -> Self {
|
||||||
|
AppError::InternalError(value.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<tower_sessions::session::Error> for AppError {
|
||||||
|
fn from(value: tower_sessions::session::Error) -> Self {
|
||||||
|
AppError::InternalError(value.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for AppError {
|
||||||
|
fn from(value: sqlx::Error) -> Self {
|
||||||
|
AppError::InternalError(value.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
35
src/main.rs
35
src/main.rs
@@ -2,36 +2,59 @@ use std::env::var;
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
use axum::http::{HeaderValue, Method};
|
use axum::http::{HeaderValue, Method};
|
||||||
use axum::routing::get;
|
use axum::routing::{get, post};
|
||||||
use axum::{Router, serve};
|
use axum::{Router, serve};
|
||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
|
use http::header::CONTENT_TYPE;
|
||||||
use sqlx::postgres::PgPool;
|
use sqlx::postgres::PgPool;
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
use tower_http::cors::CorsLayer;
|
use tower_http::cors::CorsLayer;
|
||||||
|
use tower_sessions::SessionManagerLayer;
|
||||||
|
use tower_sessions::cookie::SameSite;
|
||||||
|
use tower_sessions_sqlx_store::PostgresStore;
|
||||||
|
use tower_sessions_sqlx_store::sqlx::PgPool as SessionPgPool;
|
||||||
|
|
||||||
|
mod error;
|
||||||
|
mod skins;
|
||||||
mod users;
|
mod users;
|
||||||
use users::{login, me};
|
use skins::{agent_info, list_paint_index, skin_info, weapons};
|
||||||
|
use users::{login, logout, me, reload, update};
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn Error>> {
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
dotenv()?;
|
dotenv()?;
|
||||||
let db_url = var("DATABASE_URL")?;
|
let db_url = var("DATABASE_URL")?;
|
||||||
let pool = PgPool::connect(&db_url).await?;
|
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()
|
let app = Router::new()
|
||||||
.route("/status", get(status))
|
.route("/status", get(status))
|
||||||
.route("/me", get(me))
|
.route("/me", get(me))
|
||||||
.route("/login", get(login))
|
.route("/login", get(login))
|
||||||
|
.route("/logout", get(logout))
|
||||||
|
.route("/update", post(update))
|
||||||
|
.route("/reload", get(reload))
|
||||||
|
.route("/weapons", get(weapons))
|
||||||
|
.route("/skin", get(skin_info))
|
||||||
|
.route("/agent", get(agent_info))
|
||||||
|
.route("/index", get(list_paint_index))
|
||||||
.layer(
|
.layer(
|
||||||
CorsLayer::new()
|
CorsLayer::new()
|
||||||
.allow_origin("http://localhost:5173".parse::<HeaderValue>().unwrap())
|
.allow_origin("http://localhost:5173".parse::<HeaderValue>().unwrap())
|
||||||
.allow_methods([Method::GET])
|
.allow_methods([Method::GET, Method::POST])
|
||||||
.allow_credentials(true),
|
.allow_credentials(true)
|
||||||
|
.allow_headers([CONTENT_TYPE]),
|
||||||
)
|
)
|
||||||
|
.layer(session)
|
||||||
.with_state(pool);
|
.with_state(pool);
|
||||||
let listener = TcpListener::bind("0.0.0.0:8080").await?;
|
let listener = TcpListener::bind(var("BIND_ADDRESS")?).await?;
|
||||||
Ok(serve(listener, app).await?)
|
Ok(serve(listener, app).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn status() -> &'static str {
|
async fn status() -> &'static str {
|
||||||
"api online"
|
"API online"
|
||||||
}
|
}
|
||||||
|
|||||||
311
src/skins.rs
Normal file
311
src/skins.rs
Normal file
@@ -0,0 +1,311 @@
|
|||||||
|
use axum::{
|
||||||
|
Json, debug_handler,
|
||||||
|
extract::{Query, State},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sqlx::{PgPool, query, query_as, types::Uuid};
|
||||||
|
use tower_sessions::Session;
|
||||||
|
|
||||||
|
use crate::error::AppError;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub struct Weapon {
|
||||||
|
id: Uuid,
|
||||||
|
name: String,
|
||||||
|
display: String,
|
||||||
|
def_index: i32,
|
||||||
|
category: String,
|
||||||
|
team: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub struct SkinInfo {
|
||||||
|
id: Uuid,
|
||||||
|
weapon_id: Uuid,
|
||||||
|
name: String,
|
||||||
|
display: String,
|
||||||
|
paint_index: i32,
|
||||||
|
color: String,
|
||||||
|
float: f64,
|
||||||
|
min_float: f64,
|
||||||
|
max_float: f64,
|
||||||
|
pattern: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
pub async fn weapons(State(pool): State<PgPool>) -> Result<Json<Vec<Weapon>>, AppError> {
|
||||||
|
let weapons = query_as!(Weapon, "SELECT * FROM weapons")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await?;
|
||||||
|
Ok(Json(weapons))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
|
||||||
|
enum Teams {
|
||||||
|
CT,
|
||||||
|
T,
|
||||||
|
BOTH,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Teams {
|
||||||
|
fn as_i32(self) -> i32 {
|
||||||
|
match self {
|
||||||
|
Teams::CT => 0,
|
||||||
|
Teams::T => 1,
|
||||||
|
Teams::BOTH => 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
|
||||||
|
enum Categories {
|
||||||
|
Knives,
|
||||||
|
Gloves,
|
||||||
|
Rifles,
|
||||||
|
SMGs,
|
||||||
|
Pistols,
|
||||||
|
Heavy,
|
||||||
|
Equipment,
|
||||||
|
Weapons, // Special category to get all weapons except gloves and knives
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Categories {
|
||||||
|
fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Categories::Knives => "Knives",
|
||||||
|
Categories::Gloves => "Gloves",
|
||||||
|
Categories::Rifles => "Rifles",
|
||||||
|
Categories::SMGs => "SMGs",
|
||||||
|
Categories::Pistols => "Pistols",
|
||||||
|
Categories::Heavy => "Heavy",
|
||||||
|
Categories::Equipment => "Equipment",
|
||||||
|
Categories::Weapons => "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub struct SkinInfoQuery {
|
||||||
|
category: Option<Categories>,
|
||||||
|
team: Option<Teams>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn skin_info(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
session: Session,
|
||||||
|
Query(info_query): Query<SkinInfoQuery>,
|
||||||
|
) -> Result<Json<Vec<SkinInfo>>, AppError> {
|
||||||
|
if let Some(uuid) = session.get::<Uuid>("uuid").await? {
|
||||||
|
// Fetch all default skins
|
||||||
|
let mut default_skins = query!("SELECT w.id, w.name, w.display, w.team, w.category, w.display as wd, s.display as sd, r.color FROM skins s JOIN weapons w ON w.id = s.weapon JOIN rarity r ON r.id = s.rarity WHERE s.default = true").fetch_all(&pool).await?;
|
||||||
|
// Filter those skins by team if present in query
|
||||||
|
if let Some(team) = info_query.team {
|
||||||
|
default_skins = default_skins
|
||||||
|
.into_iter()
|
||||||
|
.filter(|x| team.as_i32() == x.team || Teams::BOTH.as_i32() == x.team)
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
// Same with category
|
||||||
|
if let Some(category) = info_query.category {
|
||||||
|
default_skins = match category {
|
||||||
|
Categories::Weapons => default_skins
|
||||||
|
.into_iter()
|
||||||
|
.filter(|x| {
|
||||||
|
![Categories::Gloves.as_str(), Categories::Knives.as_str()]
|
||||||
|
.contains(&x.category.as_str())
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
_ => default_skins
|
||||||
|
.into_iter()
|
||||||
|
.filter(|x| category.as_str() == x.category)
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// For each remaining default weapon, see if the user has set a skin
|
||||||
|
// Secific cases for Knives and Gloves
|
||||||
|
let mut skin_infos = vec![];
|
||||||
|
for default in default_skins {
|
||||||
|
struct Info {
|
||||||
|
id: Uuid,
|
||||||
|
weapon_id: Uuid,
|
||||||
|
float: f64,
|
||||||
|
min_float: f64,
|
||||||
|
max_float: f64,
|
||||||
|
pattern: i32,
|
||||||
|
team: i32,
|
||||||
|
name: String,
|
||||||
|
wd: String,
|
||||||
|
sd: String,
|
||||||
|
paint_index: i32,
|
||||||
|
color: String,
|
||||||
|
}
|
||||||
|
let user_skin = match default.category.as_str() {
|
||||||
|
"Gloves" | "Knives" => {
|
||||||
|
query_as!(Info, "SELECT us.id, w.id as weapon_id, us.float, us.pattern, us.team, w.name, w.display as wd, s.display as sd, s.paint_index, s.min_float, s.max_float, r.color FROM user_skins us JOIN skins s ON us.skin_id = s.id JOIN weapons w ON s.weapon = w.id JOIN rarity r ON r.id = s.rarity WHERE us.user_id = $1 AND w.category = $2", uuid, default.category).fetch_all(&pool).await?
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
query_as!(Info, "SELECT us.id, w.id as weapon_id, us.float, us.pattern, us.team, w.name, w.display as wd, s.display as sd, s.paint_index, s.min_float, s.max_float, r.color FROM user_skins us JOIN skins s ON us.skin_id = s.id JOIN weapons w ON s.weapon = w.id JOIN rarity r ON r.id = s.rarity WHERE us.user_id = $1 AND w.id = $2", uuid, default.id).fetch_all(&pool).await?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let user_skin = if let Some(team) = info_query.team {
|
||||||
|
user_skin
|
||||||
|
.into_iter()
|
||||||
|
.filter(|x| x.team == team.as_i32() || x.team == Teams::BOTH.as_i32())
|
||||||
|
.min_by(|x, y| x.team.cmp(&y.team))
|
||||||
|
.unwrap_or(Info {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
weapon_id: default.id,
|
||||||
|
float: 0.0,
|
||||||
|
min_float: 0.0,
|
||||||
|
max_float: 1.0,
|
||||||
|
pattern: 0,
|
||||||
|
team: 2,
|
||||||
|
name: default.name,
|
||||||
|
wd: default.wd,
|
||||||
|
sd: default.sd,
|
||||||
|
paint_index: 0,
|
||||||
|
color: default.color,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
user_skin
|
||||||
|
.into_iter()
|
||||||
|
.max_by(|x, y| x.team.cmp(&y.team))
|
||||||
|
.unwrap_or(Info {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
weapon_id: default.id,
|
||||||
|
float: 0.0,
|
||||||
|
min_float: 0.0,
|
||||||
|
max_float: 1.0,
|
||||||
|
pattern: 0,
|
||||||
|
team: 2,
|
||||||
|
name: default.name,
|
||||||
|
wd: default.wd,
|
||||||
|
sd: default.sd,
|
||||||
|
paint_index: 0,
|
||||||
|
color: default.color,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let display = if user_skin.sd.is_empty() {
|
||||||
|
user_skin.wd
|
||||||
|
} else {
|
||||||
|
format!("{} | {}", user_skin.wd, user_skin.sd)
|
||||||
|
};
|
||||||
|
let info = SkinInfo {
|
||||||
|
display,
|
||||||
|
id: user_skin.id,
|
||||||
|
weapon_id: user_skin.weapon_id,
|
||||||
|
name: user_skin.name,
|
||||||
|
paint_index: user_skin.paint_index,
|
||||||
|
color: user_skin.color,
|
||||||
|
float: user_skin.float,
|
||||||
|
min_float: user_skin.min_float,
|
||||||
|
max_float: user_skin.max_float,
|
||||||
|
pattern: user_skin.pattern,
|
||||||
|
};
|
||||||
|
skin_infos.push(info);
|
||||||
|
}
|
||||||
|
Ok(Json(skin_infos))
|
||||||
|
} else {
|
||||||
|
Err(AppError::Unauthorised)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub struct AgentInfoQuery {
|
||||||
|
team: Teams,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[debug_handler]
|
||||||
|
pub async fn agent_info(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
session: Session,
|
||||||
|
Query(info_query): Query<AgentInfoQuery>,
|
||||||
|
) -> Result<Json<SkinInfo>, AppError> {
|
||||||
|
if let Some(uuid) = session.get::<Uuid>("uuid").await? {
|
||||||
|
let agent = query!("SELECT us.id, a.id as weapon_id, a.name, a.display, r.color FROM user_skins us JOIN agents a ON a.id = us.agent_id JOIN rarity r ON r.id = a.rarity WHERE us.user_id=$1 AND us.team=$2", uuid, info_query.team.as_i32()).fetch_optional(&pool).await?;
|
||||||
|
match agent {
|
||||||
|
Some(agent) => Ok(Json(SkinInfo {
|
||||||
|
id: agent.id,
|
||||||
|
weapon_id: agent.weapon_id,
|
||||||
|
name: agent.name,
|
||||||
|
display: agent.display,
|
||||||
|
paint_index: 0,
|
||||||
|
color: agent.color,
|
||||||
|
float: 0.0,
|
||||||
|
min_float: 0.0,
|
||||||
|
max_float: 0.0,
|
||||||
|
pattern: 0,
|
||||||
|
})),
|
||||||
|
None => {
|
||||||
|
let default = query!("SELECT a.name, a.id as weapon_id, a.display, r.color FROM agents a JOIN rarity r ON r.id = a.rarity WHERE a.team = $1 AND a.default = true", info_query.team.as_i32()).fetch_one(&pool).await?;
|
||||||
|
Ok(Json(SkinInfo {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
weapon_id: default.weapon_id,
|
||||||
|
name: default.name,
|
||||||
|
display: default.display,
|
||||||
|
paint_index: 0,
|
||||||
|
color: default.color,
|
||||||
|
float: 0.0,
|
||||||
|
min_float: 0.0,
|
||||||
|
max_float: 0.0,
|
||||||
|
pattern: 0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(AppError::Unauthorised)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Default, Debug)]
|
||||||
|
pub struct PaintIndexInfo {
|
||||||
|
name: String,
|
||||||
|
paint_index: i32,
|
||||||
|
display: String,
|
||||||
|
color: String,
|
||||||
|
min_float: f64,
|
||||||
|
max_float: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct PaintQuery {
|
||||||
|
weapon: Uuid,
|
||||||
|
team: Teams,
|
||||||
|
agent: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_paint_index(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
Query(paint_query): Query<PaintQuery>,
|
||||||
|
) -> Result<Json<Vec<PaintIndexInfo>>, AppError> {
|
||||||
|
let agent = match paint_query.agent {
|
||||||
|
Some(agent) => agent,
|
||||||
|
None => false,
|
||||||
|
};
|
||||||
|
let paints = if agent {
|
||||||
|
let values = query!("SELECT a.name, a.def_index, a.display, r.color FROM agents a JOIN rarity r ON r.id = a.rarity WHERE a.team=$1", paint_query.team.as_i32()).fetch_all(&pool).await?;
|
||||||
|
values
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| PaintIndexInfo {
|
||||||
|
name: x.name,
|
||||||
|
paint_index: x.def_index,
|
||||||
|
display: x.display,
|
||||||
|
color: x.color,
|
||||||
|
min_float: 0.0,
|
||||||
|
max_float: 0.0,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
let category = query!(
|
||||||
|
"SELECT w.category FROM weapons w WHERE w.id=$1",
|
||||||
|
paint_query.weapon
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
match category.category.as_str() {
|
||||||
|
"Knives" | "Gloves" => query_as!(PaintIndexInfo, "SELECT w.name, s.paint_index, s.display, r.color, s.min_float, s.max_float FROM skins s JOIN rarity r ON r.id = s.rarity JOIN weapons w ON w.id = s.weapon WHERE w.category=$1", category.category).fetch_all(&pool).await?,
|
||||||
|
_ => query_as!(PaintIndexInfo, "SELECT w.name, s.paint_index, s.display, r.color, s.min_float, s.max_float FROM skins s JOIN rarity r ON r.id = s.rarity JOIN weapons w ON w.id = s.weapon WHERE w.id=$1", paint_query.weapon).fetch_all(&pool).await?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(Json(paints))
|
||||||
|
}
|
||||||
180
src/users.rs
180
src/users.rs
@@ -3,11 +3,13 @@ use std::error::Error;
|
|||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
extract::{Query, State},
|
extract::{Query, State},
|
||||||
http::StatusCode,
|
|
||||||
};
|
};
|
||||||
use axum_extra::extract::CookieJar;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sqlx::{PgPool, query, types::Uuid};
|
use serde_json::Value;
|
||||||
|
use sqlx::{PgPool, query, query_as, query_scalar, types::Uuid};
|
||||||
|
use tower_sessions::Session;
|
||||||
|
|
||||||
|
use crate::error::AppError;
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
@@ -30,26 +32,27 @@ impl User {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create(self, pool: PgPool) -> Result<(), Box<dyn Error>> {
|
async fn create(&mut self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||||
query!(
|
let uuid: Uuid = query_scalar!(
|
||||||
"INSERT INTO users (steamid, name, avatar) VALUES ($1, $2, $3)",
|
"INSERT INTO users (steamid, name, avatar) VALUES ($1, $2, $3) RETURNING id",
|
||||||
self.steamid,
|
self.steamid,
|
||||||
self.name,
|
self.name,
|
||||||
self.avatar
|
self.avatar
|
||||||
)
|
)
|
||||||
.execute(&pool)
|
.fetch_one(pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
self.id = uuid;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete(self, pool: PgPool) -> Result<(), Box<dyn Error>> {
|
async fn delete(&self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||||
query!("DELETE FROM users WHERE id=$1", self.id)
|
query!("DELETE FROM users WHERE id=$1", self.id)
|
||||||
.execute(&pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update(self, pool: PgPool) -> Result<(), Box<dyn Error>> {
|
async fn update(&self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||||
query!(
|
query!(
|
||||||
"UPDATE users SET steamid=$1, name=$2, avatar=$3 WHERE id=$4",
|
"UPDATE users SET steamid=$1, name=$2, avatar=$3 WHERE id=$4",
|
||||||
self.steamid,
|
self.steamid,
|
||||||
@@ -57,24 +60,57 @@ impl User {
|
|||||||
self.avatar,
|
self.avatar,
|
||||||
self.id
|
self.id
|
||||||
)
|
)
|
||||||
.execute(&pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn fetch_id(pool: &PgPool, uuid: Uuid) -> Result<Self, Box<dyn Error>> {
|
||||||
|
Ok(query_as!(User, "SELECT * FROM users WHERE id=$1", uuid)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
async fn steamid_exists(pool: &PgPool, steamid: &String) -> Result<bool, Box<dyn Error>> {
|
||||||
pub async fn me(State(pool): State<PgPool>, jar: CookieJar) -> Json<Option<User>> {
|
match query!("SELECT id FROM users WHERE steamid=$1", steamid)
|
||||||
if let Some(cookie) = jar.get("token") {
|
.fetch_optional(pool)
|
||||||
println!("Cookie received: {cookie}");
|
.await?
|
||||||
Json(Some(User::new(
|
{
|
||||||
"76561198840243902",
|
Some(_) => Ok(true),
|
||||||
"p0rning AINDUSTRIES",
|
None => Ok(false),
|
||||||
"https://avatars.steamstatic.com/c6975c06a7a7cb874c8f95ed5a10c8a25c936a6b_full.jpg",
|
}
|
||||||
)))
|
}
|
||||||
} else {
|
|
||||||
println!("No cookie received");
|
async fn from_steamid(pool: &PgPool, steamid: String) -> Result<Self, Box<dyn Error>> {
|
||||||
Json(None)
|
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 raw_user = Self::fetch_steam(&steamid).await?;
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_steam(steamid: &String) -> Result<Value, Box<dyn Error>> {
|
||||||
|
let response = reqwest::get(format!("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=ABBFE30D7BDC1FD582DB1A2CEBD563B4&steamids={steamid}"))
|
||||||
|
.await?.bytes().await?;
|
||||||
|
let mut json: serde_json::Value = serde_json::from_slice(&response)?;
|
||||||
|
Ok(json["response"]["players"][0].take())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_from_steam(&mut self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||||
|
let raw_user = Self::fetch_steam(&self.steamid).await?;
|
||||||
|
self.name = raw_user["personaname"].to_string().trim_matches('"').into();
|
||||||
|
self.avatar = raw_user["avatarfull"].to_string().trim_matches('"').into();
|
||||||
|
self.update(pool).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,26 +147,92 @@ pub struct OpenId {
|
|||||||
sig: String,
|
sig: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl OpenId {
|
||||||
|
pub async fn is_valid(&mut self) -> Result<bool, Box<dyn Error>> {
|
||||||
|
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]
|
#[axum::debug_handler]
|
||||||
pub async fn login(
|
pub async fn login(
|
||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
Query(mut info): Query<OpenId>,
|
Query(mut info): Query<OpenId>,
|
||||||
) -> Result<String, StatusCode> {
|
session: Session,
|
||||||
info.mode = "check_authentication".into();
|
) -> Result<(), AppError> {
|
||||||
if let Ok(url_encoded) = serde_urlencoded::to_string(info) {
|
if !info.is_valid().await? {
|
||||||
println!("https://steamcommunity.com/openid/login?{url_encoded}");
|
return Err(AppError::OpenIdError(
|
||||||
let response = reqwest::get(format!(
|
"Some query parameters are erronous or lacking.".into(),
|
||||||
"https://steamcommunity.com/openid/login?{url_encoded}"
|
));
|
||||||
))
|
}
|
||||||
.await
|
let steamid = info
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
.identity
|
||||||
.text()
|
.replace("https://steamcommunity.com/openid/id/", "");
|
||||||
.await
|
let user = User::from_steamid(&pool, steamid).await?;
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
session.insert("uuid", user.id).await?;
|
||||||
println!("{response}");
|
Ok(())
|
||||||
if response.contains("is_valid:true") {
|
}
|
||||||
return Ok("ok".to_string());
|
|
||||||
|
pub async fn logout(session: Session) -> Result<(), AppError> {
|
||||||
|
session.delete().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
pub async fn me(State(pool): State<PgPool>, session: Session) -> Result<Json<User>, AppError> {
|
||||||
|
if let Some(uuid) = session.get("uuid").await? {
|
||||||
|
let user = User::fetch_id(&pool, uuid).await?;
|
||||||
|
Ok(Json(user))
|
||||||
|
} else {
|
||||||
|
Err(AppError::Unauthorised)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok("nok".to_string())
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct Settings {
|
||||||
|
username: String,
|
||||||
|
avatar: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
pub async fn update(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
session: Session,
|
||||||
|
data: Json<Settings>,
|
||||||
|
) -> Result<(), AppError> {
|
||||||
|
if let Some(uuid) = session.get("uuid").await? {
|
||||||
|
let mut user = User::fetch_id(&pool, uuid).await?;
|
||||||
|
|
||||||
|
if !data.username.is_empty() {
|
||||||
|
user.name = data.username.clone();
|
||||||
|
}
|
||||||
|
if !data.avatar.is_empty() {
|
||||||
|
user.avatar = data.avatar.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
user.update(&pool).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(AppError::Unauthorised)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reload(State(pool): State<PgPool>, session: Session) -> Result<(), AppError> {
|
||||||
|
if let Some(uuid) = session.get("uuid").await? {
|
||||||
|
let mut user = User::fetch_id(&pool, uuid).await?;
|
||||||
|
user.update_from_steam(&pool).await?;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(AppError::Unauthorised)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user