Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(users): Separate signup and signin #2921

Merged
merged 15 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions crates/api_models/src/events/user.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};

use crate::user::{ConnectAccountRequest, ConnectAccountResponse};
use crate::user::{SignInRequest, SignInResponse, SignUpRequest, SignUpResponse};

impl ApiEventMetric for ConnectAccountResponse {
impl ApiEventMetric for SignUpResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::User {
merchant_id: self.merchant_id.clone(),
Expand All @@ -11,4 +11,15 @@ impl ApiEventMetric for ConnectAccountResponse {
}
}

impl ApiEventMetric for ConnectAccountRequest {}
impl ApiEventMetric for SignUpRequest {}

impl ApiEventMetric for SignInResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::User {
merchant_id: self.merchant_id.clone(),
user_id: self.user_id.clone(),
})
}
}

impl ApiEventMetric for SignInRequest {}
23 changes: 21 additions & 2 deletions crates/api_models/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,32 @@ use common_utils::pii;
use masking::Secret;

#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
pub struct SignUpRequest {
pub email: pii::Email,
pub password: Secret<String>,
}

#[derive(serde::Serialize, Debug, Clone)]
pub struct ConnectAccountResponse {
pub struct SignUpResponse {
pub token: Secret<String>,
pub merchant_id: String,
pub name: Secret<String>,
pub email: pii::Email,
pub verification_days_left: Option<i64>,
pub user_role: String,
//this field is added for audit/debug reasons
#[serde(skip_serializing)]
pub user_id: String,
}

#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct SignInRequest {
pub email: pii::Email,
pub password: Secret<String>,
}

#[derive(serde::Serialize, Debug, Clone)]
pub struct SignInResponse {
pub token: Secret<String>,
pub merchant_id: String,
pub name: Secret<String>,
Expand Down
127 changes: 62 additions & 65 deletions crates/router/src/core/user.rs
Original file line number Diff line number Diff line change
@@ -1,81 +1,78 @@
use api_models::user as api;
use diesel_models::enums::UserStatus;
use error_stack::IntoReport;
use masking::{ExposeInterface, Secret};
use router_env::env;

use super::errors::{UserErrors, UserResponse};
use crate::{
consts::user as consts, routes::AppState, services::ApplicationResponse, types::domain,
};

pub async fn connect_account(
pub async fn signup(
state: AppState,
request: api::ConnectAccountRequest,
) -> UserResponse<api::ConnectAccountResponse> {
let find_user = state
.store
.find_user_by_email(request.email.clone().expose().expose().as_str())
.await;
request: api::SignUpRequest,
) -> UserResponse<api::SignUpResponse> {
let new_user = domain::NewUser::try_from(request)?;
let _ = new_user
.get_new_merchant()
.get_new_organization()
.insert_org_in_db(state.clone())
.await?;
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
Comment on lines +84 to +86
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

combine with above

Copy link
Contributor Author

@ThisIsMani ThisIsMani Dec 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can't be combined because the above function doesn't return UserFromStorage.

let user_role = new_user
.insert_user_role_in_db(
state.clone(),
consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
let jwt_token = user_from_db
.get_jwt_auth_token(state.clone(), user_role.org_id)
.await?;

if let Ok(found_user) = find_user {
let user_from_db: domain::UserFromStorage = found_user.into();

user_from_db.compare_password(request.password)?;
return Ok(ApplicationResponse::Json(api::SignUpResponse {
token: Secret::new(jwt_token),
merchant_id: user_role.merchant_id,
name: user_from_db.get_name(),
email: user_from_db.get_email(),
verification_days_left: None,
user_role: user_role.role_id,
user_id: user_from_db.get_user_id().to_string(),
}));
}

let user_role = user_from_db.get_role_from_db(state.clone()).await?;
let jwt_token = user_from_db
.get_jwt_auth_token(state.clone(), user_role.org_id)
.await?;
pub async fn signin(
state: AppState,
request: api::SignInRequest,
) -> UserResponse<api::SignInResponse> {
let user_from_db: domain::UserFromStorage = state
.store
.find_user_by_email(request.email.clone().expose().expose().as_str())
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::InvalidCredentials)
} else {
e.change_context(UserErrors::InternalServerError)
}
})?
.into();

return Ok(ApplicationResponse::Json(api::ConnectAccountResponse {
token: Secret::new(jwt_token),
merchant_id: user_role.merchant_id,
name: user_from_db.get_name(),
email: user_from_db.get_email(),
verification_days_left: None,
user_role: user_role.role_id,
user_id: user_from_db.get_user_id().to_string(),
}));
} else if find_user
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
if matches!(env::which(), env::Env::Production) {
return Err(UserErrors::InvalidCredentials).into_report();
}
user_from_db.compare_password(request.password)?;

