add start
This commit is contained in:
1
como_bin/src/services/cookie_service.rs
Normal file
1
como_bin/src/services/cookie_service.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub struct CookieService {}
|
2
como_bin/src/services/mod.rs
Normal file
2
como_bin/src/services/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod cookie_service;
|
||||
pub mod users_service;
|
80
como_bin/src/services/users_service.rs
Normal file
80
como_bin/src/services/users_service.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||
use rand_core::OsRng;
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
pub struct UserService {
|
||||
pgx: Pool<Postgres>,
|
||||
}
|
||||
|
||||
impl UserService {
|
||||
pub fn new(pgx: Pool<Postgres>) -> Self {
|
||||
Self { pgx }
|
||||
}
|
||||
|
||||
pub async fn add_user(&self, username: String, password: String) -> anyhow::Result<String> {
|
||||
let hashed_password = self.hash_password(password)?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (username, password_hash)
|
||||
VALUES ( $1, $2 )
|
||||
RETURNING id
|
||||
"#,
|
||||
username,
|
||||
hashed_password
|
||||
)
|
||||
.fetch_one(&self.pgx)
|
||||
.await?;
|
||||
|
||||
Ok(rec.id.to_string())
|
||||
}
|
||||
|
||||
pub async fn validate_user(
|
||||
&self,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<Option<()>> {
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
SELECT * from users
|
||||
where username=$1
|
||||
"#,
|
||||
username,
|
||||
)
|
||||
.fetch_optional(&self.pgx)
|
||||
.await?;
|
||||
|
||||
match rec {
|
||||
Some(user) => match self.validate_password(password, user.password_hash)? {
|
||||
true => Ok(Some(())),
|
||||
false => Ok(None),
|
||||
},
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_password(&self, password: String) -> anyhow::Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|e| anyhow!(e))?
|
||||
.to_string();
|
||||
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
fn validate_password(&self, password: String, hashed_password: String) -> anyhow::Result<bool> {
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let parsed_hash = PasswordHash::new(&hashed_password).map_err(|e| anyhow!(e))?;
|
||||
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
|
||||
Ok(..) => Ok(true),
|
||||
Err(..) => Ok(false),
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user