Proper user authentication
This commit is contained in:
133
src/users.rs
133
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<dyn Error>> {
|
||||
query!(
|
||||
"INSERT INTO users (steamid, name, avatar) VALUES ($1, $2, $3)",
|
||||
async fn create(&mut self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||
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<dyn Error>> {
|
||||
async fn delete(&self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||
query!("DELETE FROM users WHERE id=$1", self.id)
|
||||
.execute(&pool)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update(self, pool: PgPool) -> Result<(), Box<dyn Error>> {
|
||||
async fn update(&self, pool: &PgPool) -> Result<(), Box<dyn Error>> {
|
||||
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<PgPool>, jar: CookieJar) -> Json<Option<User>> {
|
||||
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<Self, Box<dyn Error>> {
|
||||
Ok(query_as!(User, "SELECT * FROM users WHERE id=$1", uuid)
|
||||
.fetch_one(pool)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn steamid_exists(pool: &PgPool, steamid: &String) -> Result<bool, Box<dyn Error>> {
|
||||
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<Self, Box<dyn Error>> {
|
||||
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<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]
|
||||
pub async fn login(
|
||||
State(pool): State<PgPool>,
|
||||
Query(mut info): Query<OpenId>,
|
||||
) -> Result<String, StatusCode> {
|
||||
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<PgPool>,
|
||||
session: Session,
|
||||
) -> Result<Json<Option<User>>, 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())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user