feat: complete auth system
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
use super::{
|
use super::{
|
||||||
AuthLoginRequestDto, AuthRegisterRequestDto, AuthResendOtpRequestDto, AuthService,
|
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||||
AuthVerifyEmailRequestDto,
|
AuthResendOtpRequestDto, AuthService, AuthVerifyEmailRequestDto,
|
||||||
};
|
};
|
||||||
use crate::{v1::AuthLoginResponsetDto, AppState};
|
use crate::{v1::AuthLoginResponsetDto, AppState};
|
||||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||||
@@ -42,7 +42,7 @@ pub async fn post_register(
|
|||||||
|
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
post,
|
post,
|
||||||
path = "/v1/auth/verify",
|
path = "/v1/auth/verify-email",
|
||||||
request_body = AuthVerifyEmailRequestDto,
|
request_body = AuthVerifyEmailRequestDto,
|
||||||
responses(
|
responses(
|
||||||
(status = 200, description = "Verify email successful", body = MessageResponseDto),
|
(status = 200, description = "Verify email successful", body = MessageResponseDto),
|
||||||
@@ -59,7 +59,7 @@ pub async fn post_verify_email(
|
|||||||
|
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
post,
|
post,
|
||||||
path = "/v1/auth/resend",
|
path = "/v1/auth/send-otp",
|
||||||
request_body = AuthResendOtpRequestDto,
|
request_body = AuthResendOtpRequestDto,
|
||||||
responses(
|
responses(
|
||||||
(status = 200, description = "Resend otp successful", body = MessageResponseDto),
|
(status = 200, description = "Resend otp successful", body = MessageResponseDto),
|
||||||
@@ -107,3 +107,19 @@ pub async fn post_new_password(
|
|||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
AuthService::mutation_new_password(payload, &state).await
|
AuthService::mutation_new_password(payload, &state).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/v1/auth/refresh",
|
||||||
|
request_body = AuthRefreshTokenRequestDto,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Refresh token request successful", body = MessageResponseDto),
|
||||||
|
(status = 401, description = "Refresh token request failed", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Authentication"
|
||||||
|
)]
|
||||||
|
pub async fn post_refresh_token(
|
||||||
|
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
AuthService::mutation_refresh_token(payload).await
|
||||||
|
}
|
||||||
|
|||||||
@@ -97,6 +97,12 @@ pub struct AuthResendOtpRequestDto {
|
|||||||
pub email: String,
|
pub email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct AuthRefreshTokenRequestDto {
|
||||||
|
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
|
||||||
|
pub refresh_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
pub struct AuthNewPasswordRequestDto {
|
pub struct AuthNewPasswordRequestDto {
|
||||||
pub token: String,
|
pub token: String,
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
use crate::{AppState, ResourceEnum, UsersSchema};
|
use super::AuthOtpSchema;
|
||||||
|
use crate::{make_thing, AppState, ResourceEnum, UsersSchema};
|
||||||
use anyhow::{anyhow, bail, Result};
|
use anyhow::{anyhow, bail, Result};
|
||||||
use chrono::{Duration, Utc};
|
use chrono::{Duration, Utc};
|
||||||
|
|
||||||
use super::AuthOtpSchema;
|
|
||||||
|
|
||||||
pub struct AuthRepository<'a> {
|
pub struct AuthRepository<'a> {
|
||||||
state: &'a AppState,
|
state: &'a AppState,
|
||||||
}
|
}
|
||||||
@@ -14,12 +13,16 @@ impl<'a> AuthRepository<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_store_user(&self, user: UsersSchema) -> Result<String> {
|
pub async fn query_store_user(&self, user: UsersSchema) -> Result<String> {
|
||||||
let user_clone = user.clone();
|
let table = ResourceEnum::UsersCache.to_string();
|
||||||
|
let user_id = user.email.clone();
|
||||||
|
let id = make_thing(&table, &user_id);
|
||||||
|
let mut user_to_store = user.clone();
|
||||||
|
user_to_store.id = id.clone();
|
||||||
let record: Option<UsersSchema> = self
|
let record: Option<UsersSchema> = self
|
||||||
.state
|
.state
|
||||||
.surrealdb_mem
|
.surrealdb_mem
|
||||||
.update((ResourceEnum::UsersCache.to_string(), user.email))
|
.create((table, user_id))
|
||||||
.content(user_clone)
|
.content(user_to_store)
|
||||||
.await?;
|
.await?;
|
||||||
match record {
|
match record {
|
||||||
Some(_) => Ok("Success store user data".to_string()),
|
Some(_) => Ok("Success store user data".to_string()),
|
||||||
@@ -52,34 +55,32 @@ impl<'a> AuthRepository<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_get_stored_otp(&self, email: String) -> Result<u32> {
|
pub async fn query_get_stored_otp(&self, email: String) -> Result<u32> {
|
||||||
let otp: Option<AuthOtpSchema> = self
|
let table = ResourceEnum::OtpCache.to_string();
|
||||||
.state
|
let key = (table.as_str(), email.as_str());
|
||||||
.surrealdb_mem
|
let result: Option<AuthOtpSchema> = self.state.surrealdb_mem.select(key).await?;
|
||||||
.select((ResourceEnum::OtpCache.to_string(), &email))
|
match result {
|
||||||
.await?;
|
Some(data) => match Utc::now() > data.expires_at {
|
||||||
match otp {
|
true => {
|
||||||
Some(data) => {
|
let _ = self
|
||||||
if Utc::now() > data.expires_at {
|
|
||||||
let _: Option<AuthOtpSchema> = self
|
|
||||||
.state
|
.state
|
||||||
.surrealdb_mem
|
.surrealdb_mem
|
||||||
.delete((ResourceEnum::OtpCache.to_string(), &email))
|
.delete::<Option<AuthOtpSchema>>(key)
|
||||||
.await?;
|
.await?;
|
||||||
Err(anyhow!("OTP expired"))
|
Err(anyhow!("OTP expired"))
|
||||||
} else {
|
|
||||||
Ok(data.otp)
|
|
||||||
}
|
}
|
||||||
}
|
false => Ok(data.otp),
|
||||||
None => Err(anyhow!("No stored OTP found")),
|
},
|
||||||
|
None => bail!("No stored OTP found"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_store_otp(&self, email: String, otp: u32) -> Result<String> {
|
pub async fn query_store_otp(&self, email: String, otp: u32) -> Result<String> {
|
||||||
let expires_at = Utc::now() + Duration::seconds(300); // 5 menit
|
let expires_at = Utc::now() + Duration::seconds(300);
|
||||||
|
let table = ResourceEnum::OtpCache.to_string();
|
||||||
let record: Option<AuthOtpSchema> = self
|
let record: Option<AuthOtpSchema> = self
|
||||||
.state
|
.state
|
||||||
.surrealdb_mem
|
.surrealdb_mem
|
||||||
.create((ResourceEnum::OtpCache.to_string(), email))
|
.create((table.as_str(), email.as_str()))
|
||||||
.content(AuthOtpSchema { otp, expires_at })
|
.content(AuthOtpSchema { otp, expires_at })
|
||||||
.await?;
|
.await?;
|
||||||
match record {
|
match record {
|
||||||
@@ -89,7 +90,7 @@ impl<'a> AuthRepository<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
|
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
|
||||||
let record: Option<String> = self
|
let record: Option<AuthOtpSchema> = self
|
||||||
.state
|
.state
|
||||||
.surrealdb_mem
|
.surrealdb_mem
|
||||||
.delete((ResourceEnum::OtpCache.to_string(), email))
|
.delete((ResourceEnum::OtpCache.to_string(), email))
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
use super::{
|
use super::{
|
||||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
|
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
|
||||||
AuthRegisterRequestDto, AuthRepository, AuthResendOtpRequestDto,
|
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthRepository,
|
||||||
AuthVerifyEmailRequestDto, TokenDto,
|
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, TokenDto,
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
common_response, encode_access_token, encode_refresh_token, extract_email_token,
|
common_response, decode_refresh_token, encode_access_token, encode_refresh_token,
|
||||||
generate_otp, get_iso_date, hash_password, send_email, success_response,
|
encode_reset_password_token, extract_email_token, generate_otp, get_iso_date,
|
||||||
validate_request, verify_password, AppState, Env, ResourceEnum,
|
hash_password, send_email, success_response, validate_request, verify_password,
|
||||||
ResponseSuccessDto, UsersActiveInactiveSchema, UsersItemDto, UsersRepository,
|
AppState, Env, ResourceEnum, ResponseSuccessDto, UsersActiveInactiveSchema,
|
||||||
UsersSchema,
|
UsersItemDto, UsersRepository, UsersSchema, UsersSetNewPasswordSchema,
|
||||||
};
|
};
|
||||||
use axum::{http::StatusCode, response::Response};
|
use axum::{http::StatusCode, response::Response};
|
||||||
use surrealdb::{
|
use surrealdb::{
|
||||||
@@ -83,8 +83,8 @@ impl AuthService {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(_) = auth_repo.query_store_user(user).await {
|
if let Err(err) = auth_repo.query_store_user(user).await {
|
||||||
return common_response(StatusCode::BAD_REQUEST, "Failed to store data");
|
return common_response(StatusCode::BAD_REQUEST, &err.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
success_response(response)
|
success_response(response)
|
||||||
@@ -200,6 +200,46 @@ impl AuthService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn mutation_refresh_token(
|
||||||
|
payload: AuthRefreshTokenRequestDto,
|
||||||
|
) -> Response {
|
||||||
|
let email = match decode_refresh_token(&payload.refresh_token) {
|
||||||
|
Ok(token) => token.claims.sub,
|
||||||
|
Err(_) => {
|
||||||
|
return common_response(StatusCode::UNAUTHORIZED, "Invalid refresh token");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let access_token = match encode_access_token(email.clone()) {
|
||||||
|
Ok(token) => token,
|
||||||
|
Err(_) => {
|
||||||
|
return common_response(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"Failed to generate access token",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let refresh_token = match encode_refresh_token(email.clone()) {
|
||||||
|
Ok(token) => token,
|
||||||
|
Err(_) => {
|
||||||
|
return common_response(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"Failed to generate refresh token",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = ResponseSuccessDto {
|
||||||
|
data: TokenDto {
|
||||||
|
access_token,
|
||||||
|
refresh_token,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
success_response(response)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn mutation_forgot_password(
|
pub async fn mutation_forgot_password(
|
||||||
payload: AuthResendOtpRequestDto,
|
payload: AuthResendOtpRequestDto,
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
@@ -212,7 +252,7 @@ impl AuthService {
|
|||||||
{
|
{
|
||||||
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
||||||
}
|
}
|
||||||
let token = match encode_access_token(payload.email.clone()) {
|
let token = match encode_reset_password_token(payload.email.clone()) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
return common_response(
|
return common_response(
|
||||||
@@ -240,46 +280,32 @@ impl AuthService {
|
|||||||
) -> Response {
|
) -> Response {
|
||||||
let user_repo = UsersRepository::new(state);
|
let user_repo = UsersRepository::new(state);
|
||||||
let auth_repo = AuthRepository::new(state);
|
let auth_repo = AuthRepository::new(state);
|
||||||
|
let email = payload.email.clone();
|
||||||
match auth_repo.query_get_stored_otp(payload.email.clone()).await {
|
match auth_repo.query_get_stored_otp(email.clone()).await {
|
||||||
Ok(stored_otp) => {
|
Ok(stored_otp) => match stored_otp == payload.otp {
|
||||||
let user_otp = payload.otp;
|
true => match user_repo
|
||||||
let is_otp_valid = stored_otp == user_otp;
|
.query_active_inactive_user(
|
||||||
if is_otp_valid {
|
email.clone(),
|
||||||
match user_repo
|
UsersActiveInactiveSchema { is_active: true },
|
||||||
.query_active_inactive_user(
|
)
|
||||||
payload.email.clone(),
|
.await
|
||||||
UsersActiveInactiveSchema { is_active: true },
|
{
|
||||||
)
|
Ok(_) => match auth_repo.query_delete_stored_otp(email).await {
|
||||||
.await
|
Ok(_) => common_response(StatusCode::OK, "Email verified successfully"),
|
||||||
{
|
Err(e) => {
|
||||||
Ok(_) => {
|
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||||
if let Err(e) = auth_repo
|
|
||||||
.query_delete_stored_otp(payload.email.clone())
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
return common_response(
|
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
&e.to_string(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
common_response(StatusCode::OK, "Email verified successfully")
|
|
||||||
}
|
}
|
||||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
},
|
||||||
}
|
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||||
} else {
|
},
|
||||||
if let Err(e) = auth_repo
|
false => match auth_repo.query_delete_stored_otp(email).await {
|
||||||
.query_delete_stored_otp(payload.email.clone())
|
Ok(_) => common_response(StatusCode::BAD_REQUEST, "Failed to verify OTP"),
|
||||||
.await
|
Err(e) => common_response(
|
||||||
{
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
return common_response(
|
&format!("Failed to delete OTP: {}", e),
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
),
|
||||||
&format!("Failed to delete OTP: {}", e),
|
},
|
||||||
);
|
},
|
||||||
}
|
|
||||||
common_response(StatusCode::BAD_REQUEST, "Failed to verify OTP")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,12 +316,9 @@ impl AuthService {
|
|||||||
) -> Response {
|
) -> Response {
|
||||||
let user_repo = UsersRepository::new(state);
|
let user_repo = UsersRepository::new(state);
|
||||||
let email = extract_email_token(payload.token).unwrap();
|
let email = extract_email_token(payload.token).unwrap();
|
||||||
|
let password = hash_password(&payload.password).unwrap();
|
||||||
match user_repo
|
match user_repo
|
||||||
.query_update_password_user(crate::UsersSetNewPasswordSchema {
|
.query_update_password_user(email, UsersSetNewPasswordSchema { password })
|
||||||
email: email.clone(),
|
|
||||||
password: payload.password.clone(),
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||||
|
|||||||
@@ -14,10 +14,11 @@ pub use auth_service::*;
|
|||||||
|
|
||||||
pub fn auth_router() -> Router {
|
pub fn auth_router() -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/login", post(auth_controller::post_login))
|
|
||||||
.route("/register", post(auth_controller::post_register))
|
|
||||||
.route("/verify", post(auth_controller::post_verify_email))
|
|
||||||
.route("/resend", post(auth_controller::post_resend_otp))
|
|
||||||
.route("/forgot", post(auth_controller::post_forgot_password))
|
.route("/forgot", post(auth_controller::post_forgot_password))
|
||||||
|
.route("/login", post(auth_controller::post_login))
|
||||||
.route("/new-password", post(auth_controller::post_new_password))
|
.route("/new-password", post(auth_controller::post_new_password))
|
||||||
|
.route("/refresh", post(auth_controller::post_refresh_token))
|
||||||
|
.route("/register", post(auth_controller::post_register))
|
||||||
|
.route("/send-otp", post(auth_controller::post_resend_otp))
|
||||||
|
.route("/verify-email", post(auth_controller::post_verify_email))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ use crate::{
|
|||||||
auth, AuthLoginRequestDto, AuthLoginResponsetDto, AuthResendOtpRequestDto,
|
auth, AuthLoginRequestDto, AuthLoginResponsetDto, AuthResendOtpRequestDto,
|
||||||
AuthVerifyEmailRequestDto,
|
AuthVerifyEmailRequestDto,
|
||||||
},
|
},
|
||||||
AuthNewPasswordRequestDto, MessageResponseDto, MetaRequestDto, MetaResponseDto,
|
AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto, MessageResponseDto,
|
||||||
ResponseSuccessDto,
|
MetaRequestDto, MetaResponseDto, ResponseSuccessDto, TokenDto,
|
||||||
};
|
};
|
||||||
|
|
||||||
use utoipa::{
|
use utoipa::{
|
||||||
@@ -19,6 +19,8 @@ use utoipa::{
|
|||||||
auth::auth_controller::post_register,
|
auth::auth_controller::post_register,
|
||||||
auth::auth_controller::post_verify_email,
|
auth::auth_controller::post_verify_email,
|
||||||
auth::auth_controller::post_resend_otp,
|
auth::auth_controller::post_resend_otp,
|
||||||
|
auth::auth_controller::post_refresh_token,
|
||||||
|
auth::auth_controller::post_forgot_password,
|
||||||
auth::auth_controller::post_new_password
|
auth::auth_controller::post_new_password
|
||||||
),
|
),
|
||||||
components(
|
components(
|
||||||
@@ -31,6 +33,8 @@ use utoipa::{
|
|||||||
AuthVerifyEmailRequestDto,
|
AuthVerifyEmailRequestDto,
|
||||||
AuthResendOtpRequestDto,
|
AuthResendOtpRequestDto,
|
||||||
AuthNewPasswordRequestDto,
|
AuthNewPasswordRequestDto,
|
||||||
|
AuthRefreshTokenRequestDto,
|
||||||
|
ResponseSuccessDto<TokenDto>,
|
||||||
ResponseSuccessDto<AuthLoginResponsetDto>,
|
ResponseSuccessDto<AuthLoginResponsetDto>,
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{UsersActiveInactiveSchema, UsersSchema, UsersSetNewPasswordSchema};
|
use super::{UsersActiveInactiveSchema, UsersSchema, UsersSetNewPasswordSchema};
|
||||||
use crate::{AppState, AuthOtpSchema, ResourceEnum};
|
use crate::{get_id, AppState, ResourceEnum};
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
|
|
||||||
pub struct UsersRepository<'a> {
|
pub struct UsersRepository<'a> {
|
||||||
@@ -55,10 +55,8 @@ impl<'a> UsersRepository<'a> {
|
|||||||
|
|
||||||
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
|
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let record: Option<UsersSchema> = db
|
let record_key = get_id(&data.id)?;
|
||||||
.update((ResourceEnum::Users.to_string(), &data.id.id.to_string()))
|
let record: Option<UsersSchema> = db.update(record_key).merge(data).await?;
|
||||||
.merge(data)
|
|
||||||
.await?;
|
|
||||||
match record {
|
match record {
|
||||||
Some(_) => Ok("Success update user".into()),
|
Some(_) => Ok("Success update user".into()),
|
||||||
None => bail!("Failed to update user"),
|
None => bail!("Failed to update user"),
|
||||||
@@ -72,29 +70,30 @@ impl<'a> UsersRepository<'a> {
|
|||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let user = self.query_user_by_email(email.clone()).await?;
|
let user = self.query_user_by_email(email.clone()).await?;
|
||||||
let table = user.id.tb.as_str();
|
let record_key = get_id(&user.id)?;
|
||||||
let id = user.id.id.to_string();
|
let record: Option<UsersSchema> = db
|
||||||
let result: Option<AuthOtpSchema> = db
|
.update(record_key)
|
||||||
.update((table, id))
|
|
||||||
.merge(UsersActiveInactiveSchema {
|
.merge(UsersActiveInactiveSchema {
|
||||||
is_active: data.is_active,
|
is_active: data.is_active,
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
match result {
|
match record {
|
||||||
Some(_) => Ok("Success update user".to_string()),
|
Some(_) => Ok("Success update user".into()),
|
||||||
None => bail!("Failed to update user"),
|
None => bail!("Failed to update user"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_update_password_user(
|
pub async fn query_update_password_user(
|
||||||
&self,
|
&self,
|
||||||
|
email: String,
|
||||||
data: UsersSetNewPasswordSchema,
|
data: UsersSetNewPasswordSchema,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
|
let user = self.query_user_by_email(email).await?;
|
||||||
|
let record_key = get_id(&user.id)?;
|
||||||
let record: Option<UsersSetNewPasswordSchema> = db
|
let record: Option<UsersSetNewPasswordSchema> = db
|
||||||
.update((ResourceEnum::Users.to_string(), &data.email))
|
.update(record_key)
|
||||||
.merge(UsersSetNewPasswordSchema {
|
.merge(UsersSetNewPasswordSchema {
|
||||||
email: data.email.clone(),
|
|
||||||
password: data.password.clone(),
|
password: data.password.clone(),
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -60,7 +60,6 @@ impl Default for UsersSchema {
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct UsersSetNewPasswordSchema {
|
pub struct UsersSetNewPasswordSchema {
|
||||||
pub email: String,
|
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,22 @@ pub fn encode_access_token(sub: String) -> Result<String, StatusCode> {
|
|||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn encode_reset_password_token(sub: String) -> Result<String, StatusCode> {
|
||||||
|
let env = Env::new();
|
||||||
|
let secret: String = env.access_token_secret;
|
||||||
|
let now = Utc::now();
|
||||||
|
let expire: TimeDelta = Duration::minutes(5);
|
||||||
|
let exp: usize = (now + expire).timestamp() as usize;
|
||||||
|
let iat: usize = now.timestamp() as usize;
|
||||||
|
let claim = Claims { iat, exp, sub };
|
||||||
|
encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claim,
|
||||||
|
&EncodingKey::from_secret(secret.as_ref()),
|
||||||
|
)
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn decode_access_token(
|
pub fn decode_access_token(
|
||||||
jwt_token: &str,
|
jwt_token: &str,
|
||||||
) -> Result<TokenData<Claims>, StatusCode> {
|
) -> Result<TokenData<Claims>, StatusCode> {
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
use surrealdb::sql::Thing;
|
||||||
|
|
||||||
|
pub fn get_id(thing: &Thing) -> Result<(&str, &str)> {
|
||||||
|
let table = thing.tb.as_str();
|
||||||
|
let id = match &thing.id {
|
||||||
|
surrealdb::sql::Id::String(s) => s.as_str(),
|
||||||
|
_ => bail!("Unsupported ID type"),
|
||||||
|
};
|
||||||
|
Ok((table, id))
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
use surrealdb::sql::Thing;
|
||||||
|
|
||||||
|
pub fn make_thing(table: &str, id: &str) -> Thing {
|
||||||
|
Thing::from((table, id))
|
||||||
|
}
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
pub mod extract_email;
|
pub mod extract_email;
|
||||||
pub mod generate_date;
|
pub mod generate_date;
|
||||||
pub mod generate_otp;
|
pub mod generate_otp;
|
||||||
|
pub mod get_id;
|
||||||
|
pub mod make_thing;
|
||||||
pub mod response_format;
|
pub mod response_format;
|
||||||
pub mod validator;
|
pub mod validator;
|
||||||
|
|
||||||
pub use extract_email::*;
|
pub use extract_email::*;
|
||||||
pub use generate_date::*;
|
pub use generate_date::*;
|
||||||
pub use generate_otp::*;
|
pub use generate_otp::*;
|
||||||
|
pub use get_id::*;
|
||||||
|
pub use make_thing::*;
|
||||||
pub use response_format::*;
|
pub use response_format::*;
|
||||||
pub use validator::*;
|
pub use validator::*;
|
||||||
|
|||||||
Reference in New Issue
Block a user