From 5898e5ab4359945ef52dc7460bb2937a85603fc2 Mon Sep 17 00:00:00 2001 From: niliara-edu Date: Sun, 26 Jan 2025 12:25:13 +0100 Subject: authentication done --- src/database/user.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/database/user.rs (limited to 'src/database/user.rs') diff --git a/src/database/user.rs b/src/database/user.rs new file mode 100644 index 0000000..ff7b1ab --- /dev/null +++ b/src/database/user.rs @@ -0,0 +1,84 @@ +use crate::database::DatabaseWrapper; +use serde::{Deserialize, Serialize}; +use sqlx::mysql::MySqlQueryResult; + +#[derive(Deserialize, Serialize)] +pub struct User { + pub id: Option, + pub name: Option, + password: Option, +} + +#[derive(Deserialize, Serialize)] +pub struct UserForm { + name: Option, + password: Option, +} + +impl DatabaseWrapper { + pub async fn register(&self, data: UserForm) -> Result { + if data.name.is_none() || data.password.is_none() { + return Err(sqlx::Error::RowNotFound); + } + + sqlx::query!( + "INSERT INTO user (name, password) + VALUE (?, PASSWORD(?))", + data.name, + data.password, + ) + .execute(&self.db_pool) + .await + } + + pub async fn login(&self, data: UserForm) -> Result, sqlx::Error> { + if data.name.is_none() || data.password.is_none() { + return Err(sqlx::Error::RowNotFound); + } + + sqlx::query_as!( + User, + "SELECT * FROM user + WHERE ? = name + AND password(?) = password + ", + data.name, + data.password, + ) + .fetch_optional(&self.db_pool) + .await + } + + pub async fn delete_user(&self, data: UserForm) -> Result { + if data.name.is_none() || data.password.is_none() { + return Err(sqlx::Error::RowNotFound); + } + + match sqlx::query_as!( + User, + "SELECT * FROM user + WHERE name = ? + AND password = password(?) + ", + data.name, + data.password, + ) + .fetch_one(&self.db_pool) + .await + { + Ok(_) => (), + Err(_) => return Err(sqlx::Error::RowNotFound), + }; + + sqlx::query!( + "DELETE FROM user + WHERE name = ? + AND password = password(?) + ", + data.name, + data.password, + ) + .execute(&self.db_pool) + .await + } +} -- cgit v1.2.3