let new_user = domain::NewUser::try_from(request)?;
let _ = new_user
.get_new_merchant()
.get_new_organization()
.insert_org_in_db(state.clone())
.await?;
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
let user_role = new_user
.insert_user_role_in_db(
state.clone(),
consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
let jwt_token = user_from_db
.get_jwt_auth_token(state.clone(), user_role.org_id)
.await?;
let user_role = user_from_db.get_role_from_db(state.clone()).await?;
let jwt_token = user_from_db
.get_jwt_auth_token(state.clone(), user_role.org_id)
.await?;

return Ok(ApplicationResponse::Json(api::ConnectAccountResponse {
token: Secret::new(jwt_token),
merchant_id: user_role.merchant_id,
name: user_from_db.get_name(),
email: user_from_db.get_email(),
verification_days_left: None,
user_role: user_role.role_id,
user_id: user_from_db.get_user_id().to_string(),
}));
} else {
Err(UserErrors::InternalServerError.into())
}
return Ok(ApplicationResponse::Json(api::SignInResponse {
token: Secret::new(jwt_token),
merchant_id: user_role.merchant_id,
name: user_from_db.get_name(),
email: user_from_db.get_email(),
verification_days_left: None,
user_role: user_role.role_id,
user_id: user_from_db.get_user_id().to_string(),
}));
}
6 changes: 2 additions & 4 deletions crates/router/src/routes/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,10 +737,8 @@ impl User {
pub fn server(state: AppState) -> Scope {
web::scope("/user")
.app_data(web::Data::new(state))
.service(web::resource("/signin").route(web::post().to(user_connect_account)))
.service(web::resource("/signup").route(web::post().to(user_connect_account)))
.service(web::resource("/v2/signin").route(web::post().to(user_connect_account)))
.service(web::resource("/v2/signup").route(web::post().to(user_connect_account)))
.service(web::resource("/signin").route(web::post().to(user_signin)))
.service(web::resource("/signup").route(web::post().to(user_signup)))
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/router/src/routes/lock_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,

Flow::UserConnectAccount => Self::User,
Flow::UserSignUp | Flow::UserSignIn => Self::User,
}
}
}
27 changes: 23 additions & 4 deletions crates/router/src/routes/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,38 @@ use crate::{
},
};

pub async fn user_connect_account(
pub async fn user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::ConnectAccountRequest>,
json_payload: web::Json<user_api::SignUpRequest>,
) -> HttpResponse {
let flow = Flow::UserConnectAccount;
let flow = Flow::UserSignUp;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _, req_body| user::connect_account(state, req_body),
|state, _, req_body| user::signup(state, req_body),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}

pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignInRequest>,
) -> HttpResponse {
let flow = Flow::UserSignIn;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _, req_body| user::signin(state, req_body),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
Expand Down
12 changes: 6 additions & 6 deletions crates/router/src/types/domain/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ impl NewUserOrganization {
}
}

impl From<user_api::ConnectAccountRequest> for NewUserOrganization {
fn from(_value: user_api::ConnectAccountRequest) -> Self {
impl From<user_api::SignUpRequest> for NewUserOrganization {
fn from(_value: user_api::SignUpRequest) -> Self {
let new_organization = api_org::OrganizationNew::new(None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
Expand Down Expand Up @@ -287,10 +287,10 @@ impl NewUserMerchant {
}
}

impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant {
impl TryFrom<user_api::SignUpRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;

fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let merchant_id = format!("merchant_{}", common_utils::date_time::now_unix_timestamp());
let new_organization = NewUserOrganization::from(value);

Expand Down Expand Up @@ -406,10 +406,10 @@ impl TryFrom<NewUser> for storage_user::UserNew {
}
}

impl TryFrom<user_api::ConnectAccountRequest> for NewUser {
impl TryFrom<user_api::SignUpRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;

fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::try_from(value.email.clone())?;
Expand Down
6 changes: 4 additions & 2 deletions crates/router_env/src/logger/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,10 @@ pub enum Flow {
GsmRuleUpdate,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// User connect account
UserConnectAccount,
/// User Sign Up
UserSignUp,
/// User Sign In
UserSignIn,
}

///
Expand Down
Loading