Get and store steam username and display it on the homepage
This commit is contained in:
@@ -21,4 +21,6 @@ diesel-async = { version = "0.5", features = ["postgres"] }
|
||||
serde_json = "1.0.128"
|
||||
diesel_async_migrations = { version = "0.15" }
|
||||
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
|
||||
common = { path = "../common/" }
|
||||
|
||||
@@ -66,7 +66,22 @@ pub mod demos {
|
||||
|
||||
pub mod steam {
|
||||
use axum::extract::State;
|
||||
use std::sync::Arc;
|
||||
use serde::Deserialize;
|
||||
use std::{sync::Arc, collections::HashMap};
|
||||
use diesel::prelude::*;
|
||||
use diesel_async::RunQueryDsl;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProfileInfoResponse {
|
||||
players: Vec<ProfileInfo>
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProfileInfo {
|
||||
pub steamid: String,
|
||||
pub personaname: String,
|
||||
#[serde(flatten)]
|
||||
other: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
pub fn router(url: &str, callback_path: &str) -> axum::Router {
|
||||
axum::Router::new()
|
||||
@@ -98,6 +113,28 @@ pub mod steam {
|
||||
axum::http::StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
let steam_client = crate::steam_api::Client::new(std::env::var("STEAM_API_KEY").unwrap());
|
||||
let profile_response_data: ProfileInfoResponse = match steam_client.get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/", &[("steamids", &format!("{}", id))]).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
tracing::error!("Getting Steam Profile Info: {:?}", e);
|
||||
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
let mut db_con = crate::db_connection().await;
|
||||
for player in profile_response_data.players {
|
||||
let query = diesel::dsl::insert_into(crate::schema::users::dsl::users).values(crate::models::User {
|
||||
steamid: player.steamid,
|
||||
name: player.personaname.clone(),
|
||||
}).on_conflict(crate::schema::users::dsl::steamid).do_update().set((crate::schema::users::dsl::name.eq(player.personaname)));
|
||||
tracing::debug!("Running Query: {:?}", query);
|
||||
|
||||
if let Err(e) = query.execute(&mut db_con).await {
|
||||
tracing::error!("Inserting/Updating user steam info: {:?}", e);
|
||||
}
|
||||
}
|
||||
|
||||
session
|
||||
.modify_data(|data| {
|
||||
data.steam_id = Some(id);
|
||||
@@ -109,23 +146,46 @@ pub mod steam {
|
||||
}
|
||||
|
||||
pub mod user {
|
||||
use diesel::prelude::*;
|
||||
use diesel_async::RunQueryDsl;
|
||||
|
||||
pub fn router() -> axum::Router {
|
||||
axum::Router::new()
|
||||
.route("/status", axum::routing::get(status))
|
||||
}
|
||||
|
||||
async fn status(session: crate::UserSession) -> axum::http::StatusCode {
|
||||
if session.data().steam_id.is_some() {
|
||||
axum::http::StatusCode::OK
|
||||
} else {
|
||||
axum::http::StatusCode::UNAUTHORIZED
|
||||
async fn status(session: crate::UserSession) -> Result<axum::response::Json<common::UserStatus>, reqwest::StatusCode> {
|
||||
let steam_id = match session.data().steam_id {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return Err(axum::http::StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
};
|
||||
|
||||
tracing::info!("Load user info");
|
||||
|
||||
let mut db_con = crate::db_connection().await;
|
||||
|
||||
let query = crate::schema::users::dsl::users.filter(crate::schema::users::dsl::steamid.eq(format!("{}", steam_id)));
|
||||
|
||||
let mut result = query.load::<crate::models::User>(&mut db_con).await.unwrap();
|
||||
if result.len() != 1 {
|
||||
tracing::error!("Unexpected query result: {:?}", result);
|
||||
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
let user_entry = result.pop().unwrap();
|
||||
|
||||
Ok(axum::Json(common::UserStatus {
|
||||
name: user_entry.name,
|
||||
steamid: user_entry.steamid,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router() -> axum::Router {
|
||||
axum::Router::new()
|
||||
.nest("/steam/", steam::router("http://192.168.0.156:3000", "/api/steam/callback"))
|
||||
.nest("/steam/", steam::router("http://localhost:3000", "/api/steam/callback"))
|
||||
.nest("/demos/", demos::router("uploads/"))
|
||||
.nest("/user/", user::router())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use diesel::prelude::*;
|
||||
use diesel_async::RunQueryDsl;
|
||||
|
||||
@@ -45,15 +47,19 @@ impl tower_sessions::SessionStore for DieselStore {
|
||||
let data = serde_json::to_value(&session_record.data).unwrap();
|
||||
let expiry_date = self.expiry_to_string(&session_record.expiry_date);
|
||||
|
||||
let steamid = session_record.data.get(crate::UserSession::KEY).map(|e| serde_json::from_value::<crate::UserSessionData>(e.clone()).ok()).flatten().map(|d| {
|
||||
d.steam_id.map(|s| s.to_string())
|
||||
}).flatten();
|
||||
|
||||
let query = diesel::dsl::insert_into(crate::schema::sessions::dsl::sessions)
|
||||
.values(crate::models::Session {
|
||||
id: db_id,
|
||||
data: data.clone(),
|
||||
steamid: steamid.clone(),
|
||||
expiry_date: expiry_date.clone(),
|
||||
})
|
||||
.on_conflict(crate::schema::sessions::dsl::id)
|
||||
.do_update()
|
||||
.set((crate::schema::sessions::dsl::data.eq(data), crate::schema::sessions::dsl::expiry_date.eq(expiry_date)));
|
||||
.set((crate::schema::sessions::dsl::steamid.eq(steamid), crate::schema::sessions::dsl::expiry_date.eq(expiry_date)));
|
||||
|
||||
let mut connection = crate::db_connection().await;
|
||||
|
||||
@@ -76,11 +82,23 @@ impl tower_sessions::SessionStore for DieselStore {
|
||||
return Err(tower_sessions::session_store::Error::Backend("Found more than 1 result".to_string()));
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let result = result.pop().unwrap();
|
||||
|
||||
let data = {
|
||||
let mut tmp = HashMap::<String, _>::new();
|
||||
tmp.insert(crate::UserSession::KEY.to_string(), serde_json::to_value(&crate::UserSessionData {
|
||||
steam_id: result.steamid.map(|s| s.parse().ok()).flatten(),
|
||||
}).unwrap());
|
||||
tmp
|
||||
};
|
||||
|
||||
Ok(Some(tower_sessions::session::Record {
|
||||
id: tower_sessions::session::Id(self.bytes_to_id(result.id)),
|
||||
data: serde_json::from_value(result.data).unwrap(),
|
||||
data: data,
|
||||
expiry_date: self.string_to_expiry(&result.expiry_date),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -34,3 +34,35 @@ pub async fn get_demo_from_upload(name: &str, mut form: axum::extract::Multipart
|
||||
}
|
||||
|
||||
pub mod api;
|
||||
pub mod steam_api {
|
||||
use serde::Deserialize;
|
||||
|
||||
pub struct Client {
|
||||
http: reqwest::Client,
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Response<T> {
|
||||
response: T,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new<IS>(api_key: IS) -> Self where IS: Into<String> {
|
||||
Self {
|
||||
http: reqwest::Client::new(),
|
||||
api_key: api_key.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get<T>(&self, path: &str, args: &[(&str, &str)]) -> Result<T, ()> where T: serde::de::DeserializeOwned {
|
||||
let response = self.http.get(path).query(&[("key", &self.api_key)]).query(args).send().await.map_err(|e| ())?;
|
||||
if !response.status().is_success() {
|
||||
dbg!(&response);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
response.json::<Response<T>>().await.map(|r| r.response).map_err(|e| ())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use diesel::prelude::*;
|
||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||
pub struct Session {
|
||||
pub id: Vec<i64>,
|
||||
pub data: serde_json::Value,
|
||||
pub steamid: Option<String>,
|
||||
pub expiry_date: String,
|
||||
}
|
||||
|
||||
@@ -16,3 +16,11 @@ pub struct Demo {
|
||||
pub steam_id: i64,
|
||||
pub demo_id: i64,
|
||||
}
|
||||
|
||||
#[derive(Queryable, Selectable, Insertable, Debug)]
|
||||
#[diesel(table_name = crate::schema::users)]
|
||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||
pub struct User {
|
||||
pub steamid: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
diesel::table! {
|
||||
sessions (id) {
|
||||
id -> Array<BigInt>,
|
||||
data -> Jsonb,
|
||||
steamid -> Nullable<Text>,
|
||||
expiry_date -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
diesel::table! {
|
||||
demos (steam_id) {
|
||||
demos (steam_id, demo_id) {
|
||||
steam_id -> BigInt,
|
||||
demo_id -> BigInt
|
||||
}
|
||||
}
|
||||
|
||||
diesel::table! {
|
||||
users (steamid) {
|
||||
steamid -> Text,
|
||||
name -> Text
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct UserSession {
|
||||
}
|
||||
|
||||
impl UserSession {
|
||||
const KEY: &'static str = "user.data";
|
||||
pub const KEY: &'static str = "user.data";
|
||||
|
||||
pub fn data(&self) -> &UserSessionData {
|
||||
&self.data
|
||||
|
||||
Reference in New Issue
Block a user