summaryrefslogtreecommitdiff
path: root/src/services
diff options
context:
space:
mode:
authormrw1593 <botahamec@outlook.com>2023-05-13 11:59:16 -0400
committermrw1593 <botahamec@outlook.com>2023-05-29 10:45:53 -0400
commitefe24b616f91121512cb6b2c61cd9b850f943e2d (patch)
tree1c91e672f7f5797e1936a8eb8b725f1d26858c2b /src/services
parent0ed1eec3dc607807bcd9aefd678f744313e2b361 (diff)
Create get requests for users
Diffstat (limited to 'src/services')
-rw-r--r--src/services/db.rs46
1 files changed, 45 insertions, 1 deletions
diff --git a/src/services/db.rs b/src/services/db.rs
index a6571b5..3eee9ba 100644
--- a/src/services/db.rs
+++ b/src/services/db.rs
@@ -1,11 +1,37 @@
use exun::*;
-use sqlx::{mysql::MySqlQueryResult, query, query_scalar, Executor, MySql, MySqlPool};
+use sqlx::{mysql::MySqlQueryResult, query, query_as, query_scalar, Executor, MySql, MySqlPool};
use uuid::Uuid;
use crate::models::User;
use super::crypto::PasswordHash;
+struct UserRow {
+ user_id: Vec<u8>,
+ username: String,
+ password_hash: Vec<u8>,
+ password_salt: Vec<u8>,
+ password_version: u32,
+}
+
+impl TryFrom<UserRow> for User {
+ type Error = RawUnexpected;
+
+ fn try_from(row: UserRow) -> Result<Self, Self::Error> {
+ let password = PasswordHash::from_fields(
+ &row.password_hash,
+ &row.password_salt,
+ row.password_version as u8,
+ );
+ let user = User {
+ user_id: Uuid::from_slice(&row.user_id)?,
+ username: row.username.into_boxed_str(),
+ password,
+ };
+ Ok(user)
+ }
+}
+
/// Intialize the connection pool
pub async fn initialize(db: &str, user: &str, password: &str) -> Result<MySqlPool, RawUnexpected> {
let url = format!("mysql://{user}:{password}@localhost/{db}");
@@ -40,6 +66,24 @@ pub async fn username_is_used<'c>(
Ok(exists)
}
+pub async fn get_user<'c>(
+ conn: impl Executor<'c, Database = MySql>,
+ user_id: Uuid,
+) -> Result<Option<User>, RawUnexpected> {
+ let record = query_as!(
+ UserRow,
+ r"SELECT user_id, username, password_hash, password_salt, password_version
+ FROM users WHERE user_id = ?",
+ user_id
+ )
+ .fetch_optional(conn)
+ .await?;
+
+ let Some(record) = record else { return Ok(None) };
+
+ Ok(Some(record.try_into()?))
+}
+
pub async fn get_username<'c>(
conn: impl Executor<'c, Database = MySql>,
user_id: Uuid,