refactor(roles): Add more checks in create, update role APIs and change the response type (#3896)

This commit is contained in:
Mani Chandra
2024-02-29 19:26:46 +05:30
committed by GitHub
parent 7db499d8a9
commit 0136523f38
4 changed files with 81 additions and 53 deletions

View File

@ -1,10 +1,12 @@
use api_models::user_role as user_role_api;
use common_enums::PermissionGroup;
use error_stack::ResultExt;
use crate::{
core::errors::{UserErrors, UserResult},
routes::AppState,
services::authorization::permissions::Permission,
services::authorization::{permissions::Permission, roles},
types::domain,
};
impl From<Permission> for user_role_api::Permission {
@ -40,23 +42,44 @@ impl From<Permission> for user_role_api::Permission {
}
}
pub async fn is_role_name_already_present_for_merchant(
pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
if groups.is_empty() {
return Err(UserErrors::InvalidRoleOperation.into())
.attach_printable("Role groups cannot be empty");
}
if groups.contains(&PermissionGroup::OrganizationManage) {
return Err(UserErrors::InvalidRoleOperation.into())
.attach_printable("Organization manage group cannot be added to role");
}
Ok(())
}
pub async fn validate_role_name(
state: &AppState,
role_name: &str,
role_name: &domain::RoleName,
merchant_id: &str,
org_id: &str,
) -> UserResult<()> {
let role_name_list: Vec<String> = state
let role_name_str = role_name.clone().get_role_name();
let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES
.iter()
.any(|(_, role_info)| role_info.get_role_name() == role_name_str);
// TODO: Create and use find_by_role_name to make this efficient
let is_present_in_custom_roles = state
.store
.list_all_roles(merchant_id, org_id)
.await
.change_context(UserErrors::InternalServerError)?
.iter()
.map(|role| role.role_name.to_owned())
.collect();
.any(|role| role.role_name == role_name_str);
if role_name_list.contains(&role_name.to_string()) {
if is_present_in_predefined_roles || is_present_in_custom_roles {
return Err(UserErrors::RoleNameAlreadyExists.into());
}
Ok(())
}