feat: user management

This commit is contained in:
Maulana Sodiqin
2025-03-21 17:00:19 +07:00
parent a0f263bb4f
commit 1e6957720e
17 changed files with 347 additions and 212 deletions
+74 -58
View File
@@ -1,6 +1,8 @@
use crate::{AppState, RedisKeyEnum, UsersSchema};
use crate::{AppState, ResourceEnum, UsersSchema};
use anyhow::{anyhow, bail, Result};
use redis::Commands;
use chrono::{Duration, Utc};
use super::AuthOtpSchema;
pub struct AuthRepository<'a> {
state: &'a AppState,
@@ -11,76 +13,90 @@ impl<'a> AuthRepository<'a> {
Self { state }
}
pub fn query_store_user_data(&self, user: UsersSchema) -> Result<String> {
let redis_key = format!("{}:{}", RedisKeyEnum::User, user.email.clone());
match &self.state.redisdb.get_connection().and_then(|mut conn| {
conn.set_ex::<_, String, ()>(
&redis_key,
serde_json::to_string(&user).unwrap_or_default(),
86400,
)
}) {
Ok(_) => Ok("Success store user data".to_string()),
Err(err) => Ok(format!("Redis storage failed: {}", err)),
pub async fn query_store_user(&self, user: UsersSchema) -> Result<String> {
let user_clone = user.clone();
let record: Option<UsersSchema> = self
.state
.surrealdb_mem
.update((ResourceEnum::UsersCache.to_string(), user.email))
.content(user_clone)
.await?;
match record {
Some(_) => Ok("Success store user data".to_string()),
None => bail!("Failed store user data"),
}
}
pub fn query_get_stored_user(&self, email: String) -> Result<UsersSchema> {
let redis_key = format!("{}:{}", RedisKeyEnum::User, email);
let mut conn = self.state.redisdb.get_connection()?;
let data: Option<String> = conn.get(&redis_key)?;
match data {
Some(user_json) => {
let user: UsersSchema = serde_json::from_str(&user_json)?;
Ok(user)
}
pub async fn query_get_stored_user(&self, email: String) -> Result<UsersSchema> {
let user: Option<UsersSchema> = self
.state
.surrealdb_mem
.select((ResourceEnum::UsersCache.to_string(), email))
.await?;
match user {
Some(u) => Ok(u),
None => bail!("No stored user data found"),
}
}
pub fn query_get_stored_otp(&self, email: String) -> Result<u32> {
let redis_key = format!("{}:{}", RedisKeyEnum::Otp, email);
let mut conn = match self.state.redisdb.get_connection() {
Ok(conn) => conn,
Err(e) => {
return Err(anyhow::anyhow!("Failed to get Redis connection: {}", e))
pub async fn query_delete_stored_user(&self, email: String) -> Result<String> {
let record: Option<String> = self
.state
.surrealdb_mem
.delete((ResourceEnum::UsersCache.to_string(), email))
.await?;
match record {
Some(_) => Ok("Success delete stored user".to_string()),
None => bail!("Failed delete stored user"),
}
}
pub async fn query_get_stored_otp(&self, email: String) -> Result<u32> {
let otp: Option<AuthOtpSchema> = self
.state
.surrealdb_mem
.select((ResourceEnum::OtpCache.to_string(), &email))
.await?;
match otp {
Some(data) => {
if Utc::now() > data.expires_at {
let _: Option<AuthOtpSchema> = self
.state
.surrealdb_mem
.delete((ResourceEnum::OtpCache.to_string(), &email))
.await?;
Err(anyhow!("OTP expired"))
} else {
Ok(data.otp)
}
}
};
let data: Option<String> = match conn.get(&redis_key) {
Ok(data) => data,
Err(e) => return Err(anyhow::anyhow!("Failed to get data from Redis: {}", e)),
};
match data {
Some(otp_str) => match otp_str.parse::<u32>() {
Ok(otp) => Ok(otp),
Err(e) => Err(anyhow::anyhow!("Failed to parse OTP as u64: {}", e)),
},
None => Err(anyhow::anyhow!("No stored OTP found")),
None => Err(anyhow!("No stored OTP found")),
}
}
pub fn query_store_otp(&self, email: String, otp: u32) -> Result<String> {
let redis_key: String = format!("{}:{}", RedisKeyEnum::Otp, email);
let mut conn = match self.state.redisdb.get_connection() {
Ok(conn) => conn,
Err(e) => return Err(anyhow!("Failed to get Redis connection: {}", e)),
};
let otp_str: String = otp.to_string();
match conn.set_ex::<_, _, ()>(&redis_key, &otp_str, 300) {
Ok(_) => Ok("Success store otp".to_string()),
Err(e) => Err(anyhow!("Failed to store OTP in Redis: {}", e)),
pub async fn query_store_otp(&self, email: String, otp: u32) -> Result<String> {
let expires_at = Utc::now() + Duration::seconds(300); // 5 menit
let record: Option<AuthOtpSchema> = self
.state
.surrealdb_mem
.create((ResourceEnum::OtpCache.to_string(), email))
.content(AuthOtpSchema { otp, expires_at })
.await?;
match record {
Some(_) => Ok("Success store otp".to_string()),
None => bail!("Failed store otp"),
}
}
pub fn query_delete_stored_otp(&self, email: String) -> Result<String> {
let redis_key = format!("{}:{}", RedisKeyEnum::Otp, email);
let mut conn = match self.state.redisdb.get_connection() {
Ok(conn) => conn,
Err(e) => return Err(anyhow!("Failed to get Redis connection: {}", e)),
};
match conn.del::<_, ()>(&redis_key) {
Ok(_) => Ok("Successfully deleted OTP".to_string()),
Err(e) => Err(anyhow!("Failed to delete OTP from Redis: {}", e)),
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
let record: Option<String> = self
.state
.surrealdb_mem
.delete((ResourceEnum::OtpCache.to_string(), email))
.await?;
match record {
Some(_) => Ok("Success delete stored otp".to_string()),
None => bail!("Failed delete stored otp"),
}
}
}
+8
View File
@@ -0,0 +1,8 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthOtpSchema {
pub otp: u32,
pub expires_at: DateTime<Utc>,
}
+41 -20
View File
@@ -83,7 +83,7 @@ impl AuthService {
},
};
if let Err(_) = auth_repo.query_store_user_data(user) {
if let Err(_) = auth_repo.query_store_user(user).await {
return common_response(StatusCode::BAD_REQUEST, "Failed to store data");
}
@@ -130,20 +130,37 @@ impl AuthService {
let otp = generate_otp::OtpManager::generate_otp();
auth_repo
match auth_repo
.query_store_otp(new_user.email.clone(), otp.clone())
.unwrap();
.await
{
Ok(_) => {
let message = format!("your otp code is {}", otp);
if let Err(err) = send_email(&new_user.email, "OTP Verification", &message) {
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
&err.to_string(),
);
}
}
Err(err) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
}
}
let message = format!("your otp code is {}", otp);
let role_thing = Thing::from((
ResourceEnum::Roles.to_string(),
Id::String(Uuid::new_v4().to_string()),
));
send_email(&new_user.email.clone(), "OTP Verification", &message).unwrap();
let role_thing =
Thing::from((ResourceEnum::Roles.to_string(), Id::String("".to_string())));
let user_thing = Thing::from((
ResourceEnum::Users.to_string(),
Id::String(Uuid::new_v4().to_string()),
));
match user_repo
.query_create_user(UsersSchema {
id: Uuid::new_v4().to_string(),
id: user_thing,
email: new_user.email.clone(),
fullname: new_user.fullname.clone(),
password: new_user.password.clone(),
@@ -160,7 +177,7 @@ impl AuthService {
})
.await
{
Ok(_) => common_response(StatusCode::CREATED, "Registration successful"),
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(err) => {
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
}
@@ -174,7 +191,7 @@ impl AuthService {
let repository = AuthRepository::new(state);
let otp = generate_otp::OtpManager::generate_otp();
let message = format!("Your OTP code is {}", otp);
match repository.query_store_otp(payload.email.clone(), otp) {
match repository.query_store_otp(payload.email.clone(), otp).await {
Ok(_) => match send_email(&payload.email, "OTP Verification", &message) {
Ok(_) => common_response(StatusCode::OK, "OTP resent successfully"),
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
@@ -224,25 +241,26 @@ impl AuthService {
let user_repo = UsersRepository::new(state);
let auth_repo = AuthRepository::new(state);
match auth_repo.query_get_stored_otp(payload.email.clone()) {
match auth_repo.query_get_stored_otp(payload.email.clone()).await {
Ok(stored_otp) => {
let user_otp = payload.otp;
let is_otp_valid = stored_otp == user_otp;
if is_otp_valid {
match user_repo
.query_active_inactive_user(UsersActiveInactiveSchema {
email: payload.email.clone(),
is_active: true,
})
.query_active_inactive_user(
payload.email.clone(),
UsersActiveInactiveSchema { is_active: true },
)
.await
{
Ok(_) => {
if let Err(e) =
auth_repo.query_delete_stored_otp(payload.email.clone())
if let Err(e) = auth_repo
.query_delete_stored_otp(payload.email.clone())
.await
{
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("Failed to delete OTP: {}", e),
&e.to_string(),
);
}
common_response(StatusCode::OK, "Email verified successfully")
@@ -250,7 +268,10 @@ impl AuthService {
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
}
} else {
if let Err(e) = auth_repo.query_delete_stored_otp(payload.email.clone()) {
if let Err(e) = auth_repo
.query_delete_stored_otp(payload.email.clone())
.await
{
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("Failed to delete OTP: {}", e),
+2
View File
@@ -4,10 +4,12 @@ pub mod auth_controller;
pub mod auth_dto;
pub mod auth_middleware;
pub mod auth_repository;
pub mod auth_schema;
pub mod auth_service;
pub use auth_dto::*;
pub use auth_repository::*;
pub use auth_schema::*;
pub use auth_service::*;
pub fn auth_router() -> Router {