Compare commits
3 Commits
d18d59054a
...
d78de75c5e
| Author | SHA1 | Date | |
|---|---|---|---|
| d78de75c5e | |||
| 2a029709b8 | |||
| 27b954a5ec |
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -15,6 +15,7 @@ dependencies = [
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"dotenvy",
|
||||
"http",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -757,9 +758,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.4.2"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
|
||||
@@ -18,3 +18,4 @@ 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"
|
||||
|
||||
@@ -6,7 +6,7 @@ use reqwest::StatusCode;
|
||||
pub enum AppError {
|
||||
InternalError(String),
|
||||
OpenIdError(String),
|
||||
Unauthorised
|
||||
Unauthorised,
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
@@ -14,7 +14,10 @@ impl IntoResponse for AppError {
|
||||
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())
|
||||
AppError::Unauthorised => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Unauthorised (did you login?)".into(),
|
||||
),
|
||||
};
|
||||
(status, message).into_response()
|
||||
}
|
||||
|
||||
14
src/main.rs
14
src/main.rs
@@ -2,20 +2,21 @@ use std::env::var;
|
||||
use std::error::Error;
|
||||
|
||||
use axum::http::{HeaderValue, Method};
|
||||
use axum::routing::get;
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Router, serve};
|
||||
use dotenvy::dotenv;
|
||||
use http::header::CONTENT_TYPE;
|
||||
use sqlx::postgres::PgPool;
|
||||
use tokio::net::TcpListener;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tower_sessions::SessionManagerLayer;
|
||||
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, logout};
|
||||
use users::{login, logout, me, reload, update};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
@@ -33,11 +34,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
.route("/me", get(me))
|
||||
.route("/login", get(login))
|
||||
.route("/logout", get(logout))
|
||||
.route("/update", post(update))
|
||||
.route("/reload", get(reload))
|
||||
.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin("http://localhost:5173".parse::<HeaderValue>().unwrap())
|
||||
.allow_methods([Method::GET])
|
||||
.allow_credentials(true),
|
||||
.allow_methods([Method::GET, Method::POST])
|
||||
.allow_credentials(true)
|
||||
.allow_headers([CONTENT_TYPE]),
|
||||
)
|
||||
.layer(session)
|
||||
.with_state(pool);
|
||||
|
||||
69
src/users.rs
69
src/users.rs
@@ -5,6 +5,7 @@ use axum::{
|
||||
extract::{Query, State},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sqlx::{PgPool, query, query_as, query_scalar, types::Uuid};
|
||||
use tower_sessions::Session;
|
||||
|
||||
@@ -88,10 +89,7 @@ impl User {
|
||||
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 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('"'),
|
||||
@@ -100,6 +98,20 @@ impl User {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -158,7 +170,9 @@ pub async fn login(
|
||||
session: Session,
|
||||
) -> Result<(), AppError> {
|
||||
if !info.is_valid().await? {
|
||||
return Err(AppError::OpenIdError("Some query parameters are erronous or lacking.".into()));
|
||||
return Err(AppError::OpenIdError(
|
||||
"Some query parameters are erronous or lacking.".into(),
|
||||
));
|
||||
}
|
||||
let steamid = info
|
||||
.identity
|
||||
@@ -174,10 +188,7 @@ pub async fn logout(session: Session) -> Result<(), AppError> {
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
pub async fn me(
|
||||
State(pool): State<PgPool>,
|
||||
session: Session,
|
||||
) -> Result<Json<User>, AppError> {
|
||||
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))
|
||||
@@ -185,3 +196,43 @@ pub async fn me(
|
||||
Err(AppError::Unauthorised)
|
||||
}
|
||||
}
|
||||
|
||||
#[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