feat: user management
This commit is contained in:
+9
-3
@@ -1,4 +1,4 @@
|
||||
use crate::{AppState, Env, RedisClient, SurrealClient};
|
||||
use crate::{AppState, Env, SurrealMemClient, SurrealWsClient};
|
||||
use axum::{
|
||||
http::{header, HeaderValue, Method},
|
||||
Extension, Router,
|
||||
@@ -11,8 +11,14 @@ pub mod v2;
|
||||
|
||||
pub use v1::*;
|
||||
|
||||
pub async fn apps(surrealdb: SurrealClient, redisdb: RedisClient) -> Router {
|
||||
let state = AppState { surrealdb, redisdb };
|
||||
pub async fn apps(
|
||||
surrealdb_ws: SurrealWsClient,
|
||||
surrealdb_mem: SurrealMemClient,
|
||||
) -> Router {
|
||||
let state = AppState {
|
||||
surrealdb_ws,
|
||||
surrealdb_mem,
|
||||
};
|
||||
let env = Env::new();
|
||||
let cors_origins = match env.rust_env.as_str() {
|
||||
"development" => vec!["http://localhost:3000"],
|
||||
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{UsersActiveInactiveSchema, UsersSchema, UsersSetNewPasswordSchema};
|
||||
use crate::{AppState, ResourceEnum};
|
||||
use crate::{AppState, AuthOtpSchema, ResourceEnum};
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
pub struct UsersRepository<'a> {
|
||||
@@ -12,9 +12,28 @@ impl<'a> UsersRepository<'a> {
|
||||
}
|
||||
|
||||
pub async fn query_user_by_email(&self, email: String) -> Result<UsersSchema> {
|
||||
let db = &self.state.surrealdb;
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE email = $email",
|
||||
ResourceEnum::Users.to_string()
|
||||
);
|
||||
let mut response: Vec<UsersSchema> = db
|
||||
.query(sql)
|
||||
.bind(("email", email.clone()))
|
||||
.await?
|
||||
.take(0)?;
|
||||
|
||||
if let Some(user) = response.pop() {
|
||||
Ok(user)
|
||||
} else {
|
||||
bail!("User not found")
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_user_by_id(&self, id: String) -> Result<UsersSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let result = db
|
||||
.select((ResourceEnum::Users.to_string(), email.clone()))
|
||||
.select((ResourceEnum::Users.to_string(), id.clone()))
|
||||
.await?;
|
||||
match result {
|
||||
Some(response) => Ok(response),
|
||||
@@ -23,9 +42,9 @@ impl<'a> UsersRepository<'a> {
|
||||
}
|
||||
|
||||
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let db = &self.state.surrealdb;
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSchema> = db
|
||||
.create((ResourceEnum::Users.to_string(), &data.id))
|
||||
.create(ResourceEnum::Users.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
match record {
|
||||
@@ -34,17 +53,11 @@ impl<'a> UsersRepository<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_active_inactive_user(
|
||||
&self,
|
||||
data: UsersActiveInactiveSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb;
|
||||
let record: Option<UsersActiveInactiveSchema> = db
|
||||
.update((ResourceEnum::Users.to_string(), &data.email))
|
||||
.merge(UsersActiveInactiveSchema {
|
||||
email: data.email.clone(),
|
||||
is_active: data.is_active.clone(),
|
||||
})
|
||||
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSchema> = db
|
||||
.update((ResourceEnum::Users.to_string(), &data.id.id.to_string()))
|
||||
.merge(data)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update user".into()),
|
||||
@@ -52,11 +65,32 @@ impl<'a> UsersRepository<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_active_inactive_user(
|
||||
&self,
|
||||
email: String,
|
||||
data: UsersActiveInactiveSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user = self.query_user_by_email(email.clone()).await?;
|
||||
let table = user.id.tb.as_str();
|
||||
let id = user.id.id.to_string();
|
||||
let result: Option<AuthOtpSchema> = db
|
||||
.update((table, id))
|
||||
.merge(UsersActiveInactiveSchema {
|
||||
is_active: data.is_active,
|
||||
})
|
||||
.await?;
|
||||
match result {
|
||||
Some(_) => Ok("Success update user".to_string()),
|
||||
None => bail!("Failed to update user"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_update_password_user(
|
||||
&self,
|
||||
data: UsersSetNewPasswordSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb;
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSetNewPasswordSchema> = db
|
||||
.update((ResourceEnum::Users.to_string(), &data.email))
|
||||
.merge(UsersSetNewPasswordSchema {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::{Id, Thing};
|
||||
|
||||
use crate::ResourceEnum;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{
|
||||
sql::{Id, Thing},
|
||||
Uuid,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersSchema {
|
||||
pub id: String,
|
||||
pub role_id: String,
|
||||
pub id: Thing,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
@@ -29,8 +30,10 @@ pub struct UsersSchema {
|
||||
impl Default for UsersSchema {
|
||||
fn default() -> Self {
|
||||
UsersSchema {
|
||||
id: String::new(),
|
||||
role_id: String::new(),
|
||||
id: Thing::from((
|
||||
ResourceEnum::Users.to_string(),
|
||||
Id::String(Uuid::new_v4().to_string()),
|
||||
)),
|
||||
fullname: String::new(),
|
||||
email: String::new(),
|
||||
password: String::new(),
|
||||
@@ -44,11 +47,11 @@ impl Default for UsersSchema {
|
||||
religion: None,
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
is_profile_completed: false,
|
||||
role: Thing::from((
|
||||
ResourceEnum::Roles.to_string(),
|
||||
Id::String("".to_string()),
|
||||
Id::String(Uuid::new_v4().to_string()),
|
||||
)),
|
||||
is_profile_completed: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
@@ -63,6 +66,5 @@ pub struct UsersSetNewPasswordSchema {
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersActiveInactiveSchema {
|
||||
pub email: String,
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user