feat: user relation
This commit is contained in:
@@ -1,7 +1,19 @@
|
||||
use super::{AuthLoginRequestDto, AuthRegisterRequestDto, AuthService};
|
||||
use crate::AppState;
|
||||
use crate::{v1::AuthLoginResponsetDto, AppState};
|
||||
use axum::{response::IntoResponse, Extension, Json};
|
||||
|
||||
use crate::{MessageResponseDto, ResponseSuccessDto};
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "Unauthorized", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
@@ -9,6 +21,16 @@ pub async fn post_login(
|
||||
AuthService::mutation_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = MessageResponseDto),
|
||||
(status = 401, description = "Unauthorized", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_register(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRegisterRequestDto>,
|
||||
|
||||
@@ -27,3 +27,10 @@ pub struct AuthRegisterRequestDto {
|
||||
pub password: String,
|
||||
pub fullname: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthQueryByEmailResponse {
|
||||
pub email: String,
|
||||
pub fullname: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::{v1::UsersItemDto, AppState, ResourceEnum};
|
||||
use std::error::Error;
|
||||
use crate::{v1::UsersItemDto, AppState, RedisKeyEnum, ResourceEnum};
|
||||
use anyhow::{bail, Result};
|
||||
use redis::Commands;
|
||||
|
||||
use super::AuthRegisterRequestDto;
|
||||
use super::{AuthQueryByEmailResponse, AuthRegisterRequestDto};
|
||||
|
||||
pub struct AuthRepository<'a> {
|
||||
state: &'a AppState,
|
||||
@@ -12,24 +13,56 @@ impl<'a> AuthRepository<'a> {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub fn query_store_user_data(
|
||||
&self,
|
||||
user: AuthRegisterRequestDto,
|
||||
) -> 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 fn query_get_stored_user(&self, email: String) -> Result<UsersItemDto> {
|
||||
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: UsersItemDto = serde_json::from_str(&user_json)?;
|
||||
Ok(user)
|
||||
}
|
||||
None => bail!("No stored user data found for email"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_user_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<AuthRegisterRequestDto, Box<dyn Error>> {
|
||||
) -> Result<AuthQueryByEmailResponse> {
|
||||
let db = &self.state.surrealdb;
|
||||
|
||||
let result = db.select((ResourceEnum::Users.to_string(), email)).await?;
|
||||
|
||||
match result {
|
||||
Some(user) => Ok(user),
|
||||
None => Err("User not found for email".into()),
|
||||
Some(response) => Ok(response),
|
||||
None => bail!("User not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_user(
|
||||
&self,
|
||||
data: AuthRegisterRequestDto,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb;
|
||||
|
||||
let record: Option<UsersItemDto> = db
|
||||
@@ -39,7 +72,7 @@ impl<'a> AuthRepository<'a> {
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success create user".into()),
|
||||
None => Err("Failed to create user".into()),
|
||||
None => bail!("Failed to create user"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use redis::Commands;
|
||||
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthRegisterRequestDto,
|
||||
@@ -55,22 +54,21 @@ impl AuthService {
|
||||
},
|
||||
};
|
||||
|
||||
let redis_key =
|
||||
format!("authenticated_users_data:{}", payload.email.clone());
|
||||
|
||||
match state.redisdb.get_connection().and_then(|mut conn| {
|
||||
conn.set_ex::<_, String, ()>(
|
||||
&redis_key,
|
||||
serde_json::to_string(&user).unwrap_or_default(),
|
||||
86400,
|
||||
)
|
||||
}) {
|
||||
Ok(_) => success_response(response),
|
||||
Err(err) => common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&format!("Redis storage failed: {}", err),
|
||||
),
|
||||
if !repository
|
||||
.query_store_user_data(AuthRegisterRequestDto {
|
||||
fullname: user.fullname,
|
||||
password: user.password,
|
||||
email: user.email,
|
||||
})
|
||||
.is_ok()
|
||||
{
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Failed to store data",
|
||||
);
|
||||
}
|
||||
|
||||
success_response(response)
|
||||
}
|
||||
Err(err) => common_response(StatusCode::UNAUTHORIZED, &err.to_string()),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use crate::{
|
||||
v1::{auth, AuthLoginRequestDto, AuthLoginResponsetDto},
|
||||
MessageResponseDto, MetaRequestDto, MetaResponseDto, ResponseSuccessDto,
|
||||
};
|
||||
|
||||
use utoipa::{
|
||||
openapi::security::{Http, HttpAuthScheme, SecurityScheme},
|
||||
Modify, OpenApi,
|
||||
};
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
auth::auth_controller::post_login,
|
||||
auth::auth_controller::post_register
|
||||
),
|
||||
components(
|
||||
schemas(
|
||||
MetaRequestDto,
|
||||
MetaResponseDto,
|
||||
MessageResponseDto,
|
||||
|
||||
AuthLoginRequestDto,
|
||||
AuthLoginResponsetDto,
|
||||
ResponseSuccessDto<AuthLoginResponsetDto>,
|
||||
)
|
||||
),
|
||||
info(
|
||||
title = "IMPHNEN API",
|
||||
description = "IMPHNEN API Documentation",
|
||||
version = "0.1.0",
|
||||
contact(
|
||||
name = "Maulana Sodiqin",
|
||||
url = ""
|
||||
),
|
||||
license(
|
||||
name = "MIT",
|
||||
url = "https://opensource.org/licenses/MIT"
|
||||
)
|
||||
),
|
||||
modifiers(&SecurityAddon),
|
||||
tags(
|
||||
(name = "Authentication", description = "List of Authentication Endpoints"),
|
||||
(name = "Users", description = "List of Users Endpoints")
|
||||
)
|
||||
)]
|
||||
|
||||
pub struct ApiDoc;
|
||||
|
||||
struct SecurityAddon;
|
||||
|
||||
impl Modify for SecurityAddon {
|
||||
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
|
||||
if let Some(components) = openapi.components.as_mut() {
|
||||
components.add_security_scheme(
|
||||
"Bearer",
|
||||
SecurityScheme::Http(Http::new(HttpAuthScheme::Bearer)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use utoipa::OpenApi;
|
||||
|
||||
pub mod docs_controller;
|
||||
pub use docs_controller::*;
|
||||
|
||||
pub fn docs_router() -> utoipa::openapi::OpenApi {
|
||||
ApiDoc::openapi()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use super::{GachaRequestDto, GachaService};
|
||||
use crate::{AppState, MessageResponseDto};
|
||||
use axum::{response::IntoResponse, Extension, Json};
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/gacha/create",
|
||||
request_body = GachaRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Create gacha successful", body = MessageResponseDto),
|
||||
(status = 401, description = "Create gacha failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn post_create_gacha(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<GachaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
GachaService::mutation_create_gacha(payload, &state).await
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::v1::UsersItemDto;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaRequestDto {
|
||||
pub email: String,
|
||||
pub fullname: String,
|
||||
pub transaction_number: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaResponseDto {
|
||||
pub transaction_number: String,
|
||||
pub user: UsersItemDto,
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use super::{GachaRequestDto, GachaResponseDto, GachaSchema};
|
||||
use crate::{v1::AuthRepository, AppState, ResourceEnum};
|
||||
use anyhow::{bail, Result};
|
||||
use surrealdb::sql::{Id, Thing};
|
||||
|
||||
pub struct GachaRepository<'a> {
|
||||
pub state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_gacha_by_transaction_number(
|
||||
&self,
|
||||
transaction_number: String,
|
||||
) -> Result<GachaResponseDto> {
|
||||
let db = &self.state.surrealdb;
|
||||
|
||||
let result = db
|
||||
.select((ResourceEnum::Gacha.to_string(), transaction_number))
|
||||
.await?;
|
||||
|
||||
match result {
|
||||
Some(response) => Ok(response),
|
||||
None => bail!("Gacha not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_gacha(&self, data: GachaRequestDto) -> Result<String> {
|
||||
let auth_repository = AuthRepository::new(self.state);
|
||||
let db = &self.state.surrealdb;
|
||||
|
||||
let user = auth_repository
|
||||
.query_user_by_email(data.email.clone())
|
||||
.await?;
|
||||
|
||||
let user_thing =
|
||||
Thing::from((ResourceEnum::Users.to_string(), Id::String(user.email)));
|
||||
|
||||
let record: Option<GachaSchema> = db
|
||||
.create((ResourceEnum::Gacha.to_string(), &data.transaction_number))
|
||||
.content(GachaSchema {
|
||||
transaction_number: data.transaction_number.clone(),
|
||||
user: user_thing,
|
||||
})
|
||||
.await?;
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Gacha successfully created".to_string()),
|
||||
None => bail!("Failed to create gacha record"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaSchema {
|
||||
pub transaction_number: String,
|
||||
pub user: Thing,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use super::{GachaRepository, GachaRequestDto};
|
||||
use crate::{common_response, AppState};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
|
||||
pub struct GachaService;
|
||||
|
||||
impl GachaService {
|
||||
pub async fn mutation_create_gacha(
|
||||
payload: GachaRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
let repository = GachaRepository::new(state);
|
||||
|
||||
match repository.query_create_gacha(payload).await {
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use axum::{routing::post, Router};
|
||||
|
||||
pub mod gacha_controller;
|
||||
pub mod gacha_dto;
|
||||
pub mod gacha_repository;
|
||||
pub mod gacha_schema;
|
||||
pub mod gacha_service;
|
||||
|
||||
pub use gacha_dto::*;
|
||||
pub use gacha_repository::*;
|
||||
pub use gacha_schema::*;
|
||||
pub use gacha_service::*;
|
||||
|
||||
pub fn gacha_router() -> Router {
|
||||
Router::new().route("/create", post(gacha_controller::post_create_gacha))
|
||||
}
|
||||
+7
-1
@@ -1,11 +1,17 @@
|
||||
use axum::Router;
|
||||
|
||||
pub mod auth;
|
||||
pub mod docs;
|
||||
pub mod gacha;
|
||||
pub mod users;
|
||||
|
||||
pub use auth::*;
|
||||
pub use docs::*;
|
||||
pub use gacha::*;
|
||||
pub use users::*;
|
||||
|
||||
pub async fn routes() -> Router {
|
||||
Router::new().nest("/auth", auth::auth_router())
|
||||
Router::new()
|
||||
.nest("/auth", auth_router())
|
||||
.nest("/gacha", gacha_router())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod users_dto;
|
||||
pub mod users_schema;
|
||||
|
||||
pub use users_dto::*;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersSchema {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub fullname: String,
|
||||
pub password: String,
|
||||
}
|
||||
Reference in New Issue
Block a user