diff --git a/.env.template b/.env.template index 92362088..194aa9de 100644 --- a/.env.template +++ b/.env.template @@ -210,6 +210,15 @@ ## For public server (URL with path) # DOMAIN=https://domain.tld/vw +## Default locale used for localized templates. +## Supported format: language or language-region (for example: en, en-US, ru, uk-UA) +# DEFAULT_LOCALE=en + +## Optional runtime locale catalogs for API/admin text localization. +## Drop JSON files into: %DATA_FOLDER%/locales/.json (for example: data/locales/de.json) +## The JSON must be a flat key-value object where values are translated strings. +## Runtime catalogs override built-in keys and allow adding new languages without recompiling. + ## Controls whether users are allowed to create Bitwarden Sends. ## This setting applies globally to all users. ## To control this on a per-org basis instead, use the "Disable Send" org policy. diff --git a/Cargo.lock b/Cargo.lock index 6cef9e27..3fe2e721 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2665,6 +2665,25 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "include_dir" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -5911,6 +5930,7 @@ dependencies = [ "hickory-resolver", "html5gum", "http 1.5.0", + "include_dir", "ipnet", "job_scheduler_ng", "jsonwebtoken", diff --git a/Cargo.toml b/Cargo.toml index 78791730..7bd9ed3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,9 +105,10 @@ tokio-util = { version = "0.7.20", features = ["compat"] } # A generic serialization/deserialization framework serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +include_dir = "0.7.4" # A safe, extensible ORM and Query builder -diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric"] } +diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric", "64-column-tables"] } diesel_migrations = "2.3.2" derive_more = { version = "2.1.1", features = [ diff --git a/src/api/admin.rs b/src/api/admin.rs index 1a2b8c9a..5947fea7 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -19,7 +19,7 @@ use crate::{ core::{log_event, two_factor}, push_logout_to_relay, unregister_push_device, }, - auth::{ClientIp, Secure, decode_admin, encode_jwt, generate_admin_claims}, + auth::{ClientIp, RequestLocale, Secure, decode_admin, encode_jwt, generate_admin_claims}, config::ConfigBuilder, db::{ ACTIVE_DB_TYPE, DbConn, DbConnType, backup_sqlite, get_sql_server_version, @@ -141,6 +141,21 @@ fn admin_url() -> String { format!("{}{}", CONFIG.domain_origin(), admin_path()) } +fn localized_admin_template_name(template_name: &str, locale: &str) -> String { + for candidate in crate::i18n::locale_candidates(locale) { + let Some(rest) = template_name.strip_prefix("admin/") else { + return template_name.to_owned(); + }; + + let localized = format!("admin/{candidate}/{rest}"); + if CONFIG.has_template(&localized) { + return localized; + } + } + + template_name.to_owned() +} + #[derive(Responder)] enum AdminResponse { #[response(status = 200)] @@ -153,25 +168,36 @@ enum AdminResponse { #[catch(401)] fn admin_login(request: &Request<'_>) -> ApiResult> { + let locale = + crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale()); if request.format() == Some(&MediaType::JSON) { - err_code!("Authorization failed.", Status::Unauthorized.code); + err_code!(crate::i18n::authorization_failed(&locale), Status::Unauthorized.code); } let redirect = request.segments::(0..).unwrap_or_default().display().to_string(); - render_admin_login(None, Some(&redirect)) + render_admin_login(None, Some(&redirect), &locale) } -fn render_admin_login(msg: Option<&str>, redirect: Option<&str>) -> ApiResult> { +fn render_admin_login(msg: Option<&str>, redirect: Option<&str>, locale: &str) -> ApiResult> { // If there is an error, show it - let msg = msg.map(|msg| format!("Error: {msg}")); + let msg = msg.map(|msg| { + if crate::i18n::is_russian(locale) { + format!("Ошибка: {msg}") + } else { + format!("Error: {msg}") + } + }); + let page_content = localized_admin_template_name("admin/login", locale); let json = json!({ - "page_content": "admin/login", + "page_content": page_content, "error": msg, "redirect": redirect, - "urlpath": CONFIG.domain_path() + "urlpath": CONFIG.domain_path(), + "lang": locale, }); // Return the page - let text = CONFIG.render_template(BASE_TEMPLATE, &json)?; + let template_name = localized_admin_template_name(BASE_TEMPLATE, locale); + let text = CONFIG.render_template(&template_name, &json)?; Ok(Html(text)) } @@ -182,10 +208,12 @@ struct LoginForm { } #[post("/", format = "application/x-www-form-urlencoded", data = "")] +#[allow(clippy::needless_pass_by_value)] fn post_admin_login( data: Form, cookies: &CookieJar<'_>, ip: ClientIp, + locale: RequestLocale, secure: Secure, ) -> Result { let data = data.into_inner(); @@ -193,8 +221,9 @@ fn post_admin_login( if crate::ratelimit::check_limit_admin(&ip.ip).is_err() { return Err(AdminResponse::TooManyRequests(render_admin_login( - Some("Too many requests, try again later."), + Some(crate::i18n::admin_login_too_many_requests(&locale.locale)), redirect.as_deref(), + &locale.locale, ))); } @@ -203,7 +232,13 @@ fn post_admin_login( // If the token received is valid, generate JWT and save it as a cookie let claims = match generate_admin_claims() { Ok(claims) => claims, - Err(e) => return Err(AdminResponse::Ok(render_admin_login(Some(e.message()), redirect.as_deref()))), + Err(e) => { + return Err(AdminResponse::Ok(render_admin_login( + Some(e.message()), + redirect.as_deref(), + &locale.locale, + ))); + } }; let jwt = encode_jwt(&claims); @@ -218,13 +253,14 @@ fn post_admin_login( if let Some(redirect) = redirect { Ok(Redirect::to(format!("{}{redirect}", admin_path()))) } else { - Err(AdminResponse::Ok(render_admin_page())) + Err(AdminResponse::Ok(render_admin_page(&locale.locale))) } } else { error!("Invalid admin token. IP: {}", ip.ip); Err(AdminResponse::Unauthorized(render_admin_login( - Some("Invalid admin token, please try again."), + Some(crate::i18n::admin_login_invalid_token(&locale.locale)), redirect.as_deref(), + &locale.locale, ))) } } @@ -256,41 +292,46 @@ struct AdminTemplateData { logged_in: bool, urlpath: String, sso_enabled: bool, + lang: String, } impl AdminTemplateData { - fn new(page_content: &str, page_data: Value) -> Self { + fn new(page_content: &str, page_data: Value, locale: &str) -> Self { Self { - page_content: String::from(page_content), + page_content: localized_admin_template_name(page_content, locale), page_data: Some(page_data), logged_in: true, urlpath: CONFIG.domain_path(), sso_enabled: CONFIG.sso_enabled(), + lang: locale.to_owned(), } } fn render(self) -> Result { - CONFIG.render_template(BASE_TEMPLATE, &self) + let template_name = localized_admin_template_name(BASE_TEMPLATE, &self.lang); + CONFIG.render_template(&template_name, &self) } } -fn render_admin_page() -> ApiResult> { +fn render_admin_page(locale: &str) -> ApiResult> { let settings_json = json!({ "config": CONFIG.prepare_json(), "can_backup": *CAN_BACKUP, }); - let text = AdminTemplateData::new("admin/settings", settings_json).render()?; + let text = AdminTemplateData::new("admin/settings", settings_json, locale).render()?; Ok(Html(text)) } #[get("/")] -fn admin_page(_token: AdminToken) -> ApiResult> { - render_admin_page() +#[allow(clippy::needless_pass_by_value)] +fn admin_page(_token: AdminToken, locale: RequestLocale) -> ApiResult> { + render_admin_page(&locale.locale) } #[get("/", rank = 2)] -fn admin_page_login() -> ApiResult> { - render_admin_login(None, None) +#[allow(clippy::needless_pass_by_value)] +fn admin_page_login(locale: RequestLocale) -> ApiResult> { + render_admin_login(None, None, &locale.locale) } #[derive(Debug, Deserialize)] @@ -338,13 +379,13 @@ async fn invite_user(data: Json, _token: AdminToken, conn: DbConn) - } #[post("/test/smtp", format = "application/json", data = "")] -async fn test_smtp(data: Json, _token: AdminToken) -> EmptyResult { +async fn test_smtp(data: Json, _token: AdminToken, locale: RequestLocale) -> EmptyResult { let data: InviteData = data.into_inner(); if CONFIG.mail_enabled() { - mail::send_test(&data.email).await + mail::send_test_for_locale(&data.email, Some(&locale.locale)).await } else { - err!("Mail is not enabled") + err!(crate::i18n::admin_mail_not_enabled(&locale.locale)) } } @@ -373,7 +414,7 @@ async fn get_users_json(_token: AdminToken, conn: DbConn) -> Json { } #[get("/users/overview")] -async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult> { +async fn users_overview(_token: AdminToken, locale: RequestLocale, conn: DbConn) -> ApiResult> { let users = User::get_all(&conn).await; let mut users_json = Vec::with_capacity(users.len()); for (u, sso_u) in users { @@ -393,7 +434,7 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult, token: AdminToken, conn: DbConn) -> EmptyResult { +async fn update_membership_type( + data: Json, + token: AdminToken, + locale: RequestLocale, + conn: DbConn, +) -> EmptyResult { let data: MembershipTypeData = data.into_inner(); let Some(mut member_to_edit) = Membership::find_by_user_and_org(&data.user_uuid, &data.org_uuid, &conn).await else { - err!("The specified user isn't member of the organization") + err!(crate::i18n::org_user_not_member(&locale.locale)) }; let new_type = if let Some(new_type) = MembershipType::from_str(&data.user_type.into_string()) { new_type as i32 } else { - err!("Invalid type") + err!(crate::i18n::org_invalid_type(&locale.locale)) }; if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner { // Removing owner permission, check that there is at least one other confirmed owner if Membership::count_confirmed_by_org_and_type(&data.org_uuid, MembershipType::Owner, &conn).await <= 1 { - err!("Can't change the type of the last owner") + err!(crate::i18n::admin_cannot_change_last_owner_type(&locale.locale)) } } @@ -602,7 +648,7 @@ async fn update_revision_users(_token: AdminToken, conn: DbConn) -> EmptyResult } #[get("/organizations/overview")] -async fn organizations_overview(_token: AdminToken, conn: DbConn) -> ApiResult> { +async fn organizations_overview(_token: AdminToken, locale: RequestLocale, conn: DbConn) -> ApiResult> { let organizations = Organization::get_all(&conn).await; let mut organizations_json = Vec::with_capacity(organizations.len()); for o in organizations { @@ -617,13 +663,14 @@ async fn organizations_overview(_token: AdminToken, conn: DbConn) -> ApiResult/delete", format = "application/json")] async fn delete_organization(org_id: OrganizationId, _token: AdminToken, conn: DbConn) -> EmptyResult { - let org = Organization::find_by_uuid(&org_id, &conn).await.map_res("Organization doesn't exist")?; + let locale = CONFIG.default_locale(); + let org = Organization::find_by_uuid(&org_id, &conn).await.map_res(crate::i18n::org_not_found_short(&locale))?; org.delete(&conn).await } @@ -759,7 +806,12 @@ fn folder_has_hbs_files(dir: &std::path::Path) -> bool { } #[get("/diagnostics")] -async fn diagnostics(_token: AdminToken, ip_header: IpHeader, conn: DbConn) -> ApiResult> { +async fn diagnostics( + _token: AdminToken, + locale: RequestLocale, + ip_header: IpHeader, + conn: DbConn, +) -> ApiResult> { use chrono::prelude::*; use std::net::ToSocketAddrs; @@ -826,7 +878,7 @@ async fn diagnostics(_token: AdminToken, ip_header: IpHeader, conn: DbConn) -> A "ntp_time": get_ntp_time(has_http_access).await, // Run the ntp check as late as possible to minimize the time difference }); - let text = AdminTemplateData::new("admin/diagnostics", diagnostics_json).render()?; + let text = AdminTemplateData::new("admin/diagnostics", diagnostics_json, &locale.locale).render()?; Ok(Html(text)) } @@ -845,7 +897,7 @@ fn get_diagnostics_http(code: u16, _token: AdminToken) -> EmptyResult { async fn post_config(data: Json, _token: AdminToken) -> EmptyResult { let data: ConfigBuilder = data.into_inner(); if let Err(e) = CONFIG.update_config(data, true).await { - err!(format!("Unable to save config: {e:?}")) + err!(crate::i18n::admin_unable_save_config(&CONFIG.default_locale()), format!("{e:?}")) } Ok(()) } @@ -853,20 +905,21 @@ async fn post_config(data: Json, _token: AdminToken) -> EmptyResu #[post("/config/delete", format = "application/json")] async fn delete_config(_token: AdminToken) -> EmptyResult { if let Err(e) = CONFIG.delete_user_config().await { - err!(format!("Unable to delete config: {e:?}")) + err!(crate::i18n::admin_unable_delete_config(&CONFIG.default_locale()), format!("{e:?}")) } Ok(()) } #[post("/config/backup_db", format = "application/json")] -fn backup_db(_token: AdminToken) -> ApiResult { +#[allow(clippy::needless_pass_by_value)] +fn backup_db(_token: AdminToken, locale: RequestLocale) -> ApiResult { if *CAN_BACKUP { match backup_sqlite() { Ok(f) => Ok(format!("Backup to '{f}' was successful")), - Err(e) => err!(format!("Backup was unsuccessful {e}")), + Err(e) => err!(crate::i18n::admin_backup_unsuccessful(&locale.locale), e.to_string()), } } else { - err!("Can't back up current DB (Only SQLite supports this feature)"); + err!(crate::i18n::admin_backup_only_sqlite(&locale.locale)); } } diff --git a/src/api/core/accounts.rs b/src/api/core/accounts.rs index cd280bc7..5c0e1e92 100644 --- a/src/api/core/accounts.rs +++ b/src/api/core/accounts.rs @@ -248,9 +248,9 @@ fn clean_password_hint(password_hint: Option<&String>) -> Option { } } -fn enforce_password_hint_setting(password_hint: Option<&String>) -> EmptyResult { +fn enforce_password_hint_setting(password_hint: Option<&String>, locale: &str) -> EmptyResult { if password_hint.is_some() && !CONFIG.password_hints_allowed() { - err!("Password hints have been disabled by the administrator. Remove the hint and try again."); + err!(crate::i18n::accounts_password_hints_disabled(locale)); } Ok(()) } @@ -267,7 +267,7 @@ async fn is_email_2fa_required(member_id: Option, conn: &DbConn) - false } -pub async fn register(data: Json, conn: DbConn) -> JsonResult { +pub async fn register(data: Json, conn: DbConn, locale: &str) -> JsonResult { let data: RegisterData = data.into_inner(); let email = data.email.to_lowercase(); @@ -290,7 +290,7 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { (Some(email_verification_token), None, None, None, None) => { let claims = crate::auth::decode_register_verify(email_verification_token)?; if claims.sub != data.email { - err!("Email verification token does not match email"); + err!(crate::i18n::accounts_email_verification_token_mismatch(locale)); } // During this call we don't get the name, so extract it from the claims @@ -300,16 +300,16 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { // Emergency access registration (None, Some(accept_emergency_access_id), Some(accept_emergency_access_invite_token), None, None) => { if !CONFIG.emergency_access_allowed() { - err!("Emergency access is not enabled.") + err!(crate::i18n::accounts_emergency_access_not_enabled(locale)) } let claims = crate::auth::decode_emergency_access_invite(accept_emergency_access_invite_token)?; if claims.email != data.email { - err!("Claim email does not match email") + err!(crate::i18n::accounts_claim_email_mismatch(locale)) } if &claims.emer_id != accept_emergency_access_id { - err!("Claim emer_id does not match accept_emergency_access_id") + err!(crate::i18n::accounts_claim_emer_id_mismatch(locale)) } pending_emergency_access = Some((accept_emergency_access_id, claims)); @@ -320,18 +320,18 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { let claims = decode_invite(org_invite_token)?; if claims.email != data.email { - err!("Claim email does not match email") + err!(crate::i18n::accounts_claim_email_mismatch(locale)) } if &claims.member_id != organization_user_id { - err!("Claim org_user_id does not match organization_user_id") + err!(crate::i18n::accounts_claim_org_user_id_mismatch(locale)) } true } _ => { - err!("Registration is missing required parameters") + err!(crate::i18n::accounts_registration_missing_required_params(locale)) } }; @@ -340,18 +340,18 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { if let Some(ref name) = name && name.len() > 50 { - err!("The field Name must be a string with a maximum length of 50."); + err!(crate::i18n::accounts_name_too_long(locale)); } // Check against the password hint setting here so if it fails, the user // can retry without losing their invitation below. let password_hint = clean_password_hint(data.master_password_hint.as_ref()); - enforce_password_hint_setting(password_hint.as_ref())?; + enforce_password_hint_setting(password_hint.as_ref(), locale)?; let mut user = match User::find_by_mail(&email, &conn).await { Some(user) => { if !user.password_hash.is_empty() { - err!("Registration not allowed or user already exists") + err!(crate::i18n::accounts_registration_not_allowed_or_exists(locale)) } if let Some(token) = data.org_invite_token.as_ref() { @@ -361,7 +361,7 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { email_verified = true; user } else { - err!("Registration email does not match invite email") + err!(crate::i18n::accounts_registration_email_invite_mismatch(locale)) } } else if Invitation::take(&email, &conn).await { Membership::accept_user_invitations(&user.uuid, &conn).await?; @@ -372,7 +372,7 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { { user } else { - err!("Registration not allowed or user already exists") + err!(crate::i18n::accounts_registration_not_allowed_or_exists(locale)) } } None => { @@ -385,7 +385,7 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { { User::new(&email, None) } else { - err!("Registration not allowed or user already exists") + err!(crate::i18n::accounts_registration_not_allowed_or_exists(locale)) } } }; @@ -393,6 +393,8 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { // Make sure we don't leave a lingering invitation. Invitation::take(&email, &conn).await; + user.locale = Some(crate::i18n::normalize_locale(locale)); + set_kdf_data(&mut user, data.kdf())?; user.set_password(&data.hash(), Some(data.key()), true, None, &conn).await?; @@ -414,11 +416,11 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { if CONFIG.mail_enabled() { if CONFIG.signups_verify() && !email_verified { - if let Err(e) = mail::send_welcome_must_verify(&user.email, &user.uuid).await { + if let Err(e) = mail::send_welcome_must_verify_for_locale(&user.email, &user.uuid, Some(locale)).await { error!("Error sending welcome email: {e:#?}"); } user.last_verifying_at = Some(user.created_at); - } else if let Err(e) = mail::send_welcome(&user.email).await { + } else if let Err(e) = mail::send_welcome_for_locale(&user.email, Some(locale)).await { error!("Error sending welcome email: {e:#?}"); } @@ -444,16 +446,17 @@ pub async fn register(data: Json, conn: DbConn) -> JsonResult { #[post("/accounts/set-password", data = "")] async fn post_set_password(data: Json, headers: Headers, conn: DbConn) -> JsonResult { let data: SetPasswordData = data.into_inner(); + let locale = &headers.locale; let mut user = headers.user; if user.private_key.is_some() || !user.password_hash.is_empty() { - err!("Account already initialized, cannot set password") + err!(crate::i18n::accounts_account_already_initialized(locale)) } // Check against the password hint setting here so if it fails, // the user can retry without losing their invitation below. let password_hint = clean_password_hint(data.master_password_hint.as_ref()); - enforce_password_hint_setting(password_hint.as_ref())?; + enforce_password_hint_setting(password_hint.as_ref(), locale)?; set_kdf_data(&mut user, &data.kdf)?; @@ -477,18 +480,18 @@ async fn post_set_password(data: Json, headers: Headers, conn: && identifier != crate::api::admin::FAKE_ADMIN_UUID { let Some(org) = Organization::find_by_uuid(&identifier.into(), &conn).await else { - err!("Failed to retrieve the associated organization") + err!(crate::i18n::accounts_associated_org_not_found(locale)) }; let Some(membership) = Membership::find_by_user_and_org(&user.uuid, &org.uuid, &conn).await else { - err!("Failed to retrieve the invitation") + err!(crate::i18n::accounts_invitation_not_found(locale)) }; accept_org_invite(&user, membership, None, &conn).await?; } if CONFIG.mail_enabled() { - mail::send_welcome(&user.email.to_lowercase()).await?; + mail::send_welcome_for_locale(&user.email.to_lowercase(), Some(locale)).await?; } else { Membership::accept_user_invitations(&user.uuid, &conn).await?; } @@ -510,7 +513,7 @@ async fn profile(headers: Headers, conn: DbConn) -> Json { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct ProfileData { - // culture: String, // Ignored, always use en-US + culture: Option, name: String, } @@ -526,11 +529,14 @@ async fn post_profile(data: Json, headers: Headers, conn: DbConn) - // Check if the length of the username exceeds 50 characters (Same is Upstream Bitwarden) // This also prevents issues with very long usernames causing to large JWT's. See #2419 if data.name.len() > 50 { - err!("The field Name must be a string with a maximum length of 50."); + err!(crate::i18n::accounts_name_too_long(&headers.locale)); } let mut user = headers.user; user.name = data.name; + if let Some(culture) = data.culture { + user.locale = Some(crate::i18n::normalize_locale(&culture)); + } user.save(&conn).await?; Ok(Json(user.to_json(&conn).await)) @@ -552,7 +558,7 @@ async fn put_avatar(data: Json, headers: Headers, conn: DbConn) -> J if let Some(color) = &data.avatar_color && color.len() != 7 { - err!("The field AvatarColor must be a HTML/Hex color code with a length of 7 characters") + err!(crate::i18n::accounts_avatar_color_invalid(&headers.locale)) } let mut user = headers.user; @@ -602,7 +608,7 @@ async fn post_keys(data: Json, headers: Headers, conn: DbConn) -> Json let mut user = headers.user; if user.private_key.is_some() || user.public_key.is_some() { - err!("User has existing keypair") + err!(crate::i18n::accounts_existing_keypair(&headers.locale)) } user.private_key = Some(data.encrypted_private_key); @@ -636,7 +642,7 @@ async fn post_password(data: Json, headers: Headers, conn: DbCon let user = headers.user; if !user.check_valid_password(&data.master_password_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } log_user_event(EventType::UserChangedPassword, &user.uuid, headers.device.atype, &headers.ip.ip, &conn).await; @@ -644,24 +650,24 @@ async fn post_password(data: Json, headers: Headers, conn: DbCon let (new_master_password_hash, new_key) = if let (Some(unlock_data), Some(authentication_data)) = (data.unlock_data, data.authentication_data) { if authentication_data.kdf != unlock_data.kdf { - err!("KDF settings must be equal for authentication and unlock") + err!(crate::i18n::accounts_kdf_auth_unlock_mismatch(&headers.locale)) } if user.email != authentication_data.salt || user.email != unlock_data.salt { - err!("Invalid master password salt") + err!(crate::i18n::accounts_invalid_master_password_salt(&headers.locale)) } (authentication_data.master_password_authentication_hash, unlock_data.master_key_wrapped_user_key) } else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) { (new_master_password_hash, new_key) } else { - err!("Invalid request!") + err!(crate::i18n::accounts_invalid_request(&headers.locale)) }; let mut user = user; user.password_hint = clean_password_hint(data.master_password_hint.as_ref()); - enforce_password_hint_setting(user.password_hint.as_ref())?; + enforce_password_hint_setting(user.password_hint.as_ref(), &headers.locale)?; user.set_password( &new_master_password_hash, @@ -688,29 +694,30 @@ async fn post_password(data: Json, headers: Headers, conn: DbCon } fn set_kdf_data(user: &mut User, data: &KDFData) -> EmptyResult { + let locale = &CONFIG.default_locale(); if data.kdf == UserKdfType::Pbkdf2 as i32 && data.kdf_iterations < 100_000 { - err!("PBKDF2 KDF iterations must be at least 100000.") + err!(crate::i18n::accounts_pbkdf2_min_iterations(locale)) } if data.kdf == UserKdfType::Argon2id as i32 { if data.kdf_iterations < 1 { - err!("Argon2 KDF iterations must be at least 1.") + err!(crate::i18n::accounts_argon2_min_iterations(locale)) } if let Some(m) = data.kdf_memory { if !(15..=1024).contains(&m) { - err!("Argon2 memory must be between 15 MB and 1024 MB.") + err!(crate::i18n::accounts_argon2_memory_range(locale)) } user.client_kdf_memory = data.kdf_memory; } else { - err!("Argon2 memory parameter is required.") + err!(crate::i18n::accounts_argon2_memory_required(locale)) } if let Some(p) = data.kdf_parallelism { if !(1..=16).contains(&p) { - err!("Argon2 parallelism must be between 1 and 16.") + err!(crate::i18n::accounts_argon2_parallelism_range(locale)) } user.client_kdf_parallelism = data.kdf_parallelism; } else { - err!("Argon2 parallelism parameter is required.") + err!(crate::i18n::accounts_argon2_parallelism_required(locale)) } } else { user.client_kdf_memory = None; @@ -735,12 +742,13 @@ pub(super) struct AuthenticationData { impl AuthenticationData { pub(super) fn check(&self, user: &User, unlock: &UnlockData) -> EmptyResult { + let locale = &CONFIG.default_locale(); if self.kdf != unlock.kdf { - err!("KDF settings must be equal for authentication and unlock") + err!(crate::i18n::accounts_kdf_auth_unlock_mismatch(locale)) } if self.salt != user.master_password_salt() || self.salt != unlock.salt { - err!("Invalid master password salt") + err!(crate::i18n::accounts_invalid_master_password_salt(locale)) } Ok(()) @@ -768,7 +776,7 @@ async fn post_kdf(data: Json, headers: Headers, conn: DbConn, nt: let data: ChangeKdfData = data.into_inner(); if !headers.user.check_valid_password(&data.master_password_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } data.authentication_data.check(&headers.user, &data.unlock_data)?; @@ -870,16 +878,17 @@ fn validate_keydata( existing_sends: &[Send], user: &User, ) -> EmptyResult { + let locale = &CONFIG.default_locale(); if user.client_kdf_type != data.account_unlock_data.master_password_unlock_data.kdf_type || user.client_kdf_iter != data.account_unlock_data.master_password_unlock_data.kdf_iterations || user.client_kdf_memory != data.account_unlock_data.master_password_unlock_data.kdf_memory || user.client_kdf_parallelism != data.account_unlock_data.master_password_unlock_data.kdf_parallelism || user.email != data.account_unlock_data.master_password_unlock_data.email { - err!("Changing the kdf variant or email is not supported during key rotation"); + err!(crate::i18n::accounts_rotate_kdf_or_email_change_not_supported(locale)); } if user.public_key.as_ref() != Some(&data.account_keys.account_public_key) { - err!("Changing the asymmetric keypair is not possible during key rotation") + err!(crate::i18n::accounts_rotate_asymmetric_keypair_change_not_supported(locale)) } // Check that we're correctly rotating all the user's ciphers @@ -892,7 +901,7 @@ fn validate_keydata( .filter_map(|c| c.id.as_ref()) .collect::>(); if !provided_cipher_ids.is_superset(&existing_cipher_ids) { - err!("All existing ciphers must be included in the rotation") + err!(crate::i18n::accounts_rotate_all_ciphers_required(locale)) } // Check that we're correctly rotating all the user's folders @@ -900,7 +909,7 @@ fn validate_keydata( let provided_folder_ids = data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::>(); if !provided_folder_ids.is_superset(&existing_folder_ids) { - err!("All existing folders must be included in the rotation") + err!(crate::i18n::accounts_rotate_all_folders_required(locale)) } // Check that we're correctly rotating all the user's emergency access keys @@ -913,7 +922,7 @@ fn validate_keydata( .map(|ea| &ea.id) .collect::>(); if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) { - err!("All existing emergency access keys must be included in the rotation") + err!(crate::i18n::accounts_rotate_all_emergency_access_required(locale)) } // Check that we're correctly rotating all the user's reset password keys @@ -926,14 +935,14 @@ fn validate_keydata( .map(|rp| &rp.organization_id) .collect::>(); if !provided_reset_password_ids.is_superset(&existing_reset_password_ids) { - err!("All existing reset password keys must be included in the rotation") + err!(crate::i18n::accounts_rotate_all_reset_password_required(locale)) } // Check that we're correctly rotating all the user's sends let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::>(); let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::>(); if !provided_send_ids.is_superset(&existing_send_ids) { - err!("All existing sends must be included in the rotation") + err!(crate::i18n::accounts_rotate_all_sends_required(locale)) } Ok(()) @@ -945,7 +954,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: let data: KeyData = data.into_inner(); if !headers.user.check_valid_password(&data.old_master_key_authentication_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } // Validate the import before continuing @@ -982,7 +991,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: // See: https://github.com/bitwarden/clients/issues/8453 if let Some(folder_id) = folder_data.id { let Some(saved_folder) = existing_folders.iter_mut().find(|f| f.uuid == folder_id) else { - err!("Folder doesn't exist") + err!(crate::i18n::accounts_folder_not_found(&headers.locale)) }; saved_folder.name = folder_data.name; @@ -995,7 +1004,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: let Some(saved_emergency_access) = existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id) else { - err!("Emergency access doesn't exist or is not owned by the user") + err!(crate::i18n::accounts_emergency_access_not_found_or_not_owned(&headers.locale)) }; saved_emergency_access.key_encrypted = Some(emergency_access_data.key_encrypted); @@ -1007,7 +1016,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: let Some(membership) = existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id) else { - err!("Reset password doesn't exist") + err!(crate::i18n::accounts_reset_password_not_found(&headers.locale)) }; membership.reset_password_key = Some(reset_password_data.reset_password_key); @@ -1017,7 +1026,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: // Update send data for send_data in data.account_data.sends { let Some(send) = send_data.id.as_ref().and_then(|id| existing_sends.iter_mut().find(|s| &s.uuid == id)) else { - err!("Send doesn't exist") + err!(crate::i18n::accounts_send_not_found(&headers.locale)) }; // Like upstream, only the key changes on rotation @@ -1031,7 +1040,7 @@ async fn post_rotatekey(data: Json, headers: Headers, conn: DbConn, nt: let Some(saved_cipher) = cipher_data.id.as_ref().and_then(|id| existing_ciphers.iter_mut().find(|c| &c.uuid == id)) else { - err!("Cipher doesn't exist") + err!(crate::i18n::accounts_cipher_not_found(&headers.locale)) }; // Prevent triggering cipher updates via WebSockets by settings UpdateType::None @@ -1108,14 +1117,14 @@ struct EmailTokenData { #[post("/accounts/email-token", data = "")] async fn post_email_token(data: Json, headers: Headers, conn: DbConn) -> EmptyResult { if !CONFIG.email_change_allowed() { - err!("Email change is not allowed."); + err!(crate::i18n::accounts_email_change_not_allowed(&headers.locale)); } let data: EmailTokenData = data.into_inner(); let mut user = headers.user; if !user.check_valid_password(&data.master_password_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } if let Some(existing_user) = User::find_by_mail(&data.new_email, &conn).await { @@ -1124,27 +1133,33 @@ async fn post_email_token(data: Json, headers: Headers, conn: Db if existing_user.password_hash.is_empty() { // inform an invited user about how to delete their temporary account if the // request was done intentionally and they want to update their mail address - if let Err(e) = mail::send_change_email_invited(&data.new_email, &user.email).await { + if let Err(e) = + mail::send_change_email_invited_for_locale(&data.new_email, &user.email, Some(&headers.locale)) + .await + { error!("Error sending change-email-invited email: {e:#?}"); } } else { // inform existing user about the failed attempt to change their mail address - if let Err(e) = mail::send_change_email_existing(&data.new_email, &user.email).await { + if let Err(e) = + mail::send_change_email_existing_for_locale(&data.new_email, &user.email, Some(&headers.locale)) + .await + { error!("Error sending change-email-existing email: {e:#?}"); } } } - err!("Email already in use"); + err!(crate::i18n::accounts_email_already_in_use(&headers.locale)); } if !CONFIG.is_email_domain_allowed(&data.new_email) { - err!("Email domain not allowed"); + err!(crate::i18n::accounts_email_domain_not_allowed(&headers.locale)); } let token = crypto::generate_email_token(6); if CONFIG.mail_enabled() { - if let Err(e) = mail::send_change_email(&data.new_email, &token).await { + if let Err(e) = mail::send_change_email_for_locale(&data.new_email, &token, Some(&headers.locale)).await { error!("Error sending change-email email: {e:#?}"); } } else { @@ -1170,36 +1185,36 @@ struct ChangeEmailData { #[post("/accounts/email", data = "")] async fn post_email(data: Json, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { if !CONFIG.email_change_allowed() { - err!("Email change is not allowed."); + err!(crate::i18n::accounts_email_change_not_allowed(&headers.locale)); } let data: ChangeEmailData = data.into_inner(); let mut user = headers.user; if !user.check_valid_password(&data.master_password_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } if User::find_by_mail(&data.new_email, &conn).await.is_some() { - err!("Email already in use"); + err!(crate::i18n::accounts_email_already_in_use(&headers.locale)); } if let Some(ref val) = user.email_new { if val != &data.new_email { - err!("Email change mismatch"); + err!(crate::i18n::accounts_email_change_mismatch(&headers.locale)); } } else { - err!("No email change pending") + err!(crate::i18n::accounts_no_email_change_pending(&headers.locale)) } if CONFIG.mail_enabled() { // Only check the token if we sent out an email... if let Some(ref val) = user.email_new_token { if *val != data.token.into_string() { - err!("Token mismatch"); + err!(crate::i18n::accounts_token_mismatch(&headers.locale)); } } else { - err!("No email change pending") + err!(crate::i18n::accounts_no_email_change_pending(&headers.locale)) } user.verified_at = Some(Utc::now().naive_utc()); } else { @@ -1224,10 +1239,10 @@ async fn post_verify_email(headers: Headers) -> EmptyResult { let user = headers.user; if !CONFIG.mail_enabled() { - err!("Cannot verify email address"); + err!(crate::i18n::accounts_cannot_verify_email(&headers.locale)); } - if let Err(e) = mail::send_verify_email(&user.email, &user.uuid).await { + if let Err(e) = mail::send_verify_email_for_locale(&user.email, &user.uuid, Some(&headers.locale)).await { error!("Error sending verify_email email: {e:#?}"); } @@ -1246,14 +1261,14 @@ async fn post_verify_email_token(data: Json, conn: DbConn) let data: VerifyEmailTokenData = data.into_inner(); let Some(mut user) = User::find_by_uuid(&data.user_id, &conn).await else { - err!("User doesn't exist") + err!(crate::i18n::accounts_user_not_found(&CONFIG.default_locale())) }; let Ok(claims) = decode_verify_email(&data.token) else { - err!("Invalid claim") + err!(crate::i18n::accounts_invalid_claim(&CONFIG.default_locale())) }; if claims.sub != *user.uuid { - err!("Invalid claim"); + err!(crate::i18n::accounts_invalid_claim(&CONFIG.default_locale())); } user.verified_at = Some(Utc::now().naive_utc()); user.last_verifying_at = None; @@ -1279,7 +1294,7 @@ async fn post_delete_recover(data: Json, ip: ClientIp, conn: if CONFIG.mail_enabled() { if let Some(user) = User::find_by_mail(&data.email, &conn).await - && let Err(e) = mail::send_delete_account(&user.email, &user.uuid).await + && let Err(e) = mail::send_delete_account_for_locale(&user.email, &user.uuid, user.locale.as_deref()).await { error!("Error sending delete account email: {e:#?}"); } @@ -1289,7 +1304,7 @@ async fn post_delete_recover(data: Json, ip: ClientIp, conn: // to delete accounts without at least logging in... And if the user // cannot remember their password then they will need to contact // the administrator to delete it... - err!("Please contact the administrator to delete your account"); + err!(crate::i18n::accounts_contact_admin_to_delete(&CONFIG.default_locale())); } } @@ -1305,15 +1320,15 @@ async fn post_delete_recover_token(data: Json, conn: DbC let data: DeleteRecoverTokenData = data.into_inner(); let Ok(claims) = decode_delete(&data.token) else { - err!("Invalid claim") + err!(crate::i18n::accounts_invalid_claim(&CONFIG.default_locale())) }; let Some(user) = User::find_by_uuid(&data.user_id, &conn).await else { - err!("User doesn't exist") + err!(crate::i18n::accounts_user_not_found(&CONFIG.default_locale())) }; if claims.sub != *user.uuid { - err!("Invalid claim"); + err!(crate::i18n::accounts_invalid_claim(&CONFIG.default_locale())); } // The devices are deleted together with the user, so check for push devices beforehand @@ -1375,7 +1390,7 @@ async fn password_hint(data: Json, ip: ClientIp, conn: DbConn) crate::ratelimit::check_limit_unauthenticated(&ip.ip)?; if !CONFIG.password_hints_allowed() || (!CONFIG.mail_enabled() && !CONFIG.show_password_hint()) { - err!("This server is not configured to provide password hints."); + err!(crate::i18n::accounts_password_hint_not_configured(&CONFIG.default_locale())); } let data: PasswordHintData = data.into_inner(); @@ -1400,10 +1415,11 @@ async fn password_hint(data: Json, ip: ClientIp, conn: DbConn) Some(user) => { let hint: Option = user.password_hint; if CONFIG.mail_enabled() { - mail::send_password_hint(email, hint).await?; + mail::send_password_hint_for_locale(email, hint, user.locale.as_deref()).await?; Ok(()) } else if let Some(hint) = hint { - err!(format!("Your password hint is: {hint}")); + let message = crate::i18n::accounts_password_hint_is(&CONFIG.default_locale()).replacen("{}", &hint, 1); + err!(message); } else { err!(NO_HINT); } @@ -1487,7 +1503,7 @@ async fn verify_password(data: Json, headers: Headers let mut user = headers.user; if !user.check_valid_password(&data.master_password_hash) { - err!("Invalid password") + err!(crate::i18n::auth_invalid_password(&headers.locale)) } kdf_upgrade(&mut user, &data.master_password_hash, &conn).await?; @@ -1590,7 +1606,7 @@ async fn get_all_devices(headers: Headers, conn: DbConn) -> JsonResult { #[get("/devices/identifier/")] async fn get_device(device_id: DeviceId, headers: Headers, conn: DbConn) -> JsonResult { let Some(device) = Device::find_by_uuid_and_user(&device_id, &headers.user.uuid, &conn).await else { - err!("No device found"); + err!(crate::i18n::accounts_no_device_found(&headers.locale)); }; Ok(Json(device.to_json())) } @@ -1612,7 +1628,10 @@ async fn put_device_token(device_id: DeviceId, data: Json, headers: H let token = data.push_token; let Some(mut device) = Device::find_by_uuid_and_user(&headers.device.uuid, &headers.user.uuid, &conn).await else { - err!(format!("Error: device {device_id} should be present before a token can be assigned")) + err!( + crate::i18n::accounts_device_should_be_present_before_token_assigned(&headers.locale), + device_id.to_string() + ) }; // Check if the new token is the same as the registered token @@ -1625,7 +1644,7 @@ async fn put_device_token(device_id: DeviceId, data: Json, headers: H device.push_token = Some(token); if let Err(e) = device.save(true, &conn).await { - err!(format!("An error occurred while trying to save the device push token: {e}")); + err!(crate::i18n::accounts_error_saving_device_push_token(&headers.locale), e.to_string()); } register_push_device(&mut device, &conn).await?; @@ -1694,13 +1713,19 @@ async fn post_auth_request( let data = data.into_inner(); let Some(user) = User::find_by_mail(&data.email, &conn).await else { - err!("AuthRequest doesn't exist", "User not found") + err!( + crate::i18n::accounts_auth_request_not_found(&client_headers.locale), + crate::i18n::org_user_not_found(&client_headers.locale) + ) }; // Validate device uuid and type let device = match Device::find_by_uuid_and_user(&data.device_identifier, &user.uuid, &conn).await { Some(device) if device.atype == client_headers.device_type => device, - _ => err!("AuthRequest doesn't exist", "Device verification failed"), + _ => err!( + crate::i18n::accounts_auth_request_not_found(&client_headers.locale), + crate::i18n::accounts_device_verification_failed(&client_headers.locale) + ), }; let auth_request = AuthRequest::new( @@ -1743,7 +1768,10 @@ async fn post_auth_request( async fn get_auth_request(auth_request_id: AuthRequestId, headers: Headers, conn: DbConn) -> JsonResult { let Some(auth_request) = AuthRequest::find_by_uuid_and_user(&auth_request_id, &headers.user.uuid, &conn).await else { - err!("AuthRequest doesn't exist", "Record not found or user uuid does not match") + err!( + crate::i18n::accounts_auth_request_not_found(&headers.locale), + crate::i18n::accounts_auth_request_not_found_or_mismatch(&headers.locale) + ) }; let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); @@ -1784,15 +1812,21 @@ async fn put_auth_request( let data = data.into_inner(); let Some(mut auth_request) = AuthRequest::find_by_uuid_and_user(&auth_request_id, &headers.user.uuid, &conn).await else { - err!("AuthRequest doesn't exist", "Record not found or user uuid does not match") + err!( + crate::i18n::accounts_auth_request_not_found(&headers.locale), + crate::i18n::accounts_auth_request_not_found_or_mismatch(&headers.locale) + ) }; if headers.device.uuid != data.device_identifier { - err!("AuthRequest doesn't exist", "Device verification failed") + err!( + crate::i18n::accounts_auth_request_not_found(&headers.locale), + crate::i18n::accounts_device_verification_failed(&headers.locale) + ) } if auth_request.approved.is_some() { - err!("An authentication request with the same device already exists") + err!(crate::i18n::accounts_auth_request_duplicate_device(&headers.locale)) } let response_date = Utc::now().naive_utc(); @@ -1855,14 +1889,20 @@ async fn get_auth_request_response( crate::ratelimit::check_limit_unauthenticated(&client_headers.ip.ip)?; let Some(auth_request) = AuthRequest::find_by_uuid(&auth_request_id, &conn).await else { - err!("AuthRequest doesn't exist", "User not found") + err!( + crate::i18n::accounts_auth_request_not_found(&client_headers.locale), + crate::i18n::org_user_not_found(&client_headers.locale) + ) }; if auth_request.device_type != client_headers.device_type || auth_request.request_ip != client_headers.ip.ip.to_string() || !auth_request.check_access_code(code) { - err!("AuthRequest doesn't exist", "Invalid device, IP or code") + err!( + crate::i18n::accounts_auth_request_not_found(&client_headers.locale), + crate::i18n::accounts_auth_request_invalid_device_ip_or_code(&client_headers.locale) + ) } let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index 92499b9f..0d4b9fb2 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -234,11 +234,11 @@ async fn get_ciphers(headers: Headers, conn: DbConn) -> JsonResult { #[get("/ciphers/")] async fn get_cipher(cipher_id: CipherId, headers: Headers, conn: DbConn) -> JsonResult { let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher is not owned by user") + err!(crate::i18n::cipher_not_owned_by_user(&headers.locale)) } Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?)) @@ -420,7 +420,7 @@ async fn enforce_personal_ownership_policy(data: Option<&CipherData>, headers: & let user_id = &headers.user.uuid; let policy_type = OrgPolicyType::PersonalOwnership; if OrgPolicy::is_applicable_to_user(user_id, policy_type, None, conn).await { - err!("Due to an Enterprise Policy, you are restricted from saving items to your personal vault.") + err!(crate::i18n::cipher_personal_vault_restricted(&headers.locale)) } } Ok(()) @@ -460,20 +460,25 @@ pub async fn update_cipher_from_data( // ISO 8601 format Err(err) => warn!("Error parsing LastKnownRevisionDate '{dt}': {err}"), Ok(dt) if cipher.updated_at.signed_duration_since(dt).num_seconds() > 1 => { - err!("The client copy of this cipher is out of date. Resync the client and try again.") + err!(crate::i18n::cipher_client_copy_outdated(&headers.locale)) } Ok(_) => (), } } if cipher.organization_uuid.is_some() && cipher.organization_uuid != data.organization_id { - err!("Organization mismatch. Please resync the client before updating the cipher") + err!(crate::i18n::cipher_organization_mismatch(&headers.locale)) } if let Some(note) = &data.notes { let max_note_size = CONFIG._max_note_size(); if note.len() > max_note_size { - err!(format!("The field Notes exceeds the maximum encrypted value length of {max_note_size} characters.")) + let message = crate::i18n::cipher_notes_exceeds_max_len(&headers.locale).replacen( + "{}", + &max_note_size.to_string(), + 1, + ); + err!(message) } } @@ -482,7 +487,7 @@ pub async fn update_cipher_from_data( if let Some(org_id) = data.organization_id { match Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &org_id, conn).await { - None => err!("You don't have permission to add item to organization"), + None => err!(crate::i18n::cipher_no_permission_add_item_to_org(&headers.locale)), Some(member) => { // A non-empty list of collections implies the caller already validated the user's write // access to them, so we can move the cipher into the organization on that basis. @@ -499,7 +504,7 @@ pub async fn update_cipher_from_data( // Removing the line below would fix that, but we have to check which effect this would have on the rest of the code. cipher.user_uuid = None; } else { - err!("You don't have permission to add cipher directly to organization") + err!(crate::i18n::cipher_no_permission_add_cipher_direct_to_org(&headers.locale)) } } } @@ -510,7 +515,7 @@ pub async fn update_cipher_from_data( if let Some(ref folder_id) = data.folder_id && Folder::find_by_uuid_and_user(folder_id, &headers.user.uuid, conn).await.is_none() { - err!("Invalid folder", "Folder does not exist or belongs to another user"); + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)); } // Modify attachments name and keys when rotating @@ -548,7 +553,7 @@ pub async fn update_cipher_from_data( 6 => data.bank_account, 7 => data.drivers_license, 8 => data.passport, - _ => err!("Invalid type"), + _ => err!(crate::i18n::cipher_invalid_type(&headers.locale)), }; let type_data = if let Some(mut data) = type_data_opt { @@ -562,7 +567,7 @@ pub async fn update_cipher_from_data( } data } else { - err!("Data missing") + err!(crate::i18n::cipher_data_missing(&headers.locale)) }; cipher.key = data.key; @@ -731,7 +736,7 @@ async fn put_cipher( let data: CipherData = data.into_inner(); let Some(mut cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; // TODO: Check if only the folder ID or favorite status is being changed. @@ -740,12 +745,12 @@ async fn put_cipher( // Interestingly, upstream Bitwarden doesn't properly handle this either. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher is not write accessible") + err!(crate::i18n::cipher_not_write_accessible(&headers.locale)) } // Moving a cipher into an organization is only possible through the share endpoints if cipher.organization_uuid != data.organization_id { - err!("Organization mismatch. Please resync the client before updating the cipher") + err!(crate::i18n::cipher_organization_mismatch(&headers.locale)) } update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherUpdate).await?; @@ -774,17 +779,17 @@ async fn put_cipher_partial( let data: PartialCipherData = data.into_inner(); let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher does not exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher does not exist", "Cipher is not accessible for the current user") + err!(crate::i18n::cipher_not_owned_by_user(&headers.locale)) } if let Some(ref folder_id) = data.folder_id && Folder::find_by_uuid_and_user(folder_id, &headers.user.uuid, &conn).await.is_none() { - err!("Invalid folder", "Folder does not exist or belongs to another user"); + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)); } // Move cipher @@ -851,15 +856,15 @@ async fn post_collections_update( let data: CollectionsAdminData = data.into_inner(); let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_in_editable_collection_by_user(&headers.user.uuid, &conn).await { - err!("Collection cannot be changed") + err!(crate::i18n::cipher_collection_cannot_be_changed(&headers.locale)) } let Some(ref org_uuid) = cipher.organization_uuid else { - err!("Cipher is not owned by an organization") + err!(crate::i18n::cipher_not_owned_by_org(&headers.locale)) }; let posted_collections = HashSet::::from_iter(data.collection_ids); @@ -868,7 +873,7 @@ async fn post_collections_update( for collection in posted_collections.symmetric_difference(¤t_collections) { match Collection::find_by_uuid_and_org(collection, org_uuid, &conn).await { - None => err!("Invalid collection ID provided"), + None => err!(crate::i18n::cipher_invalid_collection_id(&headers.locale)), Some(collection) => { if collection.is_writable_by_user(&headers.user.uuid, &conn).await { if posted_collections.contains(&collection.uuid) { @@ -879,7 +884,7 @@ async fn post_collections_update( CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?; } } else { - err!("No rights to modify the collection") + err!(crate::i18n::cipher_no_rights_modify_collection(&headers.locale)) } } } @@ -931,15 +936,15 @@ async fn post_collections_admin( let data: CollectionsAdminData = data.into_inner(); let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_in_editable_collection_by_user(&headers.user.uuid, &conn).await { - err!("Collection cannot be changed") + err!(crate::i18n::cipher_collection_cannot_be_changed(&headers.locale)) } let Some(ref org_uuid) = cipher.organization_uuid else { - err!("Cipher is not owned by an organization") + err!(crate::i18n::cipher_not_owned_by_org(&headers.locale)) }; let posted_collections = HashSet::::from_iter(data.collection_ids); @@ -948,7 +953,7 @@ async fn post_collections_admin( for collection in posted_collections.symmetric_difference(¤t_collections) { match Collection::find_by_uuid_and_org(collection, org_uuid, &conn).await { - None => err!("Invalid collection ID provided"), + None => err!(crate::i18n::cipher_invalid_collection_id(&headers.locale)), Some(collection) => { if collection.is_writable_by_user(&headers.user.uuid, &conn).await { if posted_collections.contains(&collection.uuid) { @@ -959,7 +964,7 @@ async fn post_collections_admin( CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?; } } else { - err!("No rights to modify the collection") + err!(crate::i18n::cipher_no_rights_modify_collection(&headers.locale)) } } } @@ -1020,11 +1025,11 @@ async fn put_cipher_share( let data: ShareCipherData = data.into_inner(); if data.cipher.organization_id.is_none() { - err!("Cipher OrganizationId is required.") + err!(crate::i18n::cipher_organization_id_required(&headers.locale)) } if data.collection_ids.is_empty() { - err!("You must select at least one collection.") + err!(crate::i18n::cipher_at_least_one_collection_required(&headers.locale)) } share_cipher_by_uuid(&cipher_id, data, &headers, &conn, &nt, None).await @@ -1086,19 +1091,19 @@ async fn put_cipher_share_selected( let data: ShareSelectedCipherData = data.into_inner(); if data.ciphers.is_empty() { - err!("You must select at least one cipher.") + err!(crate::i18n::cipher_at_least_one_cipher_required(&headers.locale)) } if data.collection_ids.is_empty() { - err!("You must select at least one collection.") + err!(crate::i18n::cipher_at_least_one_collection_required(&headers.locale)) } for cipher in &data.ciphers { if cipher.id.is_none() { - err!("Request missing ids field") + err!(crate::i18n::cipher_request_missing_ids(&headers.locale)) } if cipher.organization_id.is_none() { - err!("Cipher OrganizationId is required.") + err!(crate::i18n::cipher_organization_id_required(&headers.locale)) } } @@ -1122,7 +1127,7 @@ async fn put_cipher_share_selected( responses.push(cipher_mini_from_json(response.into_inner())); } } else { - err!("Request missing ids field") + err!(crate::i18n::cipher_request_missing_ids(&headers.locale)) } } @@ -1148,17 +1153,17 @@ async fn share_cipher_by_uuid( if cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await { cipher } else { - err!("Cipher is not write accessible") + err!(crate::i18n::cipher_not_write_accessible(&headers.locale)) } } else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; // `update_cipher_from_data()` rejects this too, but only after the collections below were // already linked. There are no transactions, so that would leave the cipher linked to a // collection of another organization. if cipher.organization_uuid.is_some() && cipher.organization_uuid != data.cipher.organization_id { - err!("Organization mismatch. Please resync the client before updating the cipher") + err!(crate::i18n::cipher_organization_mismatch(&headers.locale)) } let mut shared_to_collections = vec![]; @@ -1166,13 +1171,13 @@ async fn share_cipher_by_uuid( if let Some(organization_id) = &data.cipher.organization_id { for col_id in &data.collection_ids { match Collection::find_by_uuid_and_org(col_id, organization_id, conn).await { - None => err!("Invalid collection ID provided"), + None => err!(crate::i18n::cipher_invalid_collection_id(&headers.locale)), Some(collection) => { if collection.is_writable_by_user(&headers.user.uuid, conn).await { CollectionCipher::save(&cipher.uuid, &collection.uuid, conn).await?; shared_to_collections.push(collection.uuid); } else { - err!("No rights to modify the collection") + err!(crate::i18n::cipher_no_rights_modify_collection(&headers.locale)) } } } @@ -1208,17 +1213,17 @@ async fn get_attachment( conn: DbConn, ) -> JsonResult { let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher is not accessible") + err!(crate::i18n::cipher_not_accessible(&headers.locale)) } match Attachment::find_by_id(&attachment_id, &conn).await { Some(attachment) if cipher_id == attachment.cipher_uuid => Ok(Json(attachment.to_json(&headers.host).await?)), - Some(_) => err!("Attachment doesn't belong to cipher"), - None => err!("Attachment doesn't exist"), + Some(_) => err!(crate::i18n::cipher_attachment_not_belong_to_cipher(&headers.locale)), + None => err!(crate::i18n::cipher_attachment_not_found(&headers.locale)), } } @@ -1250,21 +1255,21 @@ async fn attachment_size_limit(cipher: &Cipher, size_adjust: i64, conn: &DbConn) }; (limit_kb, Attachment::size_by_org(org_id, conn).await) } else { - err!("Cipher is neither owned by a user nor an organization"); + err!(crate::i18n::cipher_neither_user_nor_org_owned(&CONFIG.default_locale())); }; if limit_kb == 0 { - err!("Attachments are disabled") + err!(crate::i18n::cipher_attachments_disabled(&CONFIG.default_locale())) } let Some(left) = limit_kb.checked_mul(1024).and_then(|l| l.checked_sub(already_used)).and_then(|l| l.checked_add(size_adjust)) else { - err!("Attachment size overflow"); + err!(crate::i18n::cipher_attachment_size_overflow(&CONFIG.default_locale())); }; if left <= 0 { - err!("Attachment storage limit reached! Delete some attachments to free up space") + err!(crate::i18n::cipher_attachment_storage_limit_reached(&CONFIG.default_locale())) } Ok(Some(left)) @@ -1283,28 +1288,28 @@ async fn post_attachment_v2( nt: Notify<'_>, ) -> JsonResult { let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher is not write accessible") + err!(crate::i18n::cipher_not_write_accessible(&headers.locale)) } let data: AttachmentRequestData = data.into_inner(); let file_size = data.file_size.into_i64()?; if file_size < 0 { - err!("Attachment size can't be negative") + err!(crate::i18n::cipher_attachment_size_negative(&headers.locale)) } // Matches the "file" upload limit in main.rs, nothing larger can be uploaded if file_size > SIZE_525_MB { - err!("Max file size is 525 MB.") + err!(crate::i18n::cipher_max_file_size_525mb(&headers.locale)) } if let Some(size_limit) = attachment_size_limit(&cipher, 0, &conn).await? && file_size > size_limit { - err!("Attachment storage limit exceeded with this file"); + err!(crate::i18n::cipher_attachment_storage_limit_exceeded_file(&headers.locale)); } let attachment_id = crypto::generate_attachment_id(); @@ -1353,18 +1358,18 @@ async fn save_attachment( let data = data.into_inner(); let Some(size) = data.data.len().to_i64() else { - err!("Attachment data size overflow"); + err!(crate::i18n::cipher_attachment_data_size_overflow(&headers.locale)); }; if size < 0 { - err!("Attachment size can't be negative") + err!(crate::i18n::cipher_attachment_size_negative(&headers.locale)) } let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn).await { - err!("Cipher is not write accessible") + err!(crate::i18n::cipher_not_write_accessible(&headers.locale)) } // In the v2 API, the attachment record has already been created, @@ -1377,7 +1382,7 @@ async fn save_attachment( if let Some(size_limit) = attachment_size_limit(&cipher, size_adjust, &conn).await? && size > size_limit { - err!("Attachment storage limit exceeded with this file"); + err!(crate::i18n::cipher_attachment_storage_limit_exceeded_file(&headers.locale)); } let file_id = match &attachment { @@ -1393,10 +1398,10 @@ async fn save_attachment( // size, but it's not clear when or why this is needed. const LEEWAY: i64 = 1024 * 1024; // 1 MiB let Some(max_size) = attachment.file_size.checked_add(LEEWAY) else { - err!("Invalid attachment size max") + err!(crate::i18n::cipher_invalid_attachment_size_max(&headers.locale)) }; let Some(min_size) = attachment.file_size.checked_sub(LEEWAY) else { - err!("Invalid attachment size min") + err!(crate::i18n::cipher_invalid_attachment_size_min(&headers.locale)) }; if min_size <= size && size <= max_size { @@ -1408,7 +1413,10 @@ async fn save_attachment( } else { attachment.delete(&conn).await.ok(); - err!(format!("Attachment size mismatch (expected within [{min_size}, {max_size}], got {size})")); + err!( + crate::i18n::cipher_attachment_size_mismatch(&headers.locale), + format!("expected within [{min_size}, {max_size}], got {size}") + ); } } else { // Legacy API @@ -1419,10 +1427,10 @@ async fn save_attachment( let encrypted_filename = data.data.raw_name().map(|s| s.dangerous_unsafe_unsanitized_raw().to_string()); if encrypted_filename.is_none() { - err!("No filename provided") + err!(crate::i18n::cipher_no_filename_provided(&headers.locale)) } if data.key.is_none() { - err!("No attachment key provided") + err!(crate::i18n::cipher_no_attachment_key_provided(&headers.locale)) } let attachment = Attachment::new(file_id.clone(), cipher_id.clone(), encrypted_filename.unwrap(), size, data.key); @@ -1480,8 +1488,8 @@ async fn post_attachment_v2_data( ) -> EmptyResult { let attachment = match Attachment::find_by_id(&attachment_id, &conn).await { Some(attachment) if cipher_id == attachment.cipher_uuid => Some(attachment), - Some(_) => err!("Attachment doesn't belong to cipher"), - None => err!("Attachment doesn't exist"), + Some(_) => err!(crate::i18n::cipher_attachment_not_belong_to_cipher(&headers.locale)), + None => err!(crate::i18n::cipher_attachment_not_found(&headers.locale)), }; save_attachment(attachment, cipher_id, data, &headers, conn, nt).await?; @@ -1728,7 +1736,7 @@ async fn move_cipher_selected( if let Some(ref folder_id) = data.folder_id && Folder::find_by_uuid_and_user(folder_id, user_id, &conn).await.is_none() { - err!("Invalid folder", "Folder does not exist or belongs to another user"); + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)); } let cipher_count = data.ids.len(); @@ -1771,9 +1779,9 @@ async fn move_cipher_selected( } if cipher_count != accessible_ciphers_count { - err!(format!( - "Not all ciphers are moved! {accessible_ciphers_count} of the selected {cipher_count} were moved." - )) + let msg = + format!("Not all ciphers are moved! {accessible_ciphers_count} of the selected {cipher_count} were moved."); + err!(msg) } Ok(()) @@ -1807,8 +1815,9 @@ async fn purge_org_vault( conn: DbConn, nt: Notify<'_>, ) -> EmptyResult { + let locale = headers.user.locale.clone().unwrap_or_else(|| CONFIG.default_locale()); if organization.org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(&locale), "Organization id's do not match"); } let data: PasswordOrOtpData = data.into_inner(); @@ -1834,7 +1843,7 @@ async fn purge_org_vault( Ok(()) } - _ => err!("You don't have permission to purge the organization vault"), + _ => err!(crate::i18n::cipher_no_permission_purge_org_vault(&locale)), } } @@ -1910,11 +1919,11 @@ async fn delete_cipher_by_uuid( nt: &Notify<'_>, ) -> EmptyResult { let Some(mut cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await { - err!("Cipher can't be deleted by user") + err!(crate::i18n::cipher_cannot_be_deleted_by_user(&headers.locale)) } if *delete_options == CipherDeleteOptions::SoftSingle || *delete_options == CipherDeleteOptions::SoftMulti { @@ -1997,11 +2006,11 @@ async fn restore_cipher_by_uuid( nt: &Notify<'_>, ) -> JsonResult { let Some(mut cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await { - err!("Cipher can't be restored by user") + err!(crate::i18n::cipher_cannot_be_restored_by_user(&headers.locale)) } cipher.deleted_at = None; @@ -2069,19 +2078,19 @@ async fn delete_cipher_attachment_by_id( nt: &Notify<'_>, ) -> JsonResult { let Some(attachment) = Attachment::find_by_id(attachment_id, conn).await else { - err!("Attachment doesn't exist") + err!(crate::i18n::cipher_attachment_not_found(&headers.locale)) }; if &attachment.cipher_uuid != cipher_id { - err!("Attachment from other cipher") + err!(crate::i18n::cipher_attachment_from_other_cipher(&headers.locale)) } let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await { - err!("Cipher cannot be deleted by user") + err!(crate::i18n::cipher_cannot_delete_by_user(&headers.locale)) } // Delete attachment @@ -2120,11 +2129,11 @@ async fn archive_cipher( nt: &Notify<'_>, ) -> JsonResult { let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_accessible_to_user(&headers.user.uuid, conn).await { - err!("Cipher is not accessible for the current user") + err!(crate::i18n::cipher_not_accessible_for_current_user(&headers.locale)) } cipher.set_archived_at(Utc::now().naive_utc(), &headers.user.uuid, conn).await?; @@ -2152,11 +2161,11 @@ async fn unarchive_cipher( nt: &Notify<'_>, ) -> JsonResult { let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { - err!("Cipher doesn't exist") + err!(crate::i18n::cipher_not_found(&headers.locale)) }; if !cipher.is_accessible_to_user(&headers.user.uuid, conn).await { - err!("Cipher is not accessible for the current user") + err!(crate::i18n::cipher_not_accessible_for_current_user(&headers.locale)) } cipher.unarchive(&headers.user.uuid, conn).await?; diff --git a/src/api/core/emergency_access.rs b/src/api/core/emergency_access.rs index 773697e5..5e2efc9a 100644 --- a/src/api/core/emergency_access.rs +++ b/src/api/core/emergency_access.rs @@ -99,7 +99,7 @@ async fn get_emergency_access(emer_id: EmergencyAccessId, headers: Headers, conn emergency_access.to_json_grantee_details(&conn).await.expect("Grantee user should exist but does not!"), )) } else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } } @@ -137,17 +137,17 @@ async fn post_emergency_access( let data: EmergencyAccessUpdateData = data.into_inner(); let Some(new_type) = EmergencyAccessType::from_str(&data.r#type.into_string()) else { - err!("Invalid emergency access type.") + err!(crate::i18n::emergency_access_invalid_type(&headers.locale)) }; if !(EMERGENCY_ACCESS_TIMEOUT_RANGE).contains(&data.wait_time_days) { - err!("Emergency access wait time is out-of-bounds!") + err!(crate::i18n::emergency_access_wait_time_out_of_bounds(&headers.locale)) } let Some(mut emergency_access) = EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; emergency_access.atype = new_type as i32; @@ -180,7 +180,7 @@ async fn delete_emergency_access(emer_id: EmergencyAccessId, headers: Headers, c info!("Grantee deleted emergency access {emer_id}"); grantee_emer } - _ => err!("Emergency access not valid."), + _ => err!(crate::i18n::emergency_access_not_valid(&headers.locale)), }; emergency_access.delete(&conn).await?; @@ -213,28 +213,31 @@ async fn send_invite(data: Json, headers: Headers, co let wait_time_days = data.wait_time_days; if !(EMERGENCY_ACCESS_TIMEOUT_RANGE).contains(&wait_time_days) { - err!("Emergency access wait time is out-of-bounds!") + err!(crate::i18n::emergency_access_wait_time_out_of_bounds(&headers.locale)) } let Some(new_type) = EmergencyAccessType::from_str(&data.r#type.into_string()) else { - err!("Invalid emergency access type.") + err!(crate::i18n::emergency_access_invalid_type(&headers.locale)) }; let grantor_user = headers.user; // avoid setting yourself as emergency contact if email == grantor_user.email { - err!("You can not set yourself as an emergency contact.") + err!(crate::i18n::emergency_access_cannot_set_self(&headers.locale)) } let (grantee_user, new_user) = match User::find_by_mail(&email, &conn).await { None => { if !CONFIG.invitations_allowed() { - err!(format!("Grantee user does not exist: {}", email.escape_debug())) + err!( + crate::i18n::emergency_access_grantee_user_not_exists(&headers.locale), + email.escape_debug().to_string() + ) } if !CONFIG.is_email_domain_allowed(&email) { - err!("Email domain not eligible for invitations") + err!(crate::i18n::emergency_access_email_domain_not_eligible(&headers.locale)) } if !CONFIG.mail_enabled() { @@ -259,7 +262,7 @@ async fn send_invite(data: Json, headers: Headers, co .await .is_some() { - err!(format!("Grantee user already invited: {}", &grantee_user.email)) + err!(crate::i18n::emergency_access_grantee_user_already_invited(&headers.locale), grantee_user.email.clone()) } let new_type = new_type as i32; @@ -269,12 +272,13 @@ async fn send_invite(data: Json, headers: Headers, co new_emergency_access.save(&conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_invite( + mail::send_emergency_access_invite_for_locale( &new_emergency_access.email.expect("Grantee email does not exists"), grantee_user.uuid, new_emergency_access.uuid, &grantor_user.name, &grantor_user.email, + grantee_user.locale.as_deref(), ) .await?; } else if !new_user { @@ -292,30 +296,31 @@ async fn resend_invite(emer_id: EmergencyAccessId, headers: Headers, conn: DbCon let Some(mut emergency_access) = EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if emergency_access.status != EmergencyAccessStatus::Invited as i32 { - err!("The grantee user is already accepted or confirmed for emergency access"); + err!(crate::i18n::emergency_access_grantee_already_accepted_or_confirmed(&headers.locale)); } let Some(email) = emergency_access.email.clone() else { - err!("Email not valid.") + err!(crate::i18n::emergency_access_email_not_valid(&headers.locale)) }; let Some(grantee_user) = User::find_by_mail(&email, &conn).await else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) }; let grantor_user = headers.user; if CONFIG.mail_enabled() { - mail::send_emergency_access_invite( + mail::send_emergency_access_invite_for_locale( &email, grantor_user.uuid, emergency_access.uuid, &grantor_user.name, &grantor_user.email, + grantee_user.locale.as_deref(), ) .await?; } else if !grantee_user.password_hash.is_empty() { @@ -351,14 +356,14 @@ async fn accept_invite( // This can happen if the user who received the invite used a different email to signup. // Since we do not know if this is intended, we error out here and do nothing with the invite. if claims.email != headers.user.email { - err!("Claim email does not match current users email") + err!(crate::i18n::emergency_access_claim_email_mismatch(&headers.locale)) } let grantee_user = if let Some(user) = User::find_by_mail(&claims.email, &conn).await { Invitation::take(&claims.email, &conn).await; user } else { - err!("Invited user not found") + err!(crate::i18n::emergency_access_invited_user_not_found(&headers.locale)) }; // We need to search for the uuid in combination with the email, since we do not yet store the uuid of the grantee in the database. @@ -366,12 +371,12 @@ async fn accept_invite( let Some(mut emergency_access) = EmergencyAccess::find_by_uuid_and_grantee_email(&emer_id, &headers.user.email, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; // get grantor user to send Accepted email let Some(grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; if emer_id == claims.emer_id @@ -381,12 +386,17 @@ async fn accept_invite( emergency_access.accept_invite(&grantee_user.uuid, &grantee_user.email, &conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_invite_accepted(&grantor_user.email, &grantee_user.email).await?; + mail::send_emergency_access_invite_accepted_for_locale( + &grantor_user.email, + &grantee_user.email, + grantor_user.locale.as_deref(), + ) + .await?; } Ok(()) } else { - err!("Emergency access invitation error.") + err!(crate::i18n::emergency_access_invitation_error(&headers.locale)) } } @@ -412,22 +422,22 @@ async fn confirm_emergency_access( let Some(mut emergency_access) = EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &confirming_user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if emergency_access.status != EmergencyAccessStatus::Accepted as i32 || emergency_access.grantor_uuid != confirming_user.uuid { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } let Some(grantor_user) = User::find_by_uuid(&confirming_user.uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() { let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) }; emergency_access.status = EmergencyAccessStatus::Confirmed as i32; @@ -437,11 +447,16 @@ async fn confirm_emergency_access( emergency_access.save(&conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_invite_confirmed(&grantee_user.email, &grantor_user.name).await?; + mail::send_emergency_access_invite_confirmed_for_locale( + &grantee_user.email, + &grantor_user.name, + grantee_user.locale.as_deref(), + ) + .await?; } Ok(Json(emergency_access.to_json())) } else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) } } @@ -458,27 +473,27 @@ async fn initiate_emergency_access(emer_id: EmergencyAccessId, headers: Headers, EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &initiating_user.uuid, &conn).await else { err!( - "Emergency access not valid.", + crate::i18n::emergency_access_not_valid(&headers.locale), format!("Emergency access '{emer_id}', not found for user '{}'.", initiating_user.email) ) }; if emergency_access.status != EmergencyAccessStatus::Confirmed as i32 { err!( - "Emergency access not valid.", + crate::i18n::emergency_access_not_valid(&headers.locale), format!("Emergency access '{emer_id}', not confirmed for user '{}'.", initiating_user.email) ) } if !EMERGENCY_ACCESS_TIMEOUT_RANGE.contains(&emergency_access.wait_time_days) { err!( - "Emergency access not valid.", + crate::i18n::emergency_access_not_valid(&headers.locale), format!("Emergency access '{emer_id}' timeout range '{}' is invalid", emergency_access.wait_time_days) ) } let Some(grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; let now = Utc::now().naive_utc(); @@ -489,11 +504,12 @@ async fn initiate_emergency_access(emer_id: EmergencyAccessId, headers: Headers, emergency_access.save(&conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_recovery_initiated( + mail::send_emergency_access_recovery_initiated_for_locale( &grantor_user.email, &initiating_user.name, emergency_access.get_type_as_str(), &emergency_access.wait_time_days, + grantor_user.locale.as_deref(), ) .await?; } @@ -508,36 +524,41 @@ async fn approve_emergency_access(emer_id: EmergencyAccessId, headers: Headers, EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await else { err!( - "Emergency access not valid.", + crate::i18n::emergency_access_not_valid(&headers.locale), format!("Emergency access '{emer_id}', not found for user '{}'.", headers.user.email) ) }; if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32 { err!( - "Emergency access not valid.", + crate::i18n::emergency_access_not_valid(&headers.locale), format!("Emergency access '{emer_id}', not initiated for user '{}'.", headers.user.email) ) } let Some(grantor_user) = User::find_by_uuid(&headers.user.uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() { let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) }; emergency_access.status = EmergencyAccessStatus::RecoveryApproved as i32; emergency_access.save(&conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_recovery_approved(&grantee_user.email, &grantor_user.name).await?; + mail::send_emergency_access_recovery_approved_for_locale( + &grantee_user.email, + &grantor_user.name, + grantee_user.locale.as_deref(), + ) + .await?; } Ok(Json(emergency_access.to_json())) } else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) } } @@ -548,29 +569,34 @@ async fn reject_emergency_access(emer_id: EmergencyAccessId, headers: Headers, c let Some(mut emergency_access) = EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32 && emergency_access.status != EmergencyAccessStatus::RecoveryApproved as i32 { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() { let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) }; emergency_access.status = EmergencyAccessStatus::Confirmed as i32; emergency_access.save(&conn).await?; if CONFIG.mail_enabled() { - mail::send_emergency_access_recovery_rejected(&grantee_user.email, &headers.user.name).await?; + mail::send_emergency_access_recovery_rejected_for_locale( + &grantee_user.email, + &headers.user.name, + grantee_user.locale.as_deref(), + ) + .await?; } Ok(Json(emergency_access.to_json())) } else { - err!("Grantee user not found.") + err!(crate::i18n::emergency_access_grantee_not_found(&headers.locale)) } } @@ -585,11 +611,11 @@ async fn view_emergency_access(emer_id: EmergencyAccessId, headers: Headers, con let Some(emergency_access) = EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &headers.user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if !is_valid_request(&emergency_access, &headers.user.uuid, EmergencyAccessType::View) { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } let ciphers = Cipher::find_owned_by_user(&emergency_access.grantor_uuid, &conn).await; @@ -624,15 +650,15 @@ async fn takeover_emergency_access(emer_id: EmergencyAccessId, headers: Headers, let Some(emergency_access) = EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if !is_valid_request(&emergency_access, &requesting_user.uuid, EmergencyAccessType::Takeover) { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } let Some(grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; let result = json!({ @@ -675,15 +701,15 @@ async fn password_emergency_access( let Some(emergency_access) = EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if !is_valid_request(&emergency_access, &requesting_user.uuid, EmergencyAccessType::Takeover) { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } let Some(mut grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; let (new_master_password_hash, new_key) = @@ -691,14 +717,14 @@ async fn password_emergency_access( authentication_data.check(&grantor_user, &unlock_data)?; if !authentication_data.kdf.matches_user(&grantor_user) { - err!("KDF settings do not match the grantor account") + err!(crate::i18n::emergency_access_kdf_mismatch_grantor(&headers.locale)) } (authentication_data.master_password_authentication_hash, unlock_data.master_key_wrapped_user_key) } else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) { (new_master_password_hash, new_key) } else { - err!("Invalid request!") + err!(crate::i18n::emergency_access_invalid_request(&headers.locale)) }; // change grantor_user password @@ -725,15 +751,15 @@ async fn policies_emergency_access(emer_id: EmergencyAccessId, headers: Headers, let Some(emergency_access) = EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await else { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) }; if !is_valid_request(&emergency_access, &requesting_user.uuid, EmergencyAccessType::Takeover) { - err!("Emergency access not valid.") + err!(crate::i18n::emergency_access_not_valid(&headers.locale)) } let Some(grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { - err!("Grantor user not found.") + err!(crate::i18n::emergency_access_grantor_not_found(&headers.locale)) }; let policies = OrgPolicy::find_confirmed_by_user(&grantor_user.uuid, &conn); @@ -759,7 +785,7 @@ fn is_valid_request( fn check_emergency_access_enabled() -> EmptyResult { if !CONFIG.emergency_access_allowed() { - err!("Emergency access is not enabled.") + err!(crate::i18n::emergency_access_not_enabled(&CONFIG.default_locale())) } Ok(()) } @@ -820,17 +846,23 @@ pub async fn emergency_request_timeout_job(pool: DbPool) { } if CONFIG.mail_enabled() { - if let Err(e) = mail::send_emergency_access_recovery_timed_out( + if let Err(e) = mail::send_emergency_access_recovery_timed_out_for_locale( &grantor_user.email, &grantee_user.name, emer.get_type_as_str(), + grantor_user.locale.as_deref(), ) .await { error!("Failed to send emergency access recovery time-out email for '{}': {e}", emer.uuid); } - if let Err(e) = mail::send_emergency_access_recovery_approved(&grantee_user.email, &grantor_user.name).await + if let Err(e) = mail::send_emergency_access_recovery_approved_for_locale( + &grantee_user.email, + &grantor_user.name, + grantee_user.locale.as_deref(), + ) + .await { error!("Failed to send emergency access recovery approved email for '{}': {e}", emer.uuid); } @@ -914,11 +946,12 @@ pub async fn emergency_notification_reminder_job(pool: DbPool) { } if CONFIG.mail_enabled() - && let Err(e) = mail::send_emergency_access_recovery_reminder( + && let Err(e) = mail::send_emergency_access_recovery_reminder_for_locale( &grantor_user.email, &grantee_user.name, emer.get_type_as_str(), "1", // This notification is only triggered one day before the activation + grantor_user.locale.as_deref(), ) .await { diff --git a/src/api/core/events.rs b/src/api/core/events.rs index 0d9f32ad..12fbd8ff 100644 --- a/src/api/core/events.rs +++ b/src/api/core/events.rs @@ -31,9 +31,10 @@ struct EventRange { } impl EventRange { - fn date_range(&self) -> ApiResult<(NaiveDateTime, NaiveDateTime)> { - let start_date = parse_date(&self.start).map_res("Invalid start date")?; - let end_date = parse_date(self.continuation_token.as_ref().unwrap_or(&self.end)).map_res("Invalid end date")?; + fn date_range(&self, locale: &str) -> ApiResult<(NaiveDateTime, NaiveDateTime)> { + let start_date = parse_date(&self.start).map_res(crate::i18n::api_invalid_start_date(locale))?; + let end_date = parse_date(self.continuation_token.as_ref().unwrap_or(&self.end)) + .map_res(crate::i18n::api_invalid_end_date(locale))?; Ok((start_date, end_date)) } } @@ -41,14 +42,16 @@ impl EventRange { // Upstream: https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Controllers/EventsController.cs#L87 #[get("/organizations//events?")] async fn get_org_events(org_id: OrganizationId, data: EventRange, headers: AdminHeaders, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } // Return an empty vec when we org events are disabled. // This prevents client errors let events_json: Vec = if CONFIG.org_events_enabled() { - let (start_date, end_date) = data.date_range()?; + let (start_date, end_date) = data.date_range(locale)?; Event::find_by_organization_uuid(&org_id, &start_date, &end_date, &conn) .await @@ -73,7 +76,7 @@ async fn get_cipher_events(cipher_id: CipherId, data: EventRange, headers: Heade let events_json: Vec = if CONFIG.org_events_enabled() && Membership::user_has_ge_admin_access_to_cipher(&headers.user.uuid, &cipher_id, &conn).await { - let (start_date, end_date) = data.date_range()?; + let (start_date, end_date) = data.date_range(&headers.locale)?; Event::find_by_cipher_uuid(&cipher_id, &start_date, &end_date, &conn).await.iter().map(Event::to_json).collect() } else { @@ -95,13 +98,15 @@ async fn get_user_events( headers: AdminHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } // Return an empty vec when we org events are disabled. // This prevents client errors let events_json: Vec = if CONFIG.org_events_enabled() { - let (start_date, end_date) = data.date_range()?; + let (start_date, end_date) = data.date_range(locale)?; Event::find_by_org_and_member(&org_id, &member_id, &start_date, &end_date, &conn) .await @@ -162,7 +167,7 @@ async fn post_events_collect(data: Json>, headers: Headers, } for event in data.iter() { - let event_date = parse_date(&event.date).map_res("Invalid event date")?; + let event_date = parse_date(&event.date).map_res(crate::i18n::api_invalid_event_date(&headers.locale))?; // Only the event types upstream accepts from clients, the rest are written server-side. match event.r#type { t if t == EventType::UserClientExportedVault as i32 => { diff --git a/src/api/core/folders.rs b/src/api/core/folders.rs index 8c930093..beb5c14d 100644 --- a/src/api/core/folders.rs +++ b/src/api/core/folders.rs @@ -32,7 +32,7 @@ async fn get_folder(folder_id: FolderId, headers: Headers, conn: DbConn) -> Json if let Some(folder) = Folder::find_by_uuid_and_user(&folder_id, &headers.user.uuid, &conn).await { Ok(Json(folder.to_json())) } else { - err!("Invalid folder", "Folder does not exist or belongs to another user") + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)) } } @@ -78,7 +78,7 @@ async fn put_folder( let data: FolderData = data.into_inner(); let Some(mut folder) = Folder::find_by_uuid_and_user(&folder_id, &headers.user.uuid, &conn).await else { - err!("Invalid folder", "Folder does not exist or belongs to another user") + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)) }; folder.name = data.name; @@ -97,7 +97,7 @@ async fn delete_folder_post(folder_id: FolderId, headers: Headers, conn: DbConn, #[delete("/folders/")] async fn delete_folder(folder_id: FolderId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { let Some(folder) = Folder::find_by_uuid_and_user(&folder_id, &headers.user.uuid, &conn).await else { - err!("Invalid folder", "Folder does not exist or belongs to another user") + err!(crate::i18n::folder_invalid(&headers.locale), crate::i18n::folder_not_found_or_not_owned(&headers.locale)) }; // Delete the actual folder entry diff --git a/src/api/core/mod.rs b/src/api/core/mod.rs index b7923982..c536fba0 100644 --- a/src/api/core/mod.rs +++ b/src/api/core/mod.rs @@ -16,7 +16,7 @@ pub use events::{event_cleanup_job, log_event, log_user_event}; pub use sends::purge_sends; use reqwest::Method; -use rocket::{Catcher, Route, serde::json::Json, serde::json::Value}; +use rocket::{Catcher, Request, Route, serde::json::Json, serde::json::Value}; use crate::{ CONFIG, @@ -268,12 +268,14 @@ pub fn catchers() -> Vec { } #[catch(404)] -fn api_not_found() -> Json { +fn api_not_found(request: &Request<'_>) -> Json { + let locale = + crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale()); Json(json!({ "error": { "code": 404, "reason": "Not Found", - "description": "The requested resource could not be found." + "description": crate::i18n::api_not_found_description(&locale) } })) } @@ -284,8 +286,10 @@ async fn accept_org_invite( reset_password_key: Option, conn: &DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = user.locale.as_deref().unwrap_or(default_locale.as_str()); if member.status != MembershipStatus::Invited as i32 { - err!("User already accepted the invitation"); + err!(crate::i18n::org_user_already_accepted_invite(locale)); } member.status = MembershipStatus::Accepted as i32; @@ -298,10 +302,12 @@ async fn accept_org_invite( if CONFIG.mail_enabled() { let Some(org) = Organization::find_by_uuid(&member.org_uuid, conn).await else { - err!("Organization not found.") + err!(crate::i18n::org_not_found_short(locale)) }; + let invitee_email = member.invited_by_email.clone().unwrap_or(org.billing_email.clone()); + let invitee_locale = User::find_by_mail(&invitee_email, conn).await.and_then(|u| u.locale); // User was invited to an organization, so they must be confirmed manually after acceptance - mail::send_invite_accepted(&user.email, &member.invited_by_email.unwrap_or(org.billing_email), &org.name) + mail::send_invite_accepted_for_locale(&user.email, &invitee_email, &org.name, invitee_locale.as_deref()) .await?; } diff --git a/src/api/core/organizations.rs b/src/api/core/organizations.rs index 3328423e..006bb3b8 100644 --- a/src/api/core/organizations.rs +++ b/src/api/core/organizations.rs @@ -128,16 +128,23 @@ struct FullCollectionData { impl FullCollectionData { pub async fn validate(&self, org_id: &OrganizationId, conn: &DbConn) -> EmptyResult { + let locale = &CONFIG.default_locale(); let org_groups = Group::find_by_organization(org_id, conn).await; let org_group_ids: HashSet<&GroupId> = org_groups.iter().map(|c| &c.uuid).collect(); if let Some(e) = self.groups.iter().find(|g| !org_group_ids.contains(&g.id)) { - err!("Invalid group", format!("Group {} does not belong to organization {}!", e.id, org_id)) + err!( + crate::i18n::org_invalid_group(locale), + format!("Group {} does not belong to organization {}!", e.id, org_id) + ) } let org_memberships = Membership::find_by_org(org_id, conn).await; let org_membership_ids: HashSet<&MembershipId> = org_memberships.iter().map(|m| &m.uuid).collect(); if let Some(e) = self.users.iter().find(|m| !org_membership_ids.contains(&m.id)) { - err!("Invalid member", format!("Member {} does not belong to organization {}!", e.id, org_id)) + err!( + crate::i18n::org_invalid_member(locale), + format!("Member {} does not belong to organization {}!", e.id, org_id) + ) } Ok(()) @@ -183,13 +190,13 @@ struct BulkMembershipIds { #[post("/organizations", data = "")] async fn create_organization(headers: Headers, data: Json, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if !CONFIG.is_org_creation_allowed(&headers.user.email) { - err!("User not allowed to create organizations") + err!(crate::i18n::org_user_not_allowed_create(locale)) } if OrgPolicy::is_applicable_to_user(&headers.user.uuid, OrgPolicyType::SingleOrg, None, &conn).await { - err!( - "You may not create an organization. You belong to an organization which has a policy that prohibits you from being a member of any other organization." - ) + err!(crate::i18n::org_single_org_policy_prohibits_membership(locale)) } let data: OrgData = data.into_inner(); @@ -222,30 +229,34 @@ async fn delete_organization( headers: OwnerHeaders, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: PasswordOrOtpData = data.into_inner(); data.validate(&headers.user, true, &conn).await?; match Organization::find_by_uuid(&org_id, &conn).await { - None => err!("Organization not found"), + None => err!(crate::i18n::org_not_found(locale)), Some(org) => org.delete(&conn).await, } } #[post("/organizations//leave")] async fn leave_organization(org_id: OrganizationId, headers: OrgMemberHeaders, conn: DbConn) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if headers.membership.status != MembershipStatus::Confirmed as i32 { - err!("You need to be a Member of the Organization to call this endpoint") + err!(crate::i18n::org_member_required(locale)) } let membership = headers.membership; if membership.atype == MembershipType::Owner && Membership::count_confirmed_by_org_and_type(&org_id, MembershipType::Owner, &conn).await <= 1 { - err!("The last owner can't leave") + err!(crate::i18n::org_cannot_leave_last_owner(locale)) } log_event( @@ -264,13 +275,15 @@ async fn leave_organization(org_id: OrganizationId, headers: OrgMemberHeaders, c #[get("/organizations/")] async fn get_organization(org_id: OrganizationId, headers: OwnerHeaders, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } if let Some(organization) = Organization::find_by_uuid(&org_id, &conn).await { Ok(Json(organization.to_json())) } else { - err!("Can't find organization details") + err!(crate::i18n::org_not_found(locale)) } } @@ -281,14 +294,16 @@ async fn put_organization( data: Json, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: OrganizationUpdateData = data.into_inner(); let Some(mut org) = Organization::find_by_uuid(&org_id, &conn).await else { - err!("Organization not found") + err!(crate::i18n::org_not_found(locale)) }; org.name = data.name; @@ -356,8 +371,10 @@ async fn get_auto_enroll_status(identifier: &str, headers: Headers, conn: DbConn #[get("/organizations//collections")] async fn get_org_collections(org_id: OrganizationId, headers: ManagerHeadersLoose, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } if !headers.membership.has_full_access() { @@ -373,12 +390,14 @@ async fn get_org_collections(org_id: OrganizationId, headers: ManagerHeadersLoos #[get("/organizations//collections/details")] async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHeadersLoose, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let Some(member) = Membership::find_by_user_and_org(&headers.user.uuid, &org_id, &conn).await else { - err!("User is not part of organization") + err!(crate::i18n::org_user_not_part(locale)) }; // get all collection memberships for the current organization @@ -471,14 +490,16 @@ async fn post_organization_collections( data: Json, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: FullCollectionData = data.into_inner(); data.validate(&org_id, &conn).await?; if headers.membership.atype == MembershipType::Manager && !headers.membership.access_all { - err!("You don't have permission to create collections") + err!(crate::i18n::org_no_permission_create_collections(locale)) } let collection = Collection::new(org_id.clone(), data.name, data.external_id); @@ -503,7 +524,7 @@ async fn post_organization_collections( for user in data.users { let Some(member) = Membership::find_by_uuid_and_org(&user.id, &org_id, &conn).await else { - err!("User is not part of organization") + err!(crate::i18n::org_user_not_part(locale)) }; if member.access_all { @@ -539,29 +560,34 @@ async fn post_bulk_access_collections( data: Json, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: BulkCollectionAccessData = data.into_inner(); if Organization::find_by_uuid(&org_id, &conn).await.is_none() { - err!("Can't find organization details") + err!(crate::i18n::org_not_found(locale)) } // The collections and members are checked below, the groups only here. let org_groups = Group::find_by_organization(&org_id, &conn).await; let org_group_ids: HashSet<&GroupId> = org_groups.iter().map(|g| &g.uuid).collect(); if let Some(g) = data.groups.iter().find(|g| !org_group_ids.contains(&g.id)) { - err!("Invalid group", format!("Group {} does not belong to organization {}!", g.id, org_id)) + err!( + crate::i18n::org_invalid_group(locale), + format!("Group {} does not belong to organization {}!", g.id, org_id) + ) } for col_id in data.collection_ids { let Some(collection) = Collection::find_by_uuid_and_org(&col_id, &org_id, &conn).await else { - err!("Collection not found") + err!(crate::i18n::org_collection_not_found(locale)) }; if !collection.is_manageable_by_user(&headers.membership.user_uuid, &conn).await { - err!("Collection not found", "The current user isn't a manager for this collection") + err!(crate::i18n::org_collection_not_found(locale), "The current user isn't a manager for this collection") } // update collection modification date @@ -588,7 +614,7 @@ async fn post_bulk_access_collections( CollectionUser::delete_all_by_collection(&col_id, &conn).await?; for user in &data.users { let Some(member) = Membership::find_by_uuid_and_org(&user.id, &org_id, &conn).await else { - err!("User is not part of organization") + err!(crate::i18n::org_user_not_part(locale)) }; if member.access_all { @@ -611,18 +637,20 @@ async fn put_organization_collection_update( data: Json, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: FullCollectionData = data.into_inner(); data.validate(&org_id, &conn).await?; if Organization::find_by_uuid(&org_id, &conn).await.is_none() { - err!("Can't find organization details") + err!(crate::i18n::org_not_found(locale)) } let Some(mut collection) = Collection::find_by_uuid_and_org(&col_id, &org_id, &conn).await else { - err!("Collection not found") + err!(crate::i18n::org_collection_not_found(locale)) }; collection.name = data.name; @@ -656,7 +684,7 @@ async fn put_organization_collection_update( for user in data.users { let Some(member) = Membership::find_by_uuid_and_org(&user.id, &org_id, &conn).await else { - err!("User is not part of organization") + err!(crate::i18n::org_user_not_part(locale)) }; if member.access_all { @@ -676,11 +704,16 @@ async fn delete_organization_collection_impl( headers: &ManagerHeaders, conn: &DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let Some(collection) = Collection::find_by_uuid_and_org(col_id, org_id, conn).await else { - err!("Collection not found", "Collection does not exist or does not belong to this organization") + err!( + crate::i18n::org_collection_not_found(locale), + "Collection does not exist or does not belong to this organization" + ) }; log_event( EventType::CollectionDeleted, @@ -718,8 +751,10 @@ async fn bulk_delete_organization_collections( data: Json, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: BulkCollectionIds = data.into_inner(); @@ -740,18 +775,20 @@ async fn get_org_collection_detail( headers: ManagerHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } match Collection::find_by_uuid_and_user(&col_id, headers.user.uuid.clone(), &conn).await { - None => err!("Collection not found"), + None => err!(crate::i18n::org_collection_not_found(locale)), Some(collection) => { if collection.org_uuid != org_id { - err!("Collection is not owned by organization") + err!(crate::i18n::org_collection_not_found(locale), "Collection is not owned by organization") } let Some(member) = Membership::find_by_user_and_org(&headers.user.uuid, &org_id, &conn).await else { - err!("User is not part of organization") + err!(crate::i18n::org_user_not_part(locale)) }; let groups: Vec = if CONFIG.org_groups_enabled() { @@ -805,12 +842,17 @@ async fn get_collection_users( headers: ManagerHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } // Get org and collection, check that collection is from org let Some(collection) = Collection::find_by_uuid_and_org(&col_id, &org_id, &conn).await else { - err!("Collection not found in Organization") + err!(crate::i18n::org_collection_not_found(locale), "Collection not found in Organization") }; let mut member_list = Vec::new(); @@ -899,7 +941,10 @@ async fn get_members( conn: DbConn, ) -> JsonResult { if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !headers.membership.has_full_access() { @@ -934,17 +979,22 @@ async fn post_org_keys( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let data: OrgKeyData = data.into_inner(); let mut org = if let Some(organization) = Organization::find_by_uuid(&org_id, &conn).await { if organization.private_key.is_some() && organization.public_key.is_some() { - err!("Organization Keys already exist") + err!(crate::i18n::org_keys_already_exist( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) } organization } else { - err!("Can't find organization details") + err!(crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; org.private_key = Some(data.encrypted_private_key); @@ -972,16 +1022,23 @@ struct InviteData { impl InviteData { async fn validate(&self, org_id: &OrganizationId, conn: &DbConn) -> EmptyResult { + let locale = &CONFIG.default_locale(); let org_collections = Collection::find_by_organization(org_id, conn).await; let org_collection_ids: HashSet<&CollectionId> = org_collections.iter().map(|c| &c.uuid).collect(); if let Some(e) = self.collections.iter().flatten().find(|c| !org_collection_ids.contains(&c.id)) { - err!("Invalid collection", format!("Collection {} does not belong to organization {}!", e.id, org_id)) + err!( + crate::i18n::org_invalid_collection(locale), + format!("Collection {} does not belong to organization {}!", e.id, org_id) + ) } let org_groups = Group::find_by_organization(org_id, conn).await; let org_group_ids: HashSet<&GroupId> = org_groups.iter().map(|c| &c.uuid).collect(); if let Some(e) = self.groups.iter().find(|g| !org_group_ids.contains(g)) { - err!("Invalid group", format!("Group {} does not belong to organization {}!", e, org_id)) + err!( + crate::i18n::org_invalid_group(locale), + format!("Group {} does not belong to organization {}!", e, org_id) + ) } Ok(()) @@ -995,8 +1052,10 @@ async fn send_invite( headers: AdminHeaders, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: InviteData = data.into_inner(); data.validate(&org_id, &conn).await?; @@ -1008,11 +1067,11 @@ async fn send_invite( let new_type = if let Some(new_type) = MembershipType::from_str(raw_type) { new_type as i32 } else { - err!("Invalid type") + err!(crate::i18n::org_invalid_type(locale)) }; if new_type != MembershipType::User && headers.membership_type != MembershipType::Owner { - err!("Only Owners can invite Managers, Admins or Owners") + err!(crate::i18n::org_only_owners_invite_privileged(locale)) } // HACK: This converts the Custom role which has the `Manage all collections` box checked into an access_all flag @@ -1030,11 +1089,14 @@ async fn send_invite( let user = match User::find_by_mail(email, &conn).await { None => { if !CONFIG.invitations_allowed() { - err!(format!("User does not exist: {}", email.escape_debug())) + err!(crate::i18n::org_user_not_found(locale), email.escape_debug().to_string()) } if !CONFIG.is_email_domain_allowed(email) { - err!("Email domain not eligible for invitations") + err!( + crate::i18n::accounts_email_domain_not_allowed(locale), + "Email domain not eligible for invitations" + ) } if !CONFIG.mail_enabled() { @@ -1048,7 +1110,7 @@ async fn send_invite( } Some(user) => { if Membership::find_by_user_and_org(&user.uuid, &org_id, &conn).await.is_some() { - err!(format!("User already in organization: {}", email.escape_debug())) + err!(crate::i18n::org_user_already_in_organization(locale), email.escape_debug().to_string()) } if !CONFIG.mail_enabled() { @@ -1074,7 +1136,7 @@ async fn send_invite( let org_name = if let Some(org) = Organization::find_by_uuid(&org_id, &conn).await { org.name } else { - err!("Error looking up organization") + err!(crate::i18n::org_error_lookup_organization(locale), "Error looking up organization") }; if let Err(e) = mail::send_invite( @@ -1093,7 +1155,7 @@ async fn send_invite( new_member.delete(&conn).await?; } - err!(format!("Error sending invite: {e:?} ")); + err!(crate::i18n::org_error_sending_invite(locale), format!("{e:?}")); } } @@ -1112,7 +1174,9 @@ async fn send_invite( if !access_all { for col in data.collections.iter().flatten() { match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { - None => err!("Collection not found in Organization"), + None => { + err!(crate::i18n::org_collection_not_found(locale), "Collection not found in Organization") + } Some(collection) => { CollectionUser::save( &user.uuid, @@ -1130,7 +1194,7 @@ async fn send_invite( for group_id in &data.groups { if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() { - err!("Group not found in Organization") + err!(crate::i18n::org_group_not_found(locale), "Group not found in Organization") } let mut group_entry = GroupUser::new(group_id.clone(), new_member.uuid.clone()); group_entry.save(&conn).await?; @@ -1147,8 +1211,10 @@ async fn bulk_reinvite_members( headers: AdminHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: BulkMembershipIds = data.into_inner(); @@ -1185,8 +1251,10 @@ async fn reinvite_member( headers: AdminHeaders, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } reinvite_member_impl(&org_id, &member_id, &headers.user.email, &conn).await } @@ -1197,26 +1265,30 @@ async fn reinvite_member_impl( invited_by_email: &str, conn: &DbConn, ) -> EmptyResult { + let locale = User::find_by_mail(invited_by_email, conn) + .await + .and_then(|u| u.locale) + .unwrap_or_else(|| crate::i18n::normalize_locale(&CONFIG.default_locale())); let Some(member) = Membership::find_by_uuid_and_org(member_id, org_id, conn).await else { - err!("The user hasn't been invited to the organization.") + err!(crate::i18n::org_user_not_invited(&locale)) }; if member.status != MembershipStatus::Invited as i32 { - err!("The user is already accepted or confirmed to the organization") + err!(crate::i18n::org_user_already_accepted_or_confirmed(&locale)) } let Some(user) = User::find_by_uuid(&member.user_uuid, conn).await else { - err!("User not found.") + err!(crate::i18n::org_user_not_found(&locale)) }; if !CONFIG.invitations_allowed() && user.password_hash.is_empty() { - err!("Invitations are not allowed.") + err!(crate::i18n::org_invitations_not_allowed(&locale)) } let org_name = if let Some(org) = Organization::find_by_uuid(org_id, conn).await { org.name } else { - err!("Error looking up organization.") + err!(crate::i18n::org_error_lookup_organization(&locale)) }; if CONFIG.mail_enabled() { @@ -1251,21 +1323,26 @@ async fn accept_invite( ) -> EmptyResult { // The web-vault passes org_id and member_id in the URL, but we are just reading them from the JWT instead let data: AcceptData = data.into_inner(); + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); let claims = decode_invite(&data.token)?; // Don't allow other users from accepting an invitation. if !claims.email.eq(&headers.user.email) { - err!("Invitation was issued to a different account", "Claim does not match user_id") + err!( + crate::i18n::org_invitation_issued_to_different_account(locale), + crate::i18n::org_claim_mismatch_user_id(locale) + ) } // If a claim org_id does not match the one in from the URI, something is wrong. if !claims.org_id.eq(&org_id) { - err!("Error accepting the invitation", "Claim does not match the org_id") + err!(crate::i18n::org_error_accepting_invitation(locale), crate::i18n::org_claim_mismatch_org_id(locale)) } // If a claim does not have a member_id or it does not match the one in from the URI, something is wrong. if !claims.member_id.eq(&member_id) { - err!("Error accepting the invitation", "Claim does not match the member_id") + err!(crate::i18n::org_error_accepting_invitation(locale), crate::i18n::org_claim_mismatch_member_id(locale)) } let member_id = &claims.member_id; @@ -1274,11 +1351,11 @@ async fn accept_invite( // skip invitation logic when we were invited via the /admin panel if **member_id != FAKE_ADMIN_UUID { let Some(mut membership) = Membership::find_by_uuid_and_org(member_id, &claims.org_id, &conn).await else { - err!("Error accepting the invitation") + err!(crate::i18n::org_error_accepting_invitation(locale)) }; let reset_password_key = match OrgPolicy::org_is_reset_password_auto_enroll(&membership.org_uuid, &conn).await { - true if data.reset_password_key.is_none() => err!("Reset password key is required, but not provided."), + true if data.reset_password_key.is_none() => err!(crate::i18n::org_reset_password_key_required(locale)), true => data.reset_password_key, false => None, }; @@ -1290,7 +1367,8 @@ async fn accept_invite( } else if CONFIG.mail_enabled() { // User was invited from /admin, so they are automatically confirmed let org_name = CONFIG.invitation_org_name(); - mail::send_invite_confirmed(&claims.email, &org_name).await?; + let locale = User::find_by_mail(&claims.email, &conn).await.and_then(|u| u.locale); + mail::send_invite_confirmed_for_locale(&claims.email, &org_name, locale.as_deref()).await?; } Ok(()) @@ -1317,8 +1395,10 @@ async fn bulk_confirm_invite( conn: DbConn, nt: Notify<'_>, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data = data.into_inner(); @@ -1327,7 +1407,7 @@ async fn bulk_confirm_invite( Some(keys) => { for invite in keys { let Some(member_id) = invite.id else { - err!("Member id is required") + err!(crate::i18n::org_member_id_required(locale)) }; let user_key = invite.key.unwrap_or_default(); let err_msg = match confirm_invite_impl(&org_id, &member_id, &user_key, &headers, &conn, &nt).await { @@ -1379,23 +1459,25 @@ async fn confirm_invite_impl( conn: &DbConn, nt: &Notify<'_>, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } if key.is_empty() || member_id.is_empty() { - err!("Key or UserId is not set, unable to process request"); + err!(crate::i18n::org_key_or_userid_not_set(locale)); } let Some(mut member_to_confirm) = Membership::find_by_uuid_and_org(member_id, org_id, conn).await else { - err!("The specified user isn't a member of the organization") + err!(crate::i18n::org_user_not_member(locale)) }; if member_to_confirm.atype != MembershipType::User && headers.membership_type != MembershipType::Owner { - err!("Only Owners can confirm Managers, Admins or Owners") + err!(crate::i18n::org_only_owners_confirm_privileged(locale)) } if member_to_confirm.status != MembershipStatus::Accepted as i32 { - err!("User in invalid state") + err!(crate::i18n::org_user_invalid_state(locale)) } member_to_confirm.status = MembershipStatus::Confirmed as i32; @@ -1419,14 +1501,12 @@ async fn confirm_invite_impl( let org_name = if let Some(org) = Organization::find_by_uuid(org_id, conn).await { org.name } else { - err!("Error looking up organization.") + err!(crate::i18n::org_error_lookup_organization(locale)) }; - let address = if let Some(user) = User::find_by_uuid(&member_to_confirm.user_uuid, conn).await { - user.email - } else { - err!("Error looking up user.") + let Some(user) = User::find_by_uuid(&member_to_confirm.user_uuid, conn).await else { + err!(crate::i18n::org_error_lookup_user(locale)) }; - mail::send_invite_confirmed(&address, &org_name).await?; + mail::send_invite_confirmed_for_locale(&user.email, &org_name, user.locale.as_deref()).await?; } let save_result = member_to_confirm.save(conn).await; @@ -1440,8 +1520,10 @@ async fn confirm_invite_impl( #[get("/organizations//users/mini-details", rank = 1)] async fn get_org_user_mini_details(org_id: OrganizationId, headers: ManagerHeadersLoose, conn: DbConn) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let mut members_json = Vec::new(); for m in Membership::find_by_org(&org_id, &conn).await { @@ -1463,11 +1545,13 @@ async fn get_user( headers: AdminHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let Some(user) = Membership::find_by_uuid_and_org(&member_id, &org_id, &conn).await else { - err!("The specified user isn't a member of the organization") + err!(crate::i18n::org_user_not_member(locale)) }; // In this case, when groups are requested we also need to include collections. @@ -1496,8 +1580,10 @@ async fn edit_member( headers: AdminHeaders, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: EditUserData = data.into_inner(); @@ -1506,7 +1592,7 @@ async fn edit_member( let raw_type = &data.r#type.into_string(); // MembershipType::from_str will convert custom (4) to manager (3) let Some(new_type) = MembershipType::from_str(raw_type) else { - err!("Invalid type") + err!(crate::i18n::org_invalid_type(locale)) }; // HACK: This converts the Custom role which has the `Manage all collections` box checked into an access_all flag @@ -1519,18 +1605,18 @@ async fn edit_member( && data.permissions.get("createNewCollections") == Some(&json!(true))); let Some(mut member_to_edit) = Membership::find_by_uuid_and_org(&member_id, &org_id, &conn).await else { - err!("The specified user isn't member of the organization") + err!(crate::i18n::org_user_not_member(locale)) }; if new_type != member_to_edit.atype && (member_to_edit.atype >= MembershipType::Admin || new_type >= MembershipType::Admin) && headers.membership_type != MembershipType::Owner { - err!("Only Owners can grant and remove Admin or Owner privileges") + err!(crate::i18n::org_only_owners_grant_remove_privileged(locale)) } if member_to_edit.atype == MembershipType::Owner && headers.membership_type != MembershipType::Owner { - err!("Only Owners can edit Owner users") + err!(crate::i18n::org_only_owners_edit_owner_users(locale)) } if member_to_edit.atype == MembershipType::Owner @@ -1539,7 +1625,7 @@ async fn edit_member( { // Removing owner permission, check that there is at least one other confirmed owner if Membership::count_confirmed_by_org_and_type(&org_id, MembershipType::Owner, &conn).await <= 1 { - err!("Can't delete the last owner") + err!(crate::i18n::org_cannot_delete_last_owner(locale)) } } @@ -1559,7 +1645,7 @@ async fn edit_member( if !access_all { for col in data.collections.iter().flatten() { match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { - None => err!("Collection not found in Organization"), + None => err!(crate::i18n::org_collection_not_found(locale), "Collection not found in Organization"), Some(collection) => { CollectionUser::save( &member_to_edit.user_uuid, @@ -1579,7 +1665,7 @@ async fn edit_member( for group_id in data.groups.iter().flatten() { if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() { - err!("Group not found in Organization") + err!(crate::i18n::org_group_not_found(locale), "Group not found in Organization") } let mut group_entry = GroupUser::new(group_id.clone(), member_to_edit.uuid.clone()); group_entry.save(&conn).await?; @@ -1607,8 +1693,10 @@ async fn bulk_delete_member( conn: DbConn, nt: Notify<'_>, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data: BulkMembershipIds = data.into_inner(); @@ -1656,22 +1744,24 @@ async fn delete_member_impl( conn: &DbConn, nt: &Notify<'_>, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let Some(member_to_delete) = Membership::find_by_uuid_and_org(member_id, org_id, conn).await else { - err!("User to delete isn't member of the organization") + err!(crate::i18n::org_user_to_delete_not_member(locale)) }; if member_to_delete.atype != MembershipType::User && headers.membership_type != MembershipType::Owner { - err!("Only Owners can delete Admins or Owners") + err!(crate::i18n::org_only_owners_delete_admin_owner(locale)) } if member_to_delete.atype == MembershipType::Owner && member_to_delete.status == MembershipStatus::Confirmed as i32 { // Removing owner, check that there is at least one other confirmed owner if Membership::count_confirmed_by_org_and_type(org_id, MembershipType::Owner, conn).await <= 1 { - err!("Can't delete the last owner") + err!(crate::i18n::org_cannot_delete_last_owner(locale)) } } @@ -1710,7 +1800,10 @@ async fn bulk_public_keys( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let data: BulkMembershipIds = data.into_inner(); @@ -1784,11 +1877,14 @@ async fn post_org_import( ) -> EmptyResult { let org_id = query.organization_id; if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } // OrgMemberHeaders also allows invited and accepted members, which are not allowed to import if headers.membership.status != MembershipStatus::Confirmed as i32 { - err!("You need to be a Member of the Organization to call this endpoint") + err!(crate::i18n::org_member_required(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) } let data: ImportData = data.into_inner(); @@ -1883,7 +1979,7 @@ async fn post_bulk_collections(data: Json, headers: Headers let data: BulkCollectionsData = data.into_inner(); if Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &data.organization_id, &conn).await.is_none() { - err!("You need to be a Member of the Organization to call this endpoint") + err!(crate::i18n::org_member_required(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) } // Get all the collection available to the user in one query @@ -1935,7 +2031,10 @@ async fn post_bulk_collections(data: Json, headers: Headers #[get("/organizations//policies")] async fn list_policies(org_id: OrganizationId, headers: AdminHeaders, conn: DbConn) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let policies = OrgPolicy::find_by_org(&org_id, &conn).await; let policies_json: Vec = policies.iter().map(OrgPolicy::to_json).collect(); @@ -1949,10 +2048,11 @@ async fn list_policies(org_id: OrganizationId, headers: AdminHeaders, conn: DbCo #[get("/organizations//policies/token?")] async fn list_policies_token(org_id: OrganizationId, token: &str, conn: DbConn) -> JsonResult { + let locale = &CONFIG.default_locale(); let invite = decode_invite(token)?; if invite.org_id != org_id { - err!("Token doesn't match request organization"); + err!(crate::i18n::org_token_org_mismatch(locale)); } // exit early when we have been invited via /admin panel @@ -2001,11 +2101,14 @@ async fn get_master_password_policy(org_id: OrganizationId, _headers: OrgMemberH #[get("/organizations//policies/", rank = 3)] async fn get_policy(org_id: OrganizationId, pol_type: i32, headers: AdminHeaders, conn: DbConn) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let Some(pol_type_enum) = OrgPolicyType::from_i32(pol_type) else { - err!("Invalid or unsupported policy type") + err!(crate::i18n::org_invalid_type(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn).await { @@ -2040,12 +2143,15 @@ async fn put_policy( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let data: PolicyData = data.into_inner().policy; let Some(pol_type_enum) = OrgPolicyType::from_i32(pol_type) else { - err!("Invalid or unsupported policy type") + err!(crate::i18n::org_invalid_type(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let current_policy = OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn).await; @@ -2085,7 +2191,9 @@ async fn put_policy( }; if !single_org_policy_enabled { - err!("Single Organization policy is not enabled. It is mandatory for this policy to be enabled.") + err!(crate::i18n::org_single_org_policy_required_for_reset( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) } } @@ -2098,7 +2206,9 @@ async fn put_policy( }; if reset_pw_policy_enabled { - err!("Account recovery policy is enabled. It is not allowed to disable this policy.") + err!(crate::i18n::org_account_recovery_policy_blocks_disable( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) } } } @@ -2161,7 +2271,8 @@ async fn put_policy( let org = Organization::find_by_uuid(&member.org_uuid, &conn).await.unwrap(); let user = User::find_by_uuid(&member.user_uuid, &conn).await.unwrap(); - mail::send_single_org_removed_from_org(&user.email, &org.name).await?; + mail::send_single_org_removed_from_org_for_locale(&user.email, &org.name, user.locale.as_deref()) + .await?; } log_event( @@ -2274,8 +2385,10 @@ async fn bulk_revoke_members( headers: AdminHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data = data.into_inner(); @@ -2316,21 +2429,23 @@ async fn revoke_member_impl( headers: &AdminHeaders, conn: &DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } match Membership::find_by_uuid_and_org(member_id, org_id, conn).await { Some(mut member) if member.status > MembershipStatus::Revoked as i32 => { if member.user_uuid == headers.user.uuid { - err!("You cannot revoke yourself") + err!(crate::i18n::org_cannot_revoke_yourself(locale)) } if member.atype == MembershipType::Owner && headers.membership_type != MembershipType::Owner { - err!("Only owners can revoke other owners") + err!(crate::i18n::org_only_owners_revoke_owners(locale)) } if member.atype == MembershipType::Owner && Membership::count_confirmed_by_org_and_type(org_id, MembershipType::Owner, conn).await <= 1 { - err!("Organization must have at least one confirmed owner") + err!(crate::i18n::org_must_have_confirmed_owner(locale)) } member.revoke(); @@ -2347,8 +2462,8 @@ async fn revoke_member_impl( ) .await; } - Some(_) => err!("User is already revoked"), - None => err!("User not found in organization"), + Some(_) => err!(crate::i18n::org_user_already_revoked(locale)), + None => err!(crate::i18n::org_user_not_found_in_org(locale)), } Ok(()) } @@ -2382,8 +2497,10 @@ async fn bulk_restore_members( headers: AdminHeaders, conn: DbConn, ) -> JsonResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } let data = data.into_inner(); @@ -2419,16 +2536,18 @@ async fn restore_member_impl( headers: &AdminHeaders, conn: &DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!(crate::i18n::org_not_found(locale), "Organization id's do not match"); } match Membership::find_by_uuid_and_org(member_id, org_id, conn).await { Some(mut member) if member.status < MembershipStatus::Accepted as i32 => { if member.user_uuid == headers.user.uuid { - err!("You cannot restore yourself") + err!(crate::i18n::org_cannot_restore_yourself(locale)) } if member.atype == MembershipType::Owner && headers.membership_type != MembershipType::Owner { - err!("Only owners can restore other owners") + err!(crate::i18n::org_only_owners_restore_owners(locale)) } member.restore(); @@ -2448,8 +2567,8 @@ async fn restore_member_impl( ) .await; } - Some(_) => err!("User is already active"), - None => err!("User not found in organization"), + Some(_) => err!(crate::i18n::org_user_already_active(locale)), + None => err!(crate::i18n::org_user_not_found_in_org(locale)), } Ok(()) } @@ -2461,7 +2580,10 @@ async fn get_groups_data( conn: DbConn, ) -> JsonResult { if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } // The details view (group→collection/user mappings) needs full org access; the plain list only @@ -2544,16 +2666,23 @@ impl GroupRequest { /// Validate if all the collections and members belong to the provided organization pub async fn validate(&self, org_id: &OrganizationId, conn: &DbConn) -> EmptyResult { + let locale = &CONFIG.default_locale(); let org_collections = Collection::find_by_organization(org_id, conn).await; let org_collection_ids: HashSet<&CollectionId> = org_collections.iter().map(|c| &c.uuid).collect(); if let Some(e) = self.collections.iter().find(|c| !org_collection_ids.contains(&c.id)) { - err!("Invalid collection", format!("Collection {} does not belong to organization {}!", e.id, org_id)) + err!( + crate::i18n::org_invalid_collection(locale), + format!("Collection {} does not belong to organization {}!", e.id, org_id) + ) } let org_memberships = Membership::find_by_org(org_id, conn).await; let org_membership_ids: HashSet<&MembershipId> = org_memberships.iter().map(|m| &m.uuid).collect(); if let Some(e) = self.users.iter().find(|m| !org_membership_ids.contains(m)) { - err!("Invalid member", format!("Member {} does not belong to organization {}!", e, org_id)) + err!( + crate::i18n::org_invalid_member(locale), + format!("Member {} does not belong to organization {}!", e, org_id) + ) } Ok(()) @@ -2583,10 +2712,13 @@ async fn post_groups( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let group_request = data.into_inner(); @@ -2617,14 +2749,20 @@ async fn put_group( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let Some(group) = Group::find_by_uuid_and_org(&group_id, &org_id, &conn).await else { - err!("Group not found", "Group uuid is invalid or does not belong to the organization") + err!( + crate::i18n::org_group_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Group uuid is invalid or does not belong to the organization" + ) }; let group_request = data.into_inner(); @@ -2697,14 +2835,20 @@ async fn get_group_details( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let Some(group) = Group::find_by_uuid_and_org(&group_id, &org_id, &conn).await else { - err!("Group not found", "Group uuid is invalid or does not belong to the organization") + err!( + crate::i18n::org_group_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Group uuid is invalid or does not belong to the organization" + ) }; Ok(Json(group.to_json_details(&conn).await)) @@ -2722,14 +2866,20 @@ async fn delete_group_impl( conn: &DbConn, ) -> EmptyResult { if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let Some(group) = Group::find_by_uuid_and_org(group_id, org_id, conn).await else { - err!("Group not found", "Group uuid is invalid or does not belong to the organization") + err!( + crate::i18n::org_group_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Group uuid is invalid or does not belong to the organization" + ) }; log_event( @@ -2754,10 +2904,13 @@ async fn bulk_delete_groups( conn: DbConn, ) -> EmptyResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let data: BulkGroupIds = data.into_inner(); @@ -2771,14 +2924,20 @@ async fn bulk_delete_groups( #[get("/organizations//groups/", rank = 2)] async fn get_group(org_id: OrganizationId, group_id: GroupId, headers: AdminHeaders, conn: DbConn) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } let Some(group) = Group::find_by_uuid_and_org(&group_id, &org_id, &conn).await else { - err!("Group not found", "Group uuid is invalid or does not belong to the organization") + err!( + crate::i18n::org_group_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Group uuid is invalid or does not belong to the organization" + ) }; Ok(Json(group.to_json())) @@ -2792,14 +2951,20 @@ async fn get_group_members( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } if !CONFIG.org_groups_enabled() { - err!("Group support is disabled"); + err!(crate::i18n::org_groups_disabled(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))); } if Group::find_by_uuid_and_org(&group_id, &org_id, &conn).await.is_none() { - err!("Group could not be found!", "Group uuid is invalid or does not belong to the organization") + err!( + crate::i18n::org_group_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Group uuid is invalid or does not belong to the organization" + ) } let group_members: Vec = GroupUser::find_by_group(&group_id, &org_id, &conn) @@ -2842,10 +3007,13 @@ struct OrganizationUserRecoverAccountRequest { #[get("/organizations//public-key")] async fn get_organization_public_key(org_id: OrganizationId, headers: OrgMemberHeaders, conn: DbConn) -> JsonResult { if org_id != headers.membership.org_uuid { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let Some(org) = Organization::find_by_uuid(&org_id, &conn).await else { - err!("Organization not found") + err!(crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; Ok(Json(json!({ @@ -2884,27 +3052,34 @@ async fn recover_account( nt: Notify<'_>, ) -> EmptyResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let Some(org) = Organization::find_by_uuid(&org_id, &conn).await else { - err!("Required organization not found") + err!(crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let Some(member) = Membership::find_by_uuid_and_org(&member_id, &org.uuid, &conn).await else { - err!("User to reset isn't member of required organization") + err!(crate::i18n::org_user_not_member(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let Some(mut user) = User::find_by_uuid(&member.user_uuid, &conn).await else { - err!("User not found") + err!(crate::i18n::org_user_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; check_reset_password_applicable_and_permissions(&org_id, &member_id, &headers, &conn).await?; if member.reset_password_key.is_none() { - err!("Password reset not or not correctly enrolled"); + err!(crate::i18n::org_password_reset_not_enrolled( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )); } if member.status != (MembershipStatus::Confirmed as i32) { - err!("Organization user must be confirmed for password reset functionality"); + err!(crate::i18n::org_user_must_be_confirmed_for_reset( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )); } let fallback_2fa_email = @@ -2923,7 +3098,9 @@ async fn recover_account( authentication_data.check(&user, &unlock_data)?; if !authentication_data.kdf.matches_user(&user) { - err!("KDF settings do not match the user account") + err!(crate::i18n::org_kdf_settings_do_not_match_user( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) } (authentication_data.master_password_authentication_hash, unlock_data.master_key_wrapped_user_key) @@ -2939,17 +3116,23 @@ async fn recover_account( // Sending email first ensure working email configuration and the resulting user notification. // Also this might add some protection against security flaws and misuse - if let Err(e) = mail::send_admin_account_recovery( + if let Err(e) = mail::send_admin_account_recovery_for_locale( &user.email, user.display_name(), &org.name, req.reset_master_password, req.reset_two_factor, fallback_2fa_email, + user.locale.as_deref(), ) .await { - err!(format!("Error sending user reset password email: {e:#?}")); + err!( + crate::i18n::org_error_sending_user_reset_password_email( + headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + ), + format!("{e:#?}") + ); } if let Some((new_master_password_hash, new_key)) = new_password { @@ -2988,18 +3171,21 @@ async fn get_reset_password_details( conn: DbConn, ) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let Some(org) = Organization::find_by_uuid(&org_id, &conn).await else { - err!("Required organization not found") + err!(crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let Some(member) = Membership::find_by_uuid_and_org(&member_id, &org_id, &conn).await else { - err!("User to reset isn't member of required organization") + err!(crate::i18n::org_user_not_member(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; let Some(user) = User::find_by_uuid(&member.user_uuid, &conn).await else { - err!("User not found") + err!(crate::i18n::org_user_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()))) }; check_reset_password_applicable_and_permissions(&org_id, &member_id, &headers, &conn).await?; @@ -3024,31 +3210,33 @@ async fn check_reset_password_applicable_and_permissions( headers: &AdminHeaders, conn: &DbConn, ) -> EmptyResult { - check_reset_password_applicable(org_id, conn).await?; + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); + check_reset_password_applicable(org_id, conn, locale).await?; let Some(target_user) = Membership::find_by_uuid_and_org(member_id, org_id, conn).await else { - err!("Reset target user not found") + err!(crate::i18n::org_user_not_found_in_org(locale)) }; // Resetting user must be higher/equal to user to reset match headers.membership_type { MembershipType::Owner => Ok(()), MembershipType::Admin if target_user.atype <= MembershipType::Admin => Ok(()), - _ => err!("No permission to reset this user's password"), + _ => err!(crate::i18n::org_no_permission_reset_user_password(locale)), } } -async fn check_reset_password_applicable(org_id: &OrganizationId, conn: &DbConn) -> EmptyResult { +async fn check_reset_password_applicable(org_id: &OrganizationId, conn: &DbConn, locale: &str) -> EmptyResult { if !CONFIG.mail_enabled() { - err!("Password reset is not supported on an email-disabled instance."); + err!(crate::i18n::org_password_reset_not_supported_email_disabled(locale)); } let Some(policy) = OrgPolicy::find_by_org_and_type(org_id, OrgPolicyType::ResetPassword, conn).await else { - err!("Policy not found") + err!(crate::i18n::org_policy_not_found(locale)) }; if !policy.enabled { - err!("Reset password policy not enabled"); + err!(crate::i18n::org_reset_password_policy_not_enabled(locale)); } Ok(()) @@ -3062,13 +3250,15 @@ async fn put_reset_password_enrollment( data: Json, conn: DbConn, ) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = headers.user.locale.as_deref().unwrap_or(default_locale.as_str()); if user_id != headers.user.uuid { - err!("User to enroll isn't member of required organization", "The user_id and acting user do not match"); + err!(crate::i18n::org_user_not_member(locale), "The user_id and acting user do not match"); } let mut membership = headers.membership; - check_reset_password_applicable(&org_id, &conn).await?; + check_reset_password_applicable(&org_id, &conn, locale).await?; let reset_request = data.into_inner(); @@ -3079,7 +3269,7 @@ async fn put_reset_password_enrollment( }; if reset_password_key.is_none() && OrgPolicy::org_is_reset_password_auto_enroll(&org_id, &conn).await { - err!("Reset password can't be withdrawn due to an enterprise policy"); + err!(crate::i18n::org_reset_password_withdraw_blocked_by_policy(locale)); } if reset_password_key.is_some() { @@ -3115,7 +3305,10 @@ async fn put_reset_password_enrollment( #[get("/organizations//export")] async fn get_org_export(org_id: OrganizationId, headers: AdminHeaders, conn: DbConn) -> JsonResult { if org_id != headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } Ok(Json(json!({ @@ -3132,7 +3325,10 @@ async fn api_key( conn: DbConn, ) -> JsonResult { if org_id != &headers.org_id { - err!("Organization not found", "Organization id's do not match"); + err!( + crate::i18n::org_not_found(headers.user.locale.as_deref().unwrap_or(&CONFIG.default_locale())), + "Organization id's do not match" + ); } let data: PasswordOrOtpData = data.into_inner(); let user = headers.user; diff --git a/src/api/core/public.rs b/src/api/core/public.rs index 1ee80515..ac20b142 100644 --- a/src/api/core/public.rs +++ b/src/api/core/public.rs @@ -108,7 +108,7 @@ async fn ldap_import(data: Json, token: PublicToken, conn: DbConn let (org_name, org_email) = if let Some(org) = Organization::find_by_uuid(&org_id, &conn).await { (org.name, org.billing_email) } else { - err!("Error looking up organization") + err!(crate::i18n::org_error_lookup_organization_short(&CONFIG.default_locale())) }; let mut new_member = Membership::new(user.uuid.clone(), org_id.clone(), Some(org_email.clone())); @@ -130,7 +130,7 @@ async fn ldap_import(data: Json, token: PublicToken, conn: DbConn new_member.delete(&conn).await?; } - err!(format!("Error sending invite: {e:?} ")); + err!(crate::i18n::org_error_sending_invite(&CONFIG.default_locale()), format!("{e:?}")); } } } diff --git a/src/api/core/sends.rs b/src/api/core/sends.rs index 2a604b74..b5927fe9 100644 --- a/src/api/core/sends.rs +++ b/src/api/core/sends.rs @@ -103,7 +103,7 @@ async fn enforce_disable_send_policy(headers: &Headers, conn: &DbConn) -> EmptyR if !CONFIG.sends_allowed() || OrgPolicy::is_applicable_to_user(user_id, OrgPolicyType::DisableSend, None, conn).await { - err!("Due to an Enterprise Policy, you are only able to delete an existing Send.") + err!(crate::i18n::send_delete_only_policy(&headers.locale)) } Ok(()) } @@ -118,10 +118,7 @@ async fn enforce_disable_hide_email_policy(data: &SendData, headers: &Headers, c let user_id = &headers.user.uuid; let hide_email = data.hide_email.unwrap_or(false); if hide_email && OrgPolicy::is_hide_email_disabled(user_id, conn).await { - err!( - "Due to an Enterprise Policy, you are not allowed to hide your email address \ - from recipients when creating or editing a Send." - ) + err!(crate::i18n::send_hide_email_policy_forbidden(&headers.locale)) } Ok(()) } @@ -132,24 +129,22 @@ fn create_send(data: SendData, user_id: UserId) -> ApiResult { } else if data.r#type == SendType::File as i32 { data.file } else { - err!("Invalid Send type") + err!(crate::i18n::send_invalid_type(&CONFIG.default_locale())) }; let data_str = if let Some(mut d) = data_val { d.as_object_mut().and_then(|o| o.remove("response")); serde_json::to_string(&d)? } else { - err!("Send data not provided"); + err!(crate::i18n::send_data_not_provided(&CONFIG.default_locale())); }; if data.deletion_date > Utc::now() + TimeDelta::try_days(31).unwrap() { - err!( - "You cannot have a Send with a deletion date that far into the future. Adjust the Deletion Date to a value less than 31 days from now and try again." - ); + err!(crate::i18n::send_deletion_date_too_far(&CONFIG.default_locale())); } if data.emails.is_some() { - err!("Sends with email verification is not supported"); + err!(crate::i18n::send_email_verification_not_supported(&CONFIG.default_locale())); } let mut send = Send::new(data.r#type, data.name, data_str, data.key, data.deletion_date.naive_utc()); @@ -186,7 +181,7 @@ async fn get_send(send_id: SendId, headers: Headers, conn: DbConn) -> JsonResult if let Some(send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await { Ok(Json(send.to_json())) } else { - err!("Send not found", "Invalid send uuid or does not belong to user") + err!(crate::i18n::send_not_found(&headers.locale), crate::i18n::send_invalid_uuid_or_not_owned(&headers.locale)) } } @@ -198,7 +193,7 @@ async fn post_send(data: Json, headers: Headers, conn: DbConn, nt: Not enforce_disable_hide_email_policy(&data, &headers, &conn).await?; if data.r#type == SendType::File as i32 { - err!("File sends should use /api/sends/file/v2") + err!(crate::i18n::send_file_use_v2(&headers.locale)) } let mut send = create_send(data, headers.user.uuid)?; @@ -228,7 +223,7 @@ async fn post_send_file_v2(data: Json, headers: Headers, conn: DbConn) let data = data.into_inner(); if data.r#type != SendType::File as i32 { - err!("Send content is not a file"); + err!(crate::i18n::send_content_not_file(&headers.locale)); } enforce_disable_hide_email_policy(&data, &headers, &conn).await?; @@ -236,23 +231,23 @@ async fn post_send_file_v2(data: Json, headers: Headers, conn: DbConn) let file_length = if let Some(m) = &data.file_length { m.into_i64()? } else { - err!("Invalid send length") + err!(crate::i18n::send_invalid_length(&headers.locale)) }; if file_length < 0 { - err!("Send size can't be negative") + err!(crate::i18n::send_size_negative(&headers.locale)) } let size_limit = match CONFIG.user_send_limit() { - Some(0) => err!("File uploads are disabled"), + Some(0) => err!(crate::i18n::send_file_uploads_disabled(&headers.locale)), Some(limit_kb) => { let Some(already_used) = Send::size_by_user(&headers.user.uuid, &conn).await else { - err!("Existing sends overflow") + err!(crate::i18n::send_existing_overflow(&headers.locale)) }; let Some(left) = limit_kb.checked_mul(1024).and_then(|l| l.checked_sub(already_used)) else { - err!("Send size overflow"); + err!(crate::i18n::send_size_overflow(&headers.locale)); }; if left <= 0 { - err!("Send storage limit reached! Delete some sends to free up space") + err!(crate::i18n::send_storage_limit_reached(&headers.locale)) } i64::clamp(left, 0, SIZE_525_MB) } @@ -260,7 +255,7 @@ async fn post_send_file_v2(data: Json, headers: Headers, conn: DbConn) }; if file_length > size_limit { - err!("Send storage limit exceeded with this file"); + err!(crate::i18n::send_storage_limit_exceeded_file(&headers.locale)); } let mut send = create_send(data, headers.user.uuid)?; @@ -307,15 +302,18 @@ async fn post_send_file_v2_data( let data = data.into_inner(); let Some(send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await else { - err!("Send not found. Unable to save the file.", "Invalid send uuid or does not belong to user.") + err!( + crate::i18n::send_not_found_unable_save_file(&headers.locale), + crate::i18n::send_invalid_uuid_or_not_owned(&headers.locale) + ) }; if send.atype != SendType::File as i32 { - err!("Send is not a file type send."); + err!(crate::i18n::send_not_file_type(&headers.locale)); } let Ok(send_data) = serde_json::from_str::(&send.data) else { - err!("Unable to decode send data as json.") + err!(crate::i18n::send_unable_decode_json(&headers.locale)) }; match data.data.raw_name() { @@ -325,26 +323,32 @@ async fn post_send_file_v2_data( || (headers.device.is_cli() && send_data.fileName.ends_with(raw_file_name.dangerous_unsafe_unsanitized_raw().as_str()) ) => {} Some(raw_file_name) => err!( - "Send file name does not match.", + crate::i18n::send_file_name_mismatch(&headers.locale), format!( "Expected file name '{}' got '{}'", send_data.fileName.escape_debug(), raw_file_name.dangerous_unsafe_unsanitized_raw().as_str().escape_debug() ) ), - _ => err!("Send file name does not match or is not provided."), + _ => err!(crate::i18n::send_file_name_missing_or_mismatch(&headers.locale)), } if file_id != send_data.id { - err!("Send file does not match send data.", format!("Expected id {} got {file_id}", send_data.id)); + err!( + crate::i18n::send_file_mismatch_data(&headers.locale), + format!("Expected id {} got {file_id}", send_data.id) + ); } let Some(size) = data.data.len().to_u64() else { - err!("Send file size overflow."); + err!(crate::i18n::send_file_size_overflow(&headers.locale)); }; if size != send_data.size { - err!("Send file size does not match.", format!("Expected a file size of {} got {size}", send_data.size)); + err!( + crate::i18n::send_file_size_mismatch(&headers.locale), + format!("Expected a file size of {} got {size}", send_data.size) + ); } let file_path = format!("{send_id}/{file_id}"); @@ -414,7 +418,7 @@ async fn post_access_file( fn check_send_file_id(send: &Send, file_id: &SendFileId) -> EmptyResult { if send.atype != SendType::File as i32 { - err!("Send is not a file type send."); + err!(crate::i18n::send_not_file_type(&CONFIG.default_locale())); } match serde_json::from_str::(&send.data) { Ok(data) if &data.id == file_id => Ok(()), @@ -470,11 +474,14 @@ async fn put_send(send_id: SendId, data: Json, headers: Headers, conn: enforce_disable_hide_email_policy(&data, &headers, &conn).await?; let Some(mut send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await else { - err!("Send not found", "Send send_id is invalid or does not belong to user") + err!( + crate::i18n::send_not_found(&headers.locale), + crate::i18n::send_invalid_send_id_or_not_owned(&headers.locale) + ) }; if data.emails.is_some() { - err!("Sends with email verification is not supported"); + err!(crate::i18n::send_email_verification_not_supported(&headers.locale)); } update_send_from_data(&mut send, data, &headers, &conn, &nt, UpdateType::SyncSendUpdate).await?; @@ -491,17 +498,15 @@ async fn update_send_from_data( ut: UpdateType, ) -> EmptyResult { if send.user_uuid.as_ref() != Some(&headers.user.uuid) { - err!("Send is not owned by user") + err!(crate::i18n::send_not_owned_by_user(&headers.locale)) } if send.atype != data.r#type { - err!("Sends can't change type") + err!(crate::i18n::send_cannot_change_type(&headers.locale)) } if data.deletion_date > Utc::now() + TimeDelta::try_days(31).unwrap() { - err!( - "You cannot have a Send with a deletion date that far into the future. Adjust the Deletion Date to a value less than 31 days from now and try again." - ); + err!(crate::i18n::send_deletion_date_too_far(&headers.locale)); } // When updating a file Send, we receive nulls in the File field, as it's immutable, @@ -511,7 +516,7 @@ async fn update_send_from_data( d.as_object_mut().and_then(|d| d.remove("response")); serde_json::to_string(&d)? } else { - err!("Send data not provided"); + err!(crate::i18n::send_data_not_provided(&headers.locale)); }; send.data = data_str; } @@ -543,7 +548,7 @@ async fn update_send_from_data( #[delete("/sends/")] async fn delete_send(send_id: SendId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { let Some(send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await else { - err!("Send not found", "Invalid send uuid, or does not belong to user") + err!(crate::i18n::send_not_found(&headers.locale), crate::i18n::send_invalid_uuid_or_not_owned(&headers.locale)) }; send.delete(&conn).await?; @@ -564,7 +569,7 @@ async fn put_remove_password(send_id: SendId, headers: Headers, conn: DbConn, nt enforce_disable_send_policy(&headers, &conn).await?; let Some(mut send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await else { - err!("Send not found", "Invalid send uuid, or does not belong to user") + err!(crate::i18n::send_not_found(&headers.locale), crate::i18n::send_invalid_uuid_or_not_owned(&headers.locale)) }; send.set_password(None); diff --git a/src/api/core/two_factor/authenticator.rs b/src/api/core/two_factor/authenticator.rs index 55984443..47b16516 100644 --- a/src/api/core/two_factor/authenticator.rs +++ b/src/api/core/two_factor/authenticator.rs @@ -62,11 +62,11 @@ async fn activate_authenticator(data: Json, headers: He let decoded_key: Vec = if let Ok(decoded) = BASE32.decode(key.as_bytes()) { decoded } else { - err!("Invalid totp secret") + err!(crate::i18n::two_factor_invalid_totp_secret(&headers.locale)) }; if decoded_key.len() != 20 { - err!("Invalid key length") + err!(crate::i18n::two_factor_invalid_key_length(&headers.locale)) } // Validate the token provided with the key, and save new twofactor @@ -97,7 +97,7 @@ pub async fn validate_totp_code_str( conn: &DbConn, ) -> EmptyResult { if !totp_code.chars().all(char::is_numeric) { - err!("TOTP code is not a number"); + err!(crate::i18n::two_factor_totp_code_not_number(&CONFIG.default_locale())); } validate_totp_code(user_id, totp_code, secret, ip, conn).await @@ -113,7 +113,7 @@ pub async fn validate_totp_code( use totp_lite::{Sha1, totp_custom}; let Ok(decoded_secret) = BASE32.decode(secret.as_bytes()) else { - err!("Invalid TOTP secret") + err!(crate::i18n::two_factor_invalid_totp_secret(&CONFIG.default_locale())) }; let mut twofactor = match TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn).await { @@ -188,7 +188,7 @@ async fn disable_authenticator(data: Json, headers: He twofactor.delete(&conn).await?; log_user_event(EventType::UserDisabled2fa, &user.uuid, headers.device.atype, &headers.ip.ip, &conn).await; } else { - err!(format!("TOTP key for user {} does not match recorded value, cannot deactivate", &user.email)); + err!(crate::i18n::two_factor_totp_key_mismatch_cannot_deactivate(&headers.locale), user.email.clone()); } } diff --git a/src/api/core/two_factor/duo.rs b/src/api/core/two_factor/duo.rs index 23116b2c..d9906156 100644 --- a/src/api/core/two_factor/duo.rs +++ b/src/api/core/two_factor/duo.rs @@ -2,6 +2,7 @@ use chrono::Utc; use rocket::{Route, serde::json::Json}; use crate::{ + CONFIG, api::{ ApiResult, EmptyResult, JsonResult, PasswordOrOtpData, core::log_user_event, @@ -114,7 +115,9 @@ async fn activate_duo(data: Json, headers: Headers, conn: DbConn) let (data, data_str) = if check_duo_fields_custom(&data) { let data_req: DuoData = data.into(); let data_str = serde_json::to_string(&data_req)?; - duo_api_request("GET", "/auth/v2/check", "", &data_req).await.map_res("Failed to validate Duo credentials")?; + duo_api_request("GET", "/auth/v2/check", "", &data_req) + .await + .map_res(crate::i18n::two_factor_failed_validate_duo_credentials(&headers.locale))?; (data_req.obscure(), data_str) } else { (DuoData::secret(), String::new()) @@ -220,7 +223,7 @@ pub(crate) async fn get_duo_keys_email(email: &str, conn: &DbConn) -> ApiResult< Some(u) => get_user_duo_data(&u.uuid, conn).await.data(), _ => DuoData::global(), } - .map_res("Can't fetch Duo Keys")?; + .map_res(crate::i18n::two_factor_cant_fetch_duo_keys(&CONFIG.default_locale()))?; Ok((data.ik, data.sk, data.host)) } diff --git a/src/api/core/two_factor/duo_oidc.rs b/src/api/core/two_factor/duo_oidc.rs index e5e1df0f..c70a3b36 100644 --- a/src/api/core/two_factor/duo_oidc.rs +++ b/src/api/core/two_factor/duo_oidc.rs @@ -140,7 +140,7 @@ impl DuoClient { &EncodingKey::from_secret(self.client_secret.as_bytes()), ) { Ok(token) => Ok(token), - Err(e) => err!(format!("Error encoding Duo JWT: {e:?}")), + Err(e) => err!(crate::i18n::two_factor_duo_error_encoding_jwt(&CONFIG.default_locale()), format!("{e:?}")), } } @@ -168,12 +168,17 @@ impl DuoClient { .await { Ok(r) => r, - Err(e) => err!(format!("Error requesting Duo health check: {e:?}")), + Err(e) => err!( + crate::i18n::two_factor_duo_error_requesting_health_check(&CONFIG.default_locale()), + format!("{e:?}") + ), }; let response: HealthCheckResponse = match res.json::().await { Ok(r) => r, - Err(e) => err!(format!("Duo health check response decode error: {e:?}")), + Err(e) => { + err!(crate::i18n::two_factor_duo_health_check_decode_error(&CONFIG.default_locale()), format!("{e:?}")) + } }; let health_stat: String = match response { @@ -183,11 +188,14 @@ impl DuoClient { HealthCheckResponse::HealthFail { message, message_detail, - } => err!(format!("Duo health check FAIL response, msg: {message}, detail: {message_detail}")), + } => err!( + crate::i18n::two_factor_duo_health_check_fail_response(&CONFIG.default_locale()), + format!("msg={message}, detail={message_detail}") + ), }; if health_stat != "OK" { - err!(format!("Duo health check failed, got OK-like body with stat {health_stat}")); + err!(crate::i18n::two_factor_duo_health_check_failed_stat(&CONFIG.default_locale()), health_stat); } Ok(()) @@ -217,7 +225,10 @@ impl DuoClient { let authz_endpoint = format!("https://{}/oauth/v1/authorize", self.api_host); let mut auth_url = match Url::parse(authz_endpoint.as_str()) { Ok(url) => url, - Err(e) => err!(format!("Error parsing Duo authorization URL: {e:?}")), + Err(e) => err!( + crate::i18n::two_factor_duo_error_parsing_authorization_url(&CONFIG.default_locale()), + format!("{e:?}") + ), }; { @@ -241,7 +252,7 @@ impl DuoClient { nonce: &str, ) -> Result<(), Error> { if duo_code.is_empty() { - err!("Empty Duo authorization code") + err!(crate::i18n::two_factor_empty_duo_authorization_code(&CONFIG.default_locale())) } let token_url = format!("https://{}/oauth/v1/token", self.api_host); @@ -271,17 +282,22 @@ impl DuoClient { .await { Ok(r) => r, - Err(e) => err!(format!("Error exchanging Duo code: {e:?}")), + Err(e) => { + err!(crate::i18n::two_factor_duo_error_exchanging_code(&CONFIG.default_locale()), format!("{e:?}")) + } }; let status_code = res.status(); if status_code != StatusCode::OK { - err!(format!("Failure response from Duo: {status_code}")) + err!(crate::i18n::two_factor_duo_failure_response(&CONFIG.default_locale()), status_code.to_string()) } let response: IdTokenResponse = match res.json::().await { Ok(r) => r, - Err(e) => err!(format!("Error decoding ID token response: {e:?}")), + Err(e) => err!( + crate::i18n::two_factor_duo_error_decoding_id_token_response(&CONFIG.default_locale()), + format!("{e:?}") + ), }; let mut validation = Validation::new(DUO_RESP_SIGNATURE_ALG); @@ -295,14 +311,14 @@ impl DuoClient { &validation, ) { Ok(c) => c, - Err(e) => err!(format!("Failed to decode Duo token {e:?}")), + Err(e) => err!(crate::i18n::two_factor_duo_failed_decode_token(&CONFIG.default_locale()), format!("{e:?}")), }; let matching_nonces = crypto::ct_eq(nonce, &token_data.claims.nonce); let matching_usernames = crypto::ct_eq(duo_username, &token_data.claims.preferred_username); if !(matching_nonces && matching_usernames) { - err!("Error validating Duo authorization, nonce or username mismatch.") + err!(crate::i18n::two_factor_duo_validation_mismatch(&CONFIG.default_locale())) } Ok(()) @@ -357,13 +373,19 @@ fn make_callback_url(client_name: &str) -> Result { // Get the location of this application as defined in the config. let base = match Url::parse(&format!("{}/", CONFIG.domain())) { Ok(url) => url, - Err(e) => err!(format!("Error parsing configured domain URL (check your domain configuration): {e:?}")), + Err(e) => err!( + crate::i18n::two_factor_duo_error_parsing_configured_domain_url(&CONFIG.default_locale()), + format!("{e:?}") + ), }; // Add the client redirect bridge location let mut callback = match base.join(DUO_REDIRECT_LOCATION) { Ok(url) => url, - Err(e) => err!(format!("Error constructing Duo redirect URL (check your domain configuration): {e:?}")), + Err(e) => err!( + crate::i18n::two_factor_duo_error_constructing_redirect_url(&CONFIG.default_locale()), + format!("{e:?}") + ), }; // Add the 'client' string with the authenticating device type. The callback connector uses this @@ -408,7 +430,9 @@ pub async fn get_duo_auth_url( match TwoFactorDuoContext::save(state.as_str(), email, nonce.as_str(), CTX_VALIDITY_SECS, conn).await { Ok(()) => client.make_authz_req_url(email, state, hash), - Err(e) => err!(format!("Error saving Duo authentication context: {e:?}")), + Err(e) => { + err!(crate::i18n::two_factor_duo_error_saving_auth_context(&CONFIG.default_locale()), format!("{e:?}")) + } } } diff --git a/src/api/core/two_factor/email.rs b/src/api/core/two_factor/email.rs index 66f2a89e..e2da5337 100644 --- a/src/api/core/two_factor/email.rs +++ b/src/api/core/two_factor/email.rs @@ -47,7 +47,7 @@ async fn send_email_login(data: Json, client_headers: Client let data: SendEmailLoginData = data.into_inner(); if !CONFIG._enable_email_2fa() { - err!("Email 2FA is disabled") + err!(crate::i18n::two_factor_email_disabled(&client_headers.locale)) } // Ratelimit the login @@ -85,17 +85,23 @@ async fn send_email_login(data: Json, client_headers: Client } } else if let Some(auth_request_id) = auth_request_id { let Some(auth_request) = AuthRequest::find_by_uuid(auth_request_id, &conn).await else { - err!("AuthRequest doesn't exist", "User not found") + err!( + crate::i18n::two_factor_auth_request_not_found(&client_headers.locale), + crate::i18n::two_factor_user_not_found(&client_headers.locale) + ) }; let Some(code) = &data.auth_request_access_code else { - err!("no auth request access code") + err!(crate::i18n::two_factor_no_auth_request_access_code(&client_headers.locale)) }; if auth_request.device_type != client_headers.device_type || auth_request.request_ip != client_headers.ip.ip.to_string() || !auth_request.check_access_code(code) { - err!("AuthRequest doesn't exist", "Invalid device, IP or code") + err!( + crate::i18n::two_factor_auth_request_not_found(&client_headers.locale), + crate::i18n::two_factor_invalid_device_ip_or_code(&client_headers.locale) + ) } } else if let Some(device_identifier) = &data.device_identifier { // iOS/Android SSO logins send the email and device id but no password hash, @@ -112,13 +118,13 @@ async fn send_email_login(data: Json, client_headers: Client device_identifier.to_string().escape_debug() ); } else { - err!("No password hash has been submitted.") + err!(crate::i18n::two_factor_no_password_hash_submitted(&client_headers.locale)) } user } else { let Some(device_identifier) = &data.device_identifier else { - err!("No device identifier has been submitted.") + err!(crate::i18n::two_factor_no_device_identifier_submitted(&client_headers.locale)) }; // SSO login only sends device id, so we get the user by the most recently used device let Some(user) = User::find_by_device_for_email2fa(device_identifier, &conn).await else { @@ -131,13 +137,16 @@ async fn send_email_login(data: Json, client_headers: Client user }; - send_token(&user.uuid, &conn).await + send_token(&user.uuid, &conn, Some(&client_headers.locale)).await } /// Generate the token, save the data for later verification and send email to user -pub async fn send_token(user_id: &UserId, conn: &DbConn) -> EmptyResult { - let mut twofactor = - TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn).await.map_res("Two factor not found")?; +pub async fn send_token(user_id: &UserId, conn: &DbConn, locale: Option<&str>) -> EmptyResult { + let default_locale = CONFIG.default_locale(); + let locale = locale.unwrap_or(default_locale.as_str()); + let mut twofactor = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn) + .await + .map_res(crate::i18n::two_factor_not_found(locale))?; let generated_token = crypto::generate_email_token(CONFIG.email_token_size()); @@ -146,7 +155,12 @@ pub async fn send_token(user_id: &UserId, conn: &DbConn) -> EmptyResult { twofactor.data = twofactor_data.to_json(); twofactor.save(conn).await?; - mail::send_token(&twofactor_data.email, &twofactor_data.last_token.map_res("Token is empty")?).await?; + mail::send_token_for_locale( + &twofactor_data.email, + &twofactor_data.last_token.map_res(crate::i18n::two_factor_token_empty(locale))?, + Some(locale), + ) + .await?; Ok(()) } @@ -193,7 +207,7 @@ async fn send_email(data: Json, headers: Headers, conn: DbConn) - two_factor::validate_email(&data.user_verification_token, &user.uuid, data.email.clone(), false)?; if !CONFIG._enable_email_2fa() { - err!("Email 2FA is disabled") + err!(crate::i18n::two_factor_email_disabled(&headers.locale)) } if let Some(tf) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Email, &conn).await { @@ -208,7 +222,12 @@ async fn send_email(data: Json, headers: Headers, conn: DbConn) - TwoFactor::new(user.uuid.clone(), TwoFactorType::EmailVerificationChallenge, twofactor_data.to_json()); twofactor.save(&conn).await?; - mail::send_token(&twofactor_data.email, &twofactor_data.last_token.map_res("Token is empty")?).await?; + mail::send_token_for_locale( + &twofactor_data.email, + &twofactor_data.last_token.map_res(crate::i18n::two_factor_token_empty(&headers.locale))?, + Some(&headers.locale), + ) + .await?; Ok(Json(json!({}))) } @@ -231,16 +250,16 @@ async fn email(data: Json, headers: Headers, conn: DbConn) -> JsonRes let mut twofactor = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::EmailVerificationChallenge, &conn) .await - .map_res("Two factor not found")?; + .map_res(crate::i18n::two_factor_not_found(&headers.locale))?; let mut email_data = EmailTokenData::from_json(&twofactor.data)?; let Some(issued_token) = &email_data.last_token else { - err!("No token available") + err!(crate::i18n::two_factor_no_token_available(&headers.locale)) }; if !crypto::ct_eq(issued_token, data.token) { - err!("Token is invalid") + err!(crate::i18n::two_factor_token_invalid(&headers.locale)) } email_data.reset_token(); @@ -281,8 +300,10 @@ pub async fn validate_email_code_str( conn: &DbConn, ) -> EmptyResult { let mut email_data = EmailTokenData::from_json(data)?; - let mut twofactor = - TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn).await.map_res("Two factor not found")?; + let locale = CONFIG.default_locale(); + let mut twofactor = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn) + .await + .map_res(crate::i18n::two_factor_not_found(&locale))?; let Some(issued_token) = &email_data.last_token else { err!( format!("No token available! IP: {ip}"), @@ -373,14 +394,14 @@ impl EmailTokenData { if let Ok(x) = res { Ok(x) } else { - err!("Could not decode EmailTokenData from string") + err!(crate::i18n::two_factor_decode_email_token_data_failed(&CONFIG.default_locale())) } } } pub async fn activate_email_2fa(user: &User, conn: &DbConn) -> EmptyResult { if user.verified_at.is_none() { - err!("Auto-enabling of email 2FA failed because the users email address has not been verified!"); + err!(crate::i18n::two_factor_auto_enable_email_requires_verified(&CONFIG.default_locale())); } // The token is set when the first code is sent let twofactor_data = EmailTokenData::new(user.email.clone(), None); @@ -412,7 +433,7 @@ pub async fn find_and_activate_email_2fa(user_id: &UserId, conn: &DbConn) -> Emp if let Some(user) = User::find_by_uuid(user_id, conn).await { activate_email_2fa(&user, conn).await } else { - err!("User not found!"); + err!(crate::i18n::two_factor_user_not_found_exclam(&CONFIG.default_locale())); } } diff --git a/src/api/core/two_factor/mod.rs b/src/api/core/two_factor/mod.rs index db533b50..6204a25f 100644 --- a/src/api/core/two_factor/mod.rs +++ b/src/api/core/two_factor/mod.rs @@ -144,7 +144,7 @@ pub async fn enforce_2fa_policy( if member.atype < MembershipType::Admin { if CONFIG.mail_enabled() { let org = Organization::find_by_uuid(&member.org_uuid, conn).await.unwrap(); - mail::send_2fa_removed_from_org(&user.email, &org.name).await?; + mail::send_2fa_removed_from_org_for_locale(&user.email, &org.name, user.locale.as_deref()).await?; } let mut member = member; member.revoke(); @@ -179,7 +179,7 @@ pub async fn enforce_2fa_policy_for_org( if member.atype < MembershipType::Admin && TwoFactor::find_by_user(&member.user_uuid, conn).await.is_empty() { if CONFIG.mail_enabled() { let user = User::find_by_uuid(&member.user_uuid, conn).await.unwrap(); - mail::send_2fa_removed_from_org(&user.email, &org.name).await?; + mail::send_2fa_removed_from_org_for_locale(&user.email, &org.name, user.locale.as_deref()).await?; } let mut member = member; member.revoke(); @@ -225,12 +225,13 @@ pub async fn send_incomplete_2fa_notifications(pool: DbPool) { "User {} did not complete a 2FA login within the configured time limit. IP: {}", user.email, login.ip_address ); - match mail::send_incomplete_2fa_login( + match mail::send_incomplete_2fa_login_for_locale( &user.email, &login.ip_address, &login.login_time, &login.device_name, &DeviceType::from_i32(login.device_type).to_string(), + user.locale.as_deref(), ) .await { diff --git a/src/api/core/two_factor/protected_actions.rs b/src/api/core/two_factor/protected_actions.rs index bf757d14..6ffff0dc 100644 --- a/src/api/core/two_factor/protected_actions.rs +++ b/src/api/core/two_factor/protected_actions.rs @@ -48,7 +48,7 @@ impl ProtectedActionData { if let Ok(x) = res { Ok(x) } else { - err!("Could not decode ProtectedActionData from string") + err!(crate::i18n::two_factor_decode_protected_action_data_failed(&CONFIG.default_locale())) } } @@ -77,7 +77,10 @@ async fn request_otp(headers: Headers, conn: DbConn) -> EmptyResult { let elapsed = pa_data.time_since_sent().num_seconds(); let delay = 30; if elapsed < delay { - err!(format!("Please wait {} seconds before requesting another code.", (delay - elapsed))); + let wait_seconds = (delay - elapsed).to_string(); + let message = + crate::i18n::two_factor_request_otp_wait_seconds(&headers.locale).replacen("{}", &wait_seconds, 1); + err!(message); } pa.delete(&conn).await?; @@ -90,7 +93,7 @@ async fn request_otp(headers: Headers, conn: DbConn) -> EmptyResult { let twofactor = TwoFactor::new(user.uuid, TwoFactorType::ProtectedActions, pa_data.to_json()); twofactor.save(&conn).await?; - mail::send_protected_action_token(&user.email, &pa_data.token).await?; + mail::send_protected_action_token_for_locale(&user.email, &pa_data.token, Some(&headers.locale)).await?; Ok(()) } @@ -124,22 +127,23 @@ pub async fn validate_protected_action_otp( delete_if_valid: bool, conn: &DbConn, ) -> EmptyResult { + let locale = CONFIG.default_locale(); let mut pa = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::ProtectedActions, conn) .await - .map_res("Protected action token not found, try sending the code again or restart the process")?; + .map_res(crate::i18n::two_factor_protected_action_token_not_found(&locale))?; let mut pa_data = ProtectedActionData::from_json(&pa.data)?; // Fail after x attempts if the token has been used too many times. // Don't delete it, as we use it to keep track of attempts. if pa_data.attempts >= u64::from(CONFIG.email_attempts_limit()) { - err!("Token has expired") + err!(crate::i18n::two_factor_token_expired(&CONFIG.default_locale())) } // Check if the token has expired (Using the email 2fa expiration time) let max_time = i64::from(CONFIG.email_expiration_time()); if pa_data.time_since_sent().num_seconds() > max_time { pa.delete(conn).await?; - err!("Token has expired") + err!(crate::i18n::two_factor_token_expired(&CONFIG.default_locale())) } if !crypto::ct_eq(&pa_data.token, otp) { @@ -147,7 +151,7 @@ pub async fn validate_protected_action_otp( pa.data = pa_data.to_json(); pa.save(conn).await?; - err!("Token is invalid") + err!(crate::i18n::two_factor_token_invalid(&CONFIG.default_locale())) } if delete_if_valid { diff --git a/src/api/core/two_factor/webauthn.rs b/src/api/core/two_factor/webauthn.rs index 7eab5546..f6f23857 100644 --- a/src/api/core/two_factor/webauthn.rs +++ b/src/api/core/two_factor/webauthn.rs @@ -119,7 +119,7 @@ impl WebauthnRegistration { #[post("/two-factor/get-webauthn", data = "")] async fn get_webauthn(data: Json, headers: Headers, conn: DbConn) -> JsonResult { if !CONFIG.is_webauthn_2fa_supported() { - err!("Configured `DOMAIN` is not compatible with Webauthn") + err!(crate::i18n::two_factor_webauthn_domain_incompatible(&headers.locale)) } let data: PasswordOrOtpData = data.into_inner(); @@ -282,7 +282,7 @@ async fn activate_webauthn(data: Json, headers: Headers, con tf.delete(&conn).await?; state } else { - err!("Can't recover challenge") + err!(crate::i18n::two_factor_cannot_recover_challenge(&headers.locale)) }; // Verify the credentials with the saved state @@ -344,7 +344,7 @@ async fn inner_delete_webauthns( let user = headers.user; let Some(mut tf) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Webauthn, conn).await else { - err!("Webauthn data not found!") + err!(crate::i18n::two_factor_webauthn_data_not_found(&headers.locale)) }; let mut keys: Vec = serde_json::from_str(&tf.data)?; @@ -365,7 +365,7 @@ async fn inner_delete_webauthns( }); if removed.is_empty() { - err!("Webauthn entry not found") + err!(crate::i18n::two_factor_webauthn_entry_not_found(&headers.locale)) } if keys.is_empty() { @@ -380,7 +380,7 @@ async fn inner_delete_webauthns( // If entry is migrated from u2f, delete the u2f entry as well if migrated && let Some(mut u2f) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::U2f, conn).await { let Ok(mut data) = serde_json::from_str::>(&u2f.data) else { - err!("Error parsing U2F data") + err!(crate::i18n::two_factor_error_parsing_u2f_data(&headers.locale)) }; data.retain(|old| !removed.contains(&old.reg.key_handle)); @@ -420,7 +420,7 @@ pub async fn generate_webauthn_login(user_id: &UserId, conn: &DbConn) -> JsonRes get_webauthn_registrations(user_id, conn).await?.1.into_iter().map(|r| r.credential).collect(); if creds.is_empty() { - err!("No Webauthn devices registered") + err!(crate::i18n::two_factor_no_webauthn_devices_registered(&CONFIG.default_locale())) } // Generate a challenge based on the credentials diff --git a/src/api/core/two_factor/yubikey.rs b/src/api/core/two_factor/yubikey.rs index 17c4e9a0..cac54a7f 100644 --- a/src/api/core/two_factor/yubikey.rs +++ b/src/api/core/two_factor/yubikey.rs @@ -92,17 +92,18 @@ fn jsonify_yubikeys(yubikeys: Vec) -> Value { fn get_yubico_credentials() -> Result<(String, String), Error> { if !CONFIG._enable_yubico() { - err!("Yubico support is disabled"); + err!(crate::i18n::two_factor_yubico_support_disabled(&CONFIG.default_locale())); } if let (Some(id), Some(secret)) = (CONFIG.yubico_client_id(), CONFIG.yubico_secret_key()) { Ok((id, secret)) } else { - err!("`YUBICO_CLIENT_ID` or `YUBICO_SECRET_KEY` environment variable is not set. Yubikey OTP Disabled") + err!(crate::i18n::two_factor_yubico_credentials_not_set(&CONFIG.default_locale())) } } async fn verify_yubikey_otp(otp: String) -> EmptyResult { + let locale = CONFIG.default_locale(); let (yubico_id, yubico_secret) = get_yubico_credentials()?; let mut config = Config::default().set_client_id(yubico_id).set_key(yubico_secret)?; @@ -113,7 +114,7 @@ async fn verify_yubikey_otp(otp: String) -> EmptyResult { let client = HttpClientTransport::new()?; let verifier = Verifier::with_client(config, client)?; - verifier.verify(otp).await.map_res("Failed to verify OTP") + verifier.verify(otp).await.map_res(crate::i18n::two_factor_failed_verify_otp(&locale)) } #[post("/two-factor/get-yubikey", data = "")] @@ -154,7 +155,7 @@ async fn activate_yubikey(data: Json, headers: Headers, conn: if yubikeys.is_empty() { // Return an error to prevent saving empty keys which would cause users not being able to login anymore. // To remove all keys users should click the `Deactivate all keys` button - err!("A key is required."); + err!(crate::i18n::two_factor_key_required(&headers.locale)); } // Check if we already have some data @@ -174,7 +175,9 @@ async fn activate_yubikey(data: Json, headers: Headers, conn: continue; } - verify_yubikey_otp(yubikey.to_owned()).await.map_res("Invalid Yubikey OTP provided")?; + verify_yubikey_otp(yubikey.to_owned()) + .await + .map_res(crate::i18n::two_factor_invalid_yubikey_otp_provided(&headers.locale))?; } let yubikey_ids: Vec = yubikeys.into_iter().filter_map(|x| x.get(..12).map(str::to_owned)).collect(); @@ -221,18 +224,20 @@ async fn delete_yubikeys(data: Json, headers: Headers, co pub async fn validate_yubikey_login(response: &str, twofactor_data: &str) -> EmptyResult { if response.len() != 44 { - err!("Invalid Yubikey OTP length"); + err!(crate::i18n::two_factor_invalid_yubikey_otp_length(&CONFIG.default_locale())); } let yubikey_metadata: YubikeyMetadata = serde_json::from_str(twofactor_data).expect("Can't parse Yubikey Metadata"); let Some(response_id) = response.get(..12) else { - err!("Invalid Yubikey OTP"); + err!(crate::i18n::two_factor_invalid_yubikey_otp(&CONFIG.default_locale())); }; if !yubikey_metadata.keys.contains(&response_id.to_owned()) { - err!("Given Yubikey is not registered"); + err!(crate::i18n::two_factor_given_yubikey_not_registered(&CONFIG.default_locale())); } - verify_yubikey_otp(response.to_owned()).await.map_res("Failed to verify Yubikey against OTP server")?; + verify_yubikey_otp(response.to_owned()) + .await + .map_res(crate::i18n::two_factor_failed_verify_yubikey_against_otp_server(&CONFIG.default_locale()))?; Ok(()) } diff --git a/src/api/identity.rs b/src/api/identity.rs index 146cec4c..1c45c9cc 100644 --- a/src/api/identity.rs +++ b/src/api/identity.rs @@ -24,7 +24,7 @@ use crate::{ push::register_push_device, }, auth, - auth::{AuthMethod, ClientHeaders, ClientIp, Secure, generate_organization_api_key_login_claims}, + auth::{AuthMethod, ClientHeaders, ClientIp, RequestLocale, Secure, generate_organization_api_key_login_claims}, crypto, db::{ DbConn, @@ -66,7 +66,9 @@ async fn login(data: Form, client_header: ClientHeaders, conn: DbCo check_is_some(data.refresh_token.as_ref(), "refresh_token cannot be blank")?; refresh_login(data, &conn, &client_header.ip).await } - "password" if CONFIG.sso_enabled() && CONFIG.sso_only() => err!("SSO sign-in is required"), + "password" if CONFIG.sso_enabled() && CONFIG.sso_only() => { + err!(crate::i18n::identity_sso_required(&client_header.locale)) + } "password" => { check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; check_is_some(data.password.as_ref(), "password cannot be blank")?; @@ -77,14 +79,14 @@ async fn login(data: Form, client_header: ClientHeaders, conn: DbCo check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?; check_is_some(data.device_type.as_ref(), "device_type cannot be blank")?; - password_login(data, &mut user_id, &conn, &client_header.ip).await + password_login(data, &mut user_id, &conn, &client_header.ip, &client_header.locale).await } "client_credentials" => { check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; check_is_some(data.client_secret.as_ref(), "client_secret cannot be blank")?; check_is_some(data.scope.as_ref(), "scope cannot be blank")?; - api_key_login(data, &mut user_id, &conn, &client_header.ip).await + api_key_login(data, &mut user_id, &conn, &client_header.ip, &client_header.locale).await } "authorization_code" if CONFIG.sso_enabled() => { check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; @@ -97,7 +99,7 @@ async fn login(data: Form, client_header: ClientHeaders, conn: DbCo sso_login(data, &mut user_id, &conn, &client_header.ip).await } - "authorization_code" => err!("SSO sign-in is not available"), + "authorization_code" => err!(crate::i18n::identity_sso_unavailable(&client_header.locale)), "send_access" => { crate::ratelimit::check_limit_unauthenticated(&client_header.ip.ip)?; check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; @@ -112,7 +114,7 @@ async fn login(data: Form, client_header: ClientHeaders, conn: DbCo .await?; Ok(Json(tokens.to_json())) } - t => err!("Invalid type", t), + t => err!(crate::i18n::identity_invalid_type(&client_header.locale), t), }; if let Some(user_id) = user_id { @@ -145,7 +147,7 @@ async fn refresh_login(data: ConnectData, conn: &DbConn, ip: &ClientIp) -> JsonR // https://github.com/bitwarden/clients/blob/2ee158e720a5e7dbe3641caf80b569e97a1dd91b/libs/common/src/services/api.service.ts#L1786-L1797 let Some(refresh_token) = data.refresh_token else { - err_json!(json!({"error": "invalid_grant"}), "Missing refresh_token") + err_json!(json!({"error": "invalid_grant"}), crate::i18n::auth_invalid_refresh_token(&CONFIG.default_locale())) }; // --- @@ -350,7 +352,7 @@ async fn sso_login(data: ConnectData, user_id: &mut Option, conn: &DbCon if user.email != user_infos.email { if CONFIG.mail_enabled() { - mail::send_sso_change_email(&user_infos.email).await?; + mail::send_sso_change_email_for_locale(&user_infos.email, user.locale.as_deref()).await?; } info!("User {} email changed in SSO provider from {} to {}", user.uuid, user.email, user_infos.email); } @@ -368,7 +370,13 @@ async fn sso_login(data: ConnectData, user_id: &mut Option, conn: &DbCon authenticated_response(&user, &mut device, auth_tokens, twofactor_token, conn, ip).await } -async fn password_login(data: ConnectData, user_id: &mut Option, conn: &DbConn, ip: &ClientIp) -> JsonResult { +async fn password_login( + data: ConnectData, + user_id: &mut Option, + conn: &DbConn, + ip: &ClientIp, + locale: &str, +) -> JsonResult { // Validate scope AuthMethod::Password.check_scope(data.scope.as_ref())?; @@ -379,7 +387,10 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & let username = data.username.as_ref().unwrap().trim(); let log_username = username.escape_debug(); let Some(mut user) = User::find_by_mail(username, conn).await else { - err!("Username or password is incorrect. Try again", format!("IP: {}. Username: {log_username}.", ip.ip)) + err!( + crate::i18n::auth_invalid_username_or_password(locale), + format!("IP: {}. Username: {log_username}.", ip.ip) + ) }; // Set the user_id here to be passed back used for event logging. @@ -410,7 +421,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & || !auth_request.check_access_code(password) { err!( - "Username or access code is incorrect. Try again", + crate::i18n::auth_invalid_username_or_access_code(locale), format!("IP: {}. Username: {log_username}.", ip.ip), ErrorEvent { event: EventType::UserFailedLogIn, @@ -419,7 +430,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & } } else if !user.check_valid_password(password) { err!( - "Username or password is incorrect. Try again", + crate::i18n::auth_invalid_username_or_password(locale), format!("IP: {}. Username: {log_username}.", ip.ip), ErrorEvent { event: EventType::UserFailedLogIn, @@ -430,7 +441,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & // Check if the user is disabled if !user.enabled { err!( - "This user has been disabled", + crate::i18n::auth_user_disabled(locale), format!("IP: {}. Username: {log_username}.", ip.ip), ErrorEvent { event: EventType::UserFailedLogIn @@ -461,7 +472,10 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & error!("Error updating user: {e:#?}"); } - if let Err(e) = mail::send_verify_email(&user.email, &user.uuid).await { + let preferred_locale = user.locale.as_deref().unwrap_or(locale); + if let Err(e) = + mail::send_verify_email_for_locale(&user.email, &user.uuid, Some(preferred_locale)).await + { error!("Error auto-sending email verification email: {e:#?}"); } } @@ -469,7 +483,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & // We still want the login to fail until they actually verified the email address err!( - "Please verify your email before trying again.", + crate::i18n::auth_verify_email_before_login(locale), format!("IP: {}. Username: {log_username}.", ip.ip), ErrorEvent { event: EventType::UserFailedLogIn @@ -486,7 +500,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option, conn: & && !AuthRequest::set_authentication_date(auth_request_id, conn).await? { err!( - "Username or access code is incorrect. Try again", + crate::i18n::auth_invalid_username_or_access_code(locale), format!("IP: {}. Username: {log_username}.", ip.ip), ErrorEvent { event: EventType::UserFailedLogIn, @@ -509,7 +523,15 @@ async fn authenticated_response( ) -> JsonResult { if CONFIG.mail_enabled() && device.is_new() { let now = Utc::now().naive_utc(); - if let Err(e) = mail::send_new_device_logged_in(&user.email, &ip.ip.to_string(), &now, device).await { + if let Err(e) = mail::send_new_device_logged_in_for_locale( + &user.email, + &ip.ip.to_string(), + &now, + device, + user.locale.as_deref(), + ) + .await + { error!("Error sending new device email: {e:#?}"); if CONFIG.require_device_email() { @@ -598,7 +620,13 @@ async fn authenticated_response( Ok(Json(result)) } -async fn api_key_login(data: ConnectData, user_id: &mut Option, conn: &DbConn, ip: &ClientIp) -> JsonResult { +async fn api_key_login( + data: ConnectData, + user_id: &mut Option, + conn: &DbConn, + ip: &ClientIp, + locale: &str, +) -> JsonResult { // Ratelimit the login crate::ratelimit::check_limit_login(&ip.ip)?; @@ -610,10 +638,12 @@ async fn api_key_login(data: ConnectData, user_id: &mut Option, conn: &D check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?; check_is_some(data.device_type.as_ref(), "device_type cannot be blank")?; - user_api_key_login(data, user_id, conn, ip).await + user_api_key_login(data, user_id, conn, ip, locale).await } - Some(scope) if scope == &AuthMethod::OrgApiKey.scope() => organization_api_key_login(data, conn, ip).await, - _ => err!("Scope not supported"), + Some(scope) if scope == &AuthMethod::OrgApiKey.scope() => { + organization_api_key_login(data, conn, ip, locale).await + } + _ => err!(crate::i18n::auth_scope_not_supported(locale)), } } @@ -622,15 +652,16 @@ async fn user_api_key_login( user_id: &mut Option, conn: &DbConn, ip: &ClientIp, + locale: &str, ) -> JsonResult { // Get the user via the client_id let client_id = data.client_id.as_ref().unwrap(); let Some(client_user_id) = client_id.strip_prefix("user.") else { - err!("Malformed client_id", format!("IP: {}.", ip.ip)) + err!(crate::i18n::auth_malformed_client_id(locale), format!("IP: {}.", ip.ip)) }; let client_user_id: UserId = client_user_id.into(); - let Some(user) = User::find_by_uuid(&client_user_id, conn).await else { - err!("Invalid client_id", format!("IP: {}.", ip.ip)) + let Some(mut user) = User::find_by_uuid(&client_user_id, conn).await else { + err!(crate::i18n::auth_invalid_client_id(locale), format!("IP: {}.", ip.ip)) }; // Set the user_id here to be passed back used for event logging. @@ -651,7 +682,7 @@ async fn user_api_key_login( let client_secret = data.client_secret.as_ref().unwrap(); if !user.check_valid_api_key(client_secret) { err!( - "Incorrect client_secret", + crate::i18n::auth_incorrect_client_secret(locale), format!("IP: {}. Username: {}.", ip.ip, user.email), ErrorEvent { event: EventType::UserFailedLogIn @@ -659,11 +690,27 @@ async fn user_api_key_login( ) } + // Backfill user locale for accounts that predate locale persistence. + if user.locale.is_none() { + user.locale = Some(crate::i18n::normalize_locale(locale)); + if let Err(e) = user.save(conn).await { + error!("Error updating user locale: {e:#?}"); + } + } + let mut device = get_device(&data, conn, &user).await?; if CONFIG.mail_enabled() && device.is_new() { let now = Utc::now().naive_utc(); - if let Err(e) = mail::send_new_device_logged_in(&user.email, &ip.ip.to_string(), &now, &device).await { + if let Err(e) = mail::send_new_device_logged_in_for_locale( + &user.email, + &ip.ip.to_string(), + &now, + &device, + user.locale.as_deref(), + ) + .await + { error!("Error sending new device email: {e:#?}"); if CONFIG.require_device_email() { @@ -748,21 +795,24 @@ async fn user_api_key_login( Ok(Json(result)) } -async fn organization_api_key_login(data: ConnectData, conn: &DbConn, ip: &ClientIp) -> JsonResult { +async fn organization_api_key_login(data: ConnectData, conn: &DbConn, ip: &ClientIp, locale: &str) -> JsonResult { // Get the org via the client_id let client_id = data.client_id.as_ref().unwrap(); let Some(org_id) = client_id.strip_prefix("organization.") else { - err!("Malformed client_id", format!("IP: {}.", ip.ip)) + err!(crate::i18n::auth_malformed_client_id(locale), format!("IP: {}.", ip.ip)) }; let org_id: OrganizationId = org_id.to_owned().into(); let Some(org_api_key) = OrganizationApiKey::find_by_org_uuid(&org_id, conn).await else { - err!("Invalid client_id", format!("IP: {}.", ip.ip)) + err!(crate::i18n::auth_invalid_client_id(locale), format!("IP: {}.", ip.ip)) }; // Check API key. let client_secret = data.client_secret.as_ref().unwrap(); if !org_api_key.check_valid_api_key(client_secret) { - err!("Incorrect client_secret", format!("IP: {}. Organization: {}.", ip.ip, org_api_key.org_uuid)) + err!( + crate::i18n::auth_incorrect_client_secret(locale), + format!("IP: {}. Organization: {}.", ip.ip, org_api_key.org_uuid) + ) } let claim = generate_organization_api_key_login_claims(org_api_key.uuid, org_api_key.org_uuid); @@ -819,8 +869,10 @@ async fn twofactor_auth( (tf.enabled && is_twofactor_provider_usable(&provider_type, Some(&tf.data))).then_some(tf.atype) }) .collect(); + let default_locale = CONFIG.default_locale(); + let locale = user.locale.as_deref().unwrap_or(default_locale.as_str()); if twofactor_ids.is_empty() { - err!("No enabled and usable two factor providers are available for this account") + err!(crate::i18n::auth_no_2fa_providers(locale)) } let selected_id = data.two_factor_provider.unwrap_or(twofactor_ids[0]); // If we aren't given a two factor provider, assume the first one @@ -828,17 +880,23 @@ async fn twofactor_auth( if ![TwoFactorType::Remember as i32, TwoFactorType::RecoveryCode as i32].contains(&selected_id) && !twofactor_ids.contains(&selected_id) { - err_json!(json_err_twofactor(&twofactor_ids, user, data, conn).await?, "Invalid two factor provider") + err_json!( + json_err_twofactor(&twofactor_ids, user, data, conn).await?, + crate::i18n::auth_invalid_twofactor_provider(locale) + ) } // Like upstream, a blank token counts as not provided let Some(twofactor_code) = data.two_factor_token.as_deref().filter(|t| !t.trim().is_empty()) else { - err_json!(json_err_twofactor(&twofactor_ids, user, data, conn).await?, "2FA token not provided") + err_json!( + json_err_twofactor(&twofactor_ids, user, data, conn).await?, + crate::i18n::two_factor_no_token_available(locale) + ) }; let selected_twofactor = twofactors.into_iter().find(|tf| tf.atype == selected_id && tf.enabled); - let selected_data = selected_data(selected_twofactor); + let selected_data = selected_data(selected_twofactor, locale); match TwoFactorType::from_i32(selected_id) { Some(TwoFactorType::Authenticator) => { @@ -887,7 +945,7 @@ async fn twofactor_auth( let recovery_code = twofactor_code.replace(' ', "").trim().to_lowercase(); if !user.check_valid_recovery_code(&recovery_code) { err!( - "Two-step token is invalid. Try again.", + crate::i18n::auth_two_step_token_invalid(locale), ErrorEvent { event: EventType::UserFailedLogIn2fa } @@ -907,8 +965,13 @@ async fn twofactor_auth( log_user_event(EventType::UserRecovered2fa, &user.uuid, device.atype, &ip.ip, conn).await; if CONFIG.mail_enabled() - && let Err(e) = - mail::send_recover_twofactor(&user.email, &ip.ip.to_string(), &Utc::now().naive_utc()).await + && let Err(e) = mail::send_recover_twofactor_for_locale( + &user.email, + &ip.ip.to_string(), + &Utc::now().naive_utc(), + user.locale.as_deref(), + ) + .await { error!("Error sending two-step login recovered email: {e:#?}"); } @@ -918,7 +981,7 @@ async fn twofactor_auth( user.save(conn).await?; } _ => err!( - "Invalid two factor provider", + crate::i18n::auth_invalid_twofactor_provider(locale), ErrorEvent { event: EventType::UserFailedLogIn2fa } @@ -936,8 +999,8 @@ async fn twofactor_auth( Ok(two_factor) } -fn selected_data(tf: Option) -> ApiResult { - tf.map(|t| t.data).map_res("Two factor doesn't exist") +fn selected_data(tf: Option, locale: &str) -> ApiResult { + tf.map(|t| t.data).map_res(crate::i18n::two_factor_not_found(locale)) } async fn json_err_twofactor(providers: &[i32], user: &User, data: &ConnectData, conn: &DbConn) -> ApiResult { @@ -975,7 +1038,9 @@ async fn json_err_twofactor(providers: &[i32], user: &User, data: &ConnectData, Some(tf_type @ TwoFactorType::YubiKey) => { let Some(twofactor) = TwoFactor::find_by_user_and_type(user_id, tf_type, conn).await else { - err!("No YubiKey devices registered") + err!(crate::i18n::auth_no_yubikey_devices( + user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) }; let yubikey_metadata: yubikey::YubikeyMetadata = serde_json::from_str(&twofactor.data)?; @@ -987,7 +1052,9 @@ async fn json_err_twofactor(providers: &[i32], user: &User, data: &ConnectData, Some(tf_type @ TwoFactorType::Email) => { let Some(twofactor) = TwoFactor::find_by_user_and_type(user_id, tf_type, conn).await else { - err!("No twofactor email registered") + err!(crate::i18n::auth_no_twofactor_email( + user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )) }; let email_data = email::EmailTokenData::from_json(&twofactor.data)?; @@ -1059,6 +1126,7 @@ fn accepts_json(accept: Option<&Accept>) -> bool { async fn register_verification_email( data: Json, accept: Option<&Accept>, + locale: RequestLocale, ip: ClientIp, conn: DbConn, ) -> ApiResult { @@ -1070,7 +1138,7 @@ async fn register_verification_email( if !(CONFIG.is_signup_allowed(&data.email) || (!CONFIG.mail_enabled() && Invitation::find_by_mail(&data.email, &conn).await.is_some())) { - err!("Registration not allowed or user already exists") + err!(crate::i18n::accounts_registration_not_allowed_or_exists(&locale.locale)) } let should_send_mail = CONFIG.mail_enabled() && CONFIG.signups_verify(); @@ -1089,7 +1157,7 @@ async fn register_verification_email( let sleep_ms: u64 = rng.random_range(900..=1100); tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await; } else { - mail::send_register_verify_email(&data.email, &token).await?; + mail::send_register_verify_email_for_locale(&data.email, &token, Some(&locale.locale)).await?; } Ok(RegisterVerificationResponse::NoContent(())) @@ -1124,9 +1192,9 @@ async fn register_verification_email_clicked( } #[post("/accounts/register/finish", data = "")] -async fn register_finish(data: Json, ip: ClientIp, conn: DbConn) -> JsonResult { +async fn register_finish(data: Json, locale: RequestLocale, ip: ClientIp, conn: DbConn) -> JsonResult { crate::ratelimit::check_limit_unauthenticated(&ip.ip)?; - register(data, conn).await + register(data, conn, &locale.locale).await } // https://github.com/bitwarden/jslib/blob/master/common/src/models/request/tokenRequest.ts @@ -1201,14 +1269,15 @@ fn check_is_some(value: Option<&T>, msg: &str) -> EmptyResult { } #[get("/sso/prevalidate")] -fn prevalidate() -> JsonResult { +#[allow(clippy::needless_pass_by_value)] +fn prevalidate(locale: RequestLocale) -> JsonResult { if CONFIG.sso_enabled() { let sso_token = sso::encode_ssotoken_claims(); Ok(Json(json!({ "token": sso_token, }))) } else { - err!("SSO sign-in is not available") + err!(crate::i18n::identity_sso_unavailable(&locale.locale)) } } @@ -1256,7 +1325,7 @@ async fn oidcsignin_redirect( let state = sso::decode_state(&base64_state)?; let Some(mut sso_auth) = SsoAuth::find(&state, conn).await else { - err!(format!("Cannot retrieve sso_auth for {}", state.escape_debug())) + err!(crate::i18n::identity_cannot_retrieve_sso_auth(&CONFIG.default_locale()), state.escape_debug().to_string()) }; // Browser-binding check @@ -1265,7 +1334,10 @@ async fn oidcsignin_redirect( let provided_hash = cookie_value.as_deref().map(|v| crypto::sha256_hex(v.as_bytes())); match (sso_auth.binding_hash.as_deref(), provided_hash.as_deref()) { (Some(expected), Some(actual)) if crypto::ct_eq(expected, actual) => {} - _ => err!(format!("SSO session binding mismatch for {}", state.escape_debug())), + _ => err!( + crate::i18n::identity_sso_session_binding_mismatch(&CONFIG.default_locale()), + state.escape_debug().to_string() + ), } cookies .remove(Cookie::build(SSO_BINDING_COOKIE).path(format!("{}/identity/connect/", CONFIG.domain_path())).build()); @@ -1277,7 +1349,10 @@ async fn oidcsignin_redirect( let mut url = match url::Url::parse(&sso_auth.redirect_uri) { Ok(url) => url, - Err(err) => err!(format!("Failed to parse redirect uri ({}): {err}", sso_auth.redirect_uri)), + Err(err) => err!( + crate::i18n::identity_failed_parse_redirect_uri(&CONFIG.default_locale()), + format!("{}: {err}", sso_auth.redirect_uri) + ), }; url.query_pairs_mut() @@ -1317,7 +1392,13 @@ struct AuthorizeData { // The `redirect_uri` will change depending of the client (web, android, ios ..) #[get("/connect/authorize?")] -async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure, conn: DbConn) -> ApiResult { +async fn authorize( + data: AuthorizeData, + cookies: &CookieJar<'_>, + secure: Secure, + locale: RequestLocale, + conn: DbConn, +) -> ApiResult { let AuthorizeData { client_id, redirect_uri, @@ -1328,7 +1409,7 @@ async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure, } = data; if code_challenge_method != "S256" { - err!("Unsupported code challenge method"); + err!(crate::i18n::identity_unsupported_code_challenge_method(&locale.locale)); } // Generate browser-binding token. Stored hashed in DB; raw value handed to the browser as a cookie. diff --git a/src/api/mod.rs b/src/api/mod.rs index 450c2113..17724a11 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -64,13 +64,13 @@ impl PasswordOrOtpData { match (self.master_password_hash.as_deref(), self.otp.as_deref()) { (Some(pw_hash), None) => { if !user.check_valid_password(pw_hash) { - err!("Invalid password"); + err!(crate::i18n::auth_invalid_password(&CONFIG.default_locale())); } } (None, Some(otp)) => { validate_protected_action_otp(otp, &user.uuid, delete_if_valid, conn).await?; } - _ => err!("No validation provided"), + _ => err!(crate::i18n::api_no_validation_provided(&CONFIG.default_locale())), } Ok(()) } diff --git a/src/api/push.rs b/src/api/push.rs index 4da790e4..792d7e6f 100644 --- a/src/api/push.rs +++ b/src/api/push.rs @@ -65,12 +65,12 @@ async fn get_auth_api_token() -> ApiResult { .await { Ok(r) => r, - Err(e) => err!(format!("Error getting push token from bitwarden server: {e}")), + Err(e) => err!(crate::i18n::push_error_get_token_from_server(&CONFIG.default_locale()), e.to_string()), }; let json_pushtoken = match res.json::().await { Ok(r) => r, - Err(e) => err!(format!("Unexpected push token received from bitwarden server: {e}")), + Err(e) => err!(crate::i18n::push_unexpected_token_from_server(&CONFIG.default_locale()), e.to_string()), }; let mut api_token = API_TOKEN.write().await; @@ -125,11 +125,11 @@ pub async fn register_push_device(device: &mut Device, conn: &DbConn) -> EmptyRe .await? .error_for_status() { - err!(format!("An error occurred while proceeding registration of a device: {e}")); + err!(crate::i18n::push_error_register_device(&CONFIG.default_locale()), e.to_string()); } if let Err(e) = device.save(true, conn).await { - err!(format!("An error occurred while trying to save the (registered) device push uuid: {e}")); + err!(crate::i18n::push_error_save_registered_push_uuid(&CONFIG.default_locale()), e.to_string()); } Ok(()) @@ -155,9 +155,8 @@ pub async fn unregister_push_device(push_id: Option<&PushId>) -> EmptyResult { .await? .error_for_status() { - err!(format!("An error occurred during device unregistration: {e}")); + Err(e) => err!(crate::i18n::push_error_device_unregistration(&CONFIG.default_locale()), e.to_string()), } - Ok(()) } diff --git a/src/api/web.rs b/src/api/web.rs index e9a8b593..cfbc1058 100644 --- a/src/api/web.rs +++ b/src/api/web.rs @@ -4,10 +4,12 @@ use std::{ sync::{Arc, LazyLock, RwLock}, }; +use include_dir::{Dir, include_dir}; use rocket::{ Catcher, Route, fs::NamedFile, http::ContentType, + request::Request, response::{Redirect, content::RawHtml as Html}, serde::json::Json, }; @@ -29,7 +31,7 @@ use crate::{ pub fn routes() -> Vec { // If adding more routes here, consider also adding them to // crate::utils::LOGGED_ROUTES to make sure they appear in the log - let mut routes = routes![attachments, alive, alive_head, static_files]; + let mut routes = routes![attachments, alive, alive_head, static_files, static_locale_files]; if CONFIG.web_vault_enabled() { routes.append(&mut routes![ web_index, @@ -44,7 +46,7 @@ pub fn routes() -> Vec { #[cfg(debug_assertions)] if CONFIG.reload_templates() { - routes.append(&mut routes![static_files_dev]); + routes.append(&mut routes![static_files_dev, static_locale_files_dev]); } routes @@ -58,13 +60,28 @@ pub fn catchers() -> Vec { } } +fn localized_404_template_name(locale: &str) -> String { + for candidate in crate::i18n::locale_candidates(locale) { + let localized = format!("404/{candidate}"); + if CONFIG.has_template(&localized) { + return localized; + } + } + + "404".to_owned() +} + #[catch(404)] -fn not_found() -> ApiResult> { +fn not_found(request: &Request<'_>) -> ApiResult> { + let locale = + crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale()); // Return the page let json = json!({ - "urlpath": CONFIG.domain_path() + "urlpath": CONFIG.domain_path(), + "lang": locale, }); - let text = CONFIG.render_template("404", &json)?; + let template_name = localized_404_template_name(&locale); + let text = CONFIG.render_template(&template_name, &json)?; Ok(Html(text)) } @@ -277,12 +294,29 @@ pub async fn static_files_dev(filename: PathBuf) -> Option { None } +#[cfg(debug_assertions)] +#[get("/vw_static/locales//", rank = 1)] +pub async fn static_locale_files_dev(locale: &str, filename: PathBuf) -> Option { + let file = filename.to_str().unwrap_or_default(); + let path = tokio::fs::canonicalize( + Path::new(file!()).parent().unwrap().join("../static/locales/").join(locale).join(file), + ) + .await; + + if let Ok(path) = path { + return NamedFile::open(path).await.ok(); + } + None +} + pub struct StaticFile { pub content_type: ContentType, pub bytes: &'static [u8], pub etag: String, } +static BUILTIN_LOCALES_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/static/locales"); + pub static STATIC_FILES: LazyLock> = LazyLock::new(|| { [ ("404.png", ContentType::PNG, &include_bytes!("../static/images/404.png")[..]), @@ -295,6 +329,11 @@ pub static STATIC_FILES: LazyLock> = LazyLock: ("404.css", ContentType::CSS, &include_bytes!("../static/scripts/404.css")[..]), ("admin.css", ContentType::CSS, &include_bytes!("../static/scripts/admin.css")[..]), ("admin.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin.js")[..]), + ( + "admin_i18n_loader.js", + ContentType::JavaScript, + &include_bytes!("../static/scripts/admin_i18n_loader.js")[..], + ), ("admin_settings.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin_settings.js")[..]), ("admin_users.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin_users.js")[..]), ( @@ -327,11 +366,51 @@ pub static STATIC_FILES: LazyLock> = LazyLock: .collect() }); +pub static STATIC_LOCALE_FILES: LazyLock> = LazyLock::new(|| { + let mut files = HashMap::new(); + + let mut locale_dirs = BUILTIN_LOCALES_DIR.dirs().collect::>(); + locale_dirs.sort_by_key(|dir| dir.path().to_string_lossy().to_string()); + + for locale_dir in locale_dirs { + let Some(admin_ui_file) = locale_dir.get_file("admin_ui.json") else { + continue; + }; + + let Some(locale_name) = locale_dir.path().file_name().and_then(|name| name.to_str()) else { + continue; + }; + + let key = format!("{locale_name}/admin_ui.json"); + let bytes = admin_ui_file.contents(); + files.insert( + key, + StaticFile { + content_type: ContentType::JSON, + bytes, + etag: sha256_hex(bytes), + }, + ); + } + + files +}); + #[get("/vw_static/", rank = 2)] pub fn static_files(filename: &str) -> Result, Error> { if let Some(file) = STATIC_FILES.get(filename) { Ok(EtagCached::new(file.bytes, file.content_type.clone(), &file.etag)) } else { - err!(format!("Static file not found: {filename}")) + err!(crate::i18n::api_static_file_not_found(&CONFIG.default_locale()), filename) + } +} + +#[get("/vw_static/locales//", rank = 2)] +pub fn static_locale_files(locale: &str, filename: &str) -> Result, Error> { + let key = format!("{locale}/{filename}"); + if let Some(file) = STATIC_LOCALE_FILES.get(&key) { + Ok(EtagCached::new(file.bytes, file.content_type.clone(), &file.etag)) + } else { + err!(crate::i18n::api_static_file_not_found(&CONFIG.default_locale()), key) } } diff --git a/src/auth.rs b/src/auth.rs index cedbb130..0ed7bc2b 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -99,16 +99,16 @@ pub async fn initialize_keys() -> Result<(), Error> { let enc = EncodingKey::from_rsa_pem(&priv_key_buffer)?; let dec: DecodingKey = DecodingKey::from_rsa_pem(&pub_key_buffer)?; if PRIVATE_RSA_KEY.set(enc).is_err() { - err!("PRIVATE_RSA_KEY must only be initialized once") + err!(crate::i18n::auth_private_rsa_key_init_once(&CONFIG.default_locale())) } if PUBLIC_RSA_KEY.set(dec).is_err() { - err!("PUBLIC_RSA_KEY must only be initialized once") + err!(crate::i18n::auth_public_rsa_key_init_once(&CONFIG.default_locale())) } // Derived from the RSA key, so it stays the same across restarts without storing another secret let prelogin_kdf_key = hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, &priv_key_buffer), b"prelogin-kdf"); if PRELOGIN_KDF_KEY.set(hmac::Key::new(hmac::HMAC_SHA256, prelogin_kdf_key.as_ref())).is_err() { - err!("PRELOGIN_KDF_KEY must only be initialized once") + err!(crate::i18n::auth_prelogin_kdf_key_init_once(&CONFIG.default_locale())) } Ok(()) } @@ -138,10 +138,10 @@ pub fn decode_jwt(token: &str, issuer: String) -> Result Ok(d.claims), Err(err) => match *err.kind() { - ErrorKind::InvalidToken => err!("Token is invalid"), - ErrorKind::InvalidIssuer => err!("Issuer is invalid"), - ErrorKind::ExpiredSignature => err!("Token has expired"), - _ => err!(format!("Error decoding JWT: {:?}", err)), + ErrorKind::InvalidToken => err!(crate::i18n::auth_token_invalid(&CONFIG.default_locale())), + ErrorKind::InvalidIssuer => err!(crate::i18n::auth_issuer_invalid(&CONFIG.default_locale())), + ErrorKind::ExpiredSignature => err!(crate::i18n::auth_token_expired(&CONFIG.default_locale())), + _ => err!(crate::i18n::auth_error_decoding_jwt(&CONFIG.default_locale()), format!("{err:?}")), }, } } @@ -317,10 +317,10 @@ impl LoginJwtClaims { fn calculate_invite_expire_hours(now: &DateTime) -> Result, Error> { let expire_hours = i64::from(CONFIG.invitation_expiration_hours()); let Some(hours_delta) = TimeDelta::try_hours(expire_hours) else { - err!("Unable to calculate time delta for invite expire hours. Check `INVITATION_EXPIRATION_HOURS`."); + err!(crate::i18n::auth_invite_expire_delta_calculation_failed(&CONFIG.default_locale())); }; let Some(exp) = now.checked_add_signed(hours_delta) else { - err!("Unable to calculate invitation expire date. Check `INVITATION_EXPIRATION_HOURS`."); + err!(crate::i18n::auth_invite_expire_date_calculation_failed(&CONFIG.default_locale())); }; Ok(exp) } @@ -562,10 +562,10 @@ pub fn generate_admin_claims() -> Result { let time_now = Utc::now(); let lifetime_minutes = i64::from(CONFIG.admin_session_lifetime()); let Some(minutes_delta) = TimeDelta::try_minutes(lifetime_minutes) else { - err!("Unable to calculate time delta for admin session lifetime. Check `ADMIN_SESSION_LIFETIME`."); + err!(crate::i18n::auth_admin_session_delta_calculation_failed(&CONFIG.default_locale())); }; let Some(exp) = time_now.checked_add_signed(minutes_delta) else { - err!("Unable to calculate admin session lifetime. Check `ADMIN_SESSION_LIFETIME`."); + err!(crate::i18n::auth_admin_session_lifetime_calculation_failed(&CONFIG.default_locale())); }; Ok(BasicJwtClaims { nbf: time_now.timestamp(), @@ -632,6 +632,26 @@ impl<'r> FromRequest<'r> for Host { pub struct ClientHeaders { pub device_type: i32, pub ip: ClientIp, + pub locale: String, +} + +pub struct RequestLocale { + pub locale: String, +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for RequestLocale { + type Error = &'static str; + + async fn from_request(request: &'r Request<'_>) -> Outcome { + Outcome::Success(RequestLocale { + locale: crate::i18n::resolve_locale( + None, + request.headers().get_one("Accept-Language"), + &CONFIG.default_locale(), + ), + }) + } } #[rocket::async_trait] @@ -648,10 +668,13 @@ impl<'r> FromRequest<'r> for ClientHeaders { .get_one("device-type") .and_then(|d| d.parse().ok()) .unwrap_or(DeviceType::UnknownBrowser as i32); + let locale = + crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale()); Outcome::Success(ClientHeaders { device_type, ip, + locale, }) } } @@ -661,6 +684,7 @@ pub struct Headers { pub device: Device, pub user: User, pub ip: ClientIp, + pub locale: String, } #[rocket::async_trait] @@ -706,6 +730,9 @@ impl<'r> FromRequest<'r> for Headers { err_handler!("Device has no user associated") }; + let locale = + crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale()); + if user.security_stamp != claims.sstamp { if let Some(stamp_exception) = user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::(s).ok()) @@ -741,6 +768,7 @@ impl<'r> FromRequest<'r> for Headers { device, user, ip, + locale, }) } } @@ -953,11 +981,13 @@ impl<'r> FromRequest<'r> for ManagerHeaders { impl From for Headers { fn from(h: ManagerHeaders) -> Headers { + let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale()); Headers { host: h.host, device: h.device, user: h.user, ip: h.ip, + locale, } } } @@ -994,11 +1024,13 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose { impl From for Headers { fn from(h: ManagerHeadersLoose) -> Headers { + let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale()); Headers { host: h.host, device: h.device, user: h.user, ip: h.ip, + locale, } } } @@ -1011,10 +1043,19 @@ impl ManagerHeaders { ) -> Result { for col_id in collections { if uuid::Uuid::parse_str(col_id.as_ref()).is_err() { - err!("Collection Id is malformed!"); + err!(crate::i18n::auth_collection_id_malformed( + h.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + )); } if !Collection::is_coll_manageable_by_user(col_id, &h.membership.user_uuid, conn).await { - err!("Collection not found", "The current user isn't a manager for this collection") + err!( + crate::i18n::auth_collection_not_found_or_not_manager( + h.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + ), + crate::i18n::auth_user_not_manager_for_collection( + h.user.locale.as_deref().unwrap_or(&CONFIG.default_locale()) + ) + ) } } @@ -1084,11 +1125,13 @@ impl<'r> FromRequest<'r> for OrgMemberHeaders { impl From for Headers { fn from(h: OrgMemberHeaders) -> Headers { + let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale()); Headers { host: h.host, device: h.device, user: h.user, ip: h.ip, + locale, } } } @@ -1281,9 +1324,11 @@ impl AuthMethod { pub fn check_scope(&self, scope: Option<&String>) -> ApiResult { let method_scope = self.scope(); match scope { - None => err!("Missing scope"), + None => err!(crate::i18n::auth_missing_scope(&CONFIG.default_locale())), Some(scope) if scope == &method_scope => Ok(method_scope), - Some(scope) => err!(format!("Scope ({}) not supported", scope.escape_debug())), + Some(scope) => { + err!(crate::i18n::auth_scope_not_supported(&CONFIG.default_locale()), scope.escape_debug().to_string()) + } } } } @@ -1370,21 +1415,21 @@ pub async fn refresh_tokens( let refresh_claims = match decode_refresh(refresh_token) { Err(err) => { error!("Failed to decode refresh_token from {}: {err:?}", ip.ip); - err_silent!("Invalid refresh token") + err_silent!(crate::i18n::auth_invalid_refresh_token(&CONFIG.default_locale())) } Ok(claims) => claims, }; // Get device by refresh token let Some(mut device) = Device::find_by_refresh_token(&refresh_claims.device_token, conn).await else { - err!("Invalid refresh token") + err!(crate::i18n::auth_invalid_refresh_token(&CONFIG.default_locale())) }; // Save to update `updated_at`. device.save(true, conn).await?; let Some(user) = User::find_by_uuid(&device.user_uuid, conn).await else { - err!("Impossible to find user") + err!(crate::i18n::auth_impossible_find_user(&CONFIG.default_locale())) }; let auth_tokens = match refresh_claims.sub { @@ -1394,10 +1439,12 @@ pub async fn refresh_tokens( AuthMethod::Sso if CONFIG.sso_enabled() => { sso::exchange_refresh_token(&device, &user, client_id, refresh_claims).await? } - AuthMethod::Sso => err!("SSO is now disabled, Login again using email and master password"), - AuthMethod::Password if CONFIG.sso_enabled() && CONFIG.sso_only() => err!("SSO is now required, Login again"), + AuthMethod::Sso => err!(crate::i18n::auth_sso_now_disabled_login_password(&CONFIG.default_locale())), + AuthMethod::Password if CONFIG.sso_enabled() && CONFIG.sso_only() => { + err!(crate::i18n::auth_sso_now_required_login_again(&CONFIG.default_locale())) + } AuthMethod::Password => AuthTokens::new(&device, &user, refresh_claims.sub, client_id), - _ => err!("Invalid auth method, cannot refresh token"), + _ => err!(crate::i18n::auth_invalid_auth_method_refresh(&CONFIG.default_locale())), }; Ok((device, auth_tokens)) diff --git a/src/auth/two_factor.rs b/src/auth/two_factor.rs index 533c0cf4..8adff841 100644 --- a/src/auth/two_factor.rs +++ b/src/auth/two_factor.rs @@ -126,14 +126,16 @@ fn validate(token: &str, user_id: &UserId, enabled: bool) - match decode_jwt::>(token, JWT_2FA_AUTH_ISSUER.to_string()) { Ok(claims) => { if claims.sub != *user_id { - err!("Invalid verification token: Invalid user"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_user(&CONFIG.default_locale())); } if claims.enabled != enabled { - err!("Invalid verification token: Invalid state"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_state(&CONFIG.default_locale())); } Ok(claims.claims) } - Err(err) => err!(format!("Failed to decode verification token: {err}")), + Err(err) => { + err!(crate::i18n::two_factor_failed_decode_verification_token(&CONFIG.default_locale()), err.to_string()) + } } } @@ -150,7 +152,7 @@ pub fn authenticator_token(user_id: UserId, key: String, enabled: bool) -> Strin pub fn validate_authenticator(token: &str, user_id: &UserId, key: &str, enabled: bool) -> EmptyResult { let claims = validate::(token, user_id, enabled)?; if claims.key != key { - err!("Invalid verification token: Invalid key"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_key(&CONFIG.default_locale())); } Ok(()) } @@ -169,7 +171,7 @@ pub fn duo_token(user_id: UserId, data: Option, enabled: bool) -> Strin pub fn validate_duo(token: &str, user_id: &UserId, data: Option<&DuoData>, enabled: bool) -> EmptyResult { let claims = validate::(token, user_id, enabled)?; if enabled && claims.data.as_ref() != data { - err!("Invalid verification token: Invalid duo data"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_duo_data(&CONFIG.default_locale())); } Ok(()) } @@ -188,7 +190,7 @@ pub fn email_token(user_id: UserId, email: Option, enabled: bool) -> Str pub fn validate_email(token: &str, user_id: &UserId, email: String, enabled: bool) -> EmptyResult { let claims = validate::(token, user_id, enabled)?; if enabled && claims.email != Some(email) { - err!("Invalid verification token: Invalid email"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_email(&CONFIG.default_locale())); } Ok(()) } @@ -206,7 +208,7 @@ pub fn webauthn_token(user_id: UserId, keys: Vec, enabled: bool) -> String pub fn validate_webauthn(token: &str, user_id: &UserId, keys: &[i32], enabled: bool) -> EmptyResult { let claims = validate::(token, user_id, enabled)?; if keys != claims.keys { - err!("Invalid verification token: Invalid keys"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_keys(&CONFIG.default_locale())); } Ok(()) } @@ -224,7 +226,7 @@ pub fn yubikey_token(user_id: UserId, keys: Vec, enabled: bool) -> Strin pub fn validate_yubikey(token: &str, user_id: &UserId, keys: &Vec, enabled: bool) -> EmptyResult { let claims = validate::(token, user_id, enabled)?; if *keys != claims.keys { - err!("Invalid verification token: Invalid keys"); + err!(crate::i18n::two_factor_invalid_verification_token_invalid_keys(&CONFIG.default_locale())); } Ok(()) } diff --git a/src/config.rs b/src/config.rs index 55d08259..b0b4507f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -396,7 +396,7 @@ macro_rules! make_config { GroupData { group: stringify!($group), grouptoggle: stringify!($($group_enabled)?), - groupdoc: (make_config! { @show $($groupdoc)? }), + groupdoc: (make_config! { @show $($groupdoc)? }).trim(), elements: vec![ $( // This repetition is for each element within a group @@ -590,6 +590,8 @@ make_config! { /// Domain URL |> This needs to be set to the URL used to access the server, including 'http[s]://' /// and port, if it's different than the default. Some server functions don't work correctly without this value domain: String, true, def, "http://localhost".to_owned(); + /// Default locale |> Locale used for localized templates. Supports language or language-region (for example: en, en-US, ru, uk-UA) + default_locale: String, true, def, "en".to_owned(); /// Domain Set |> Indicates if the domain is set by the admin. Otherwise the default will be used. domain_set: bool, false, def, false; /// Domain origin |> Domain URL origin (in https://example.com:8443/path, https://example.com:8443 is the origin) @@ -957,6 +959,8 @@ make_config! { } fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { + let locale = cfg.default_locale.as_str(); + // Validate connection URL is valid and DB feature is enabled #[cfg(sqlite)] { @@ -969,10 +973,7 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { if let Some(parent) = path.parent() && !parent.is_dir() { - err!(format!( - "SQLite database directory `{}` does not exist or is not a directory", - parent.display() - )); + err!(crate::i18n::config_sqlite_database_directory_invalid(locale), parent.display().to_string()); } } } @@ -982,43 +983,40 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { if !trusted_proxies.eq_ignore_ascii_case("all") && !trusted_proxies.eq_ignore_ascii_case("local") { for entry in trusted_proxies.split(',').filter(|e| !e.trim().is_empty()) { if crate::auth::parse_trusted_proxy(entry).is_none() { - err!(format!( - "Invalid IP_HEADER_TRUSTED_PROXIES entry `{}`, expected an IP or CIDR range", - entry.trim() - )); + err!(crate::i18n::config_ip_header_trusted_proxies_invalid_entry(locale), entry.trim()); } } } if cfg.password_iterations < 100_000 { - err!("PASSWORD_ITERATIONS should be at least 100000 or higher. The default is 600000!"); + err!(crate::i18n::config_password_iterations_min(locale)); } let limit = 256; if cfg.database_max_conns < 1 || cfg.database_max_conns > limit { - err!(format!("`DATABASE_MAX_CONNS` contains an invalid value. Ensure it is between 1 and {limit}.",)); + err!(crate::i18n::config_database_max_conns_invalid_range(locale)); } if cfg.database_min_conns < 1 || cfg.database_min_conns > limit { - err!(format!("`DATABASE_MIN_CONNS` contains an invalid value. Ensure it is between 1 and {limit}.",)); + err!(crate::i18n::config_database_min_conns_invalid_range(locale)); } if cfg.database_min_conns > cfg.database_max_conns { - err!("`DATABASE_MIN_CONNS` must be less than or equal to `DATABASE_MAX_CONNS`."); + err!(crate::i18n::config_database_min_conns_lte_max(locale)); } if cfg.database_timeout < 1 { - err!("`DATABASE_TIMEOUT` must be at least 1 second"); + err!(crate::i18n::config_database_timeout_min_1(locale)); } if cfg.database_idle_timeout < 1 { - err!("`DATABASE_IDLE_TIMEOUT` must be at least 1 second"); + err!(crate::i18n::config_database_idle_timeout_min_1(locale)); } if let Some(log_file) = &cfg.log_file && std::fs::OpenOptions::new().append(true).create(true).open(log_file).is_err() { - err!("Unable to write to log file", log_file); + err!(crate::i18n::config_unable_write_log_file(locale), log_file); } let dom = cfg.domain.to_lowercase(); @@ -1054,14 +1052,14 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { let whitelist = &cfg.signups_domains_whitelist; if !whitelist.is_empty() && whitelist.split(',').any(|d| d.trim().is_empty()) { - err!("`SIGNUPS_DOMAINS_WHITELIST` contains empty tokens"); + err!(crate::i18n::config_signups_domains_whitelist_empty_tokens(locale)); } let org_creation_users = cfg.org_creation_users.trim().to_lowercase(); if !(org_creation_users.is_empty() || org_creation_users == "all" || org_creation_users == "none") && org_creation_users.split(',').any(|u| !u.contains('@')) { - err!("`ORG_CREATION_USERS` contains invalid email addresses"); + err!(crate::i18n::config_org_creation_users_invalid_emails(locale)); } if let Some(ref token) = cfg.admin_token @@ -1086,20 +1084,20 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { if cfg.push_enabled { let push_relay_uri = cfg.push_relay_uri.to_lowercase(); if !push_relay_uri.starts_with("https://") { - err!("`PUSH_RELAY_URI` must start with 'https://'.") + err!(crate::i18n::config_push_relay_uri_must_be_https(locale)) } if Url::parse(&push_relay_uri).is_err() { - err!("Invalid URL format for `PUSH_RELAY_URI`."); + err!(crate::i18n::config_push_relay_uri_invalid_url(locale)); } let push_identity_uri = cfg.push_identity_uri.to_lowercase(); if !push_identity_uri.starts_with("https://") { - err!("`PUSH_IDENTITY_URI` must start with 'https://'.") + err!(crate::i18n::config_push_identity_uri_must_be_https(locale)) } if Url::parse(&push_identity_uri).is_err() { - err!("Invalid URL format for `PUSH_IDENTITY_URI`."); + err!(crate::i18n::config_push_identity_uri_invalid_url(locale)); } } @@ -1125,41 +1123,41 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { if let Some(limit) = cfg.user_attachment_limit && !(0i64..=MAX_FILESIZE_KB).contains(&limit) { - err!("`USER_ATTACHMENT_LIMIT` is out of bounds"); + err!(crate::i18n::config_user_attachment_limit_out_of_bounds(locale)); } if let Some(limit) = cfg.org_attachment_limit && !(0i64..=MAX_FILESIZE_KB).contains(&limit) { - err!("`ORG_ATTACHMENT_LIMIT` is out of bounds"); + err!(crate::i18n::config_org_attachment_limit_out_of_bounds(locale)); } if let Some(limit) = cfg.user_send_limit && !(0i64..=MAX_FILESIZE_KB).contains(&limit) { - err!("`USER_SEND_LIMIT` is out of bounds"); + err!(crate::i18n::config_user_send_limit_out_of_bounds(locale)); } if cfg._enable_duo && (cfg.duo_host.is_some() || cfg.duo_ikey.is_some() || cfg.duo_skey.is_some()) && !(cfg.duo_host.is_some() && cfg.duo_ikey.is_some() && cfg.duo_skey.is_some()) { - err!("All Duo options need to be set for global Duo support") + err!(crate::i18n::config_duo_all_options_required(locale)) } if cfg.sso_enabled { if cfg.sso_client_id.is_empty() || cfg.sso_client_secret.is_empty() || cfg.sso_authority.is_empty() { - err!("`SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` and `SSO_AUTHORITY` must be set for SSO support") + err!(crate::i18n::config_sso_required_options_missing(locale)) } - validate_internal_sso_issuer_url(&cfg.sso_authority)?; - validate_internal_sso_redirect_url(&cfg.sso_callback_path)?; - validate_sso_master_password_policy(cfg.sso_master_password_policy.as_ref())?; + validate_internal_sso_issuer_url(&cfg.sso_authority, locale)?; + validate_internal_sso_redirect_url(&cfg.sso_callback_path, locale)?; + validate_sso_master_password_policy(cfg.sso_master_password_policy.as_ref(), locale)?; } if cfg._enable_yubico { if cfg.yubico_client_id.is_some() != cfg.yubico_secret_key.is_some() { - err!("Both `YUBICO_CLIENT_ID` and `YUBICO_SECRET_KEY` must be set for Yubikey OTP support") + err!(crate::i18n::config_yubico_both_credentials_required(locale)) } if let Some(yubico_server) = &cfg.yubico_server { @@ -1187,32 +1185,35 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { // Check if we can find the sendmail command to execute when no absolute path is given if !path.is_absolute() { let Ok(which_path) = which::which(&command) else { - err!(format!("sendmail command {command} not found in $PATH")) + err!(crate::i18n::config_sendmail_command_not_found_in_path(locale), command) }; path = which_path; } match path.metadata() { Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - err!(format!("sendmail command not found at `{path:?}`")) + err!(crate::i18n::config_sendmail_command_not_found_at_path(locale), path.display().to_string()) } Err(err) => { - err!(format!("failed to access sendmail command at `{path:?}`: {err}")) + err!( + crate::i18n::config_sendmail_command_access_failed(locale), + format!("{}: {}", path.display(), err) + ) } Ok(metadata) => { if metadata.is_dir() { - err!(format!("sendmail command at `{path:?}` isn't a directory")); + err!(crate::i18n::config_sendmail_command_is_directory(locale), path.display().to_string()); } #[cfg(unix)] if nix::unistd::access(&path, nix::unistd::AccessFlags::X_OK).is_err() { - err!(format!("sendmail command at `{path:?}` isn't executable")); + err!(crate::i18n::config_sendmail_command_not_executable(locale), path.display().to_string()); } } } } else { if cfg.smtp_host.is_some() == cfg.smtp_from.is_empty() { - err!("Both `SMTP_HOST` and `SMTP_FROM` need to be set for email support without `USE_SENDMAIL`") + err!(crate::i18n::config_smtp_host_and_from_required(locale)) } if cfg.smtp_username.is_some() != cfg.smtp_password.is_some() { @@ -1223,23 +1224,23 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { } if (cfg.smtp_host.is_some() || cfg.use_sendmail) && !is_valid_email(&cfg.smtp_from) { - err!(format!("SMTP_FROM '{}' is not a valid email address", cfg.smtp_from)) + err!(crate::i18n::config_smtp_from_invalid_email(locale), &cfg.smtp_from) } if cfg._enable_email_2fa && cfg.email_token_size < 6 { - err!("`EMAIL_TOKEN_SIZE` has a minimum size of 6") + err!(crate::i18n::config_email_token_size_min_6(locale)) } } if cfg._enable_email_2fa && !(cfg.smtp_host.is_some() || cfg.use_sendmail) { - err!("To enable email 2FA, a mail transport must be configured") + err!(crate::i18n::config_email_2fa_requires_mail_transport(locale)) } if !cfg._enable_email_2fa && cfg.email_2fa_enforce_on_verified_invite { - err!("To enforce email 2FA on verified invitations, email 2fa has to be enabled!"); + err!(crate::i18n::config_email_2fa_verified_invite_requires_enable(locale)); } if !cfg._enable_email_2fa && cfg.email_2fa_auto_fallback { - err!("To use email 2FA as automatic fallback, email 2fa has to be enabled!"); + err!(crate::i18n::config_email_2fa_fallback_requires_enable(locale)); } // Check if the HTTP request block regex is valid @@ -1247,7 +1248,7 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { let validate_regex = regex::Regex::new(r); match validate_regex { Ok(_) => (), - Err(e) => err!(format!("`HTTP_REQUEST_BLOCK_REGEX` is invalid: {e:#?}")), + Err(e) => err!(crate::i18n::config_http_request_block_regex_invalid(locale), format!("{e:#?}")), } } @@ -1257,12 +1258,12 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { "internal" | "bitwarden" | "duckduckgo" | "google" => (), _ => { if !icon_service.starts_with("http") { - err!(format!("Icon service URL `{icon_service}` must start with \"http\"")) + err!(crate::i18n::config_icon_service_url_must_start_http(locale), icon_service) } match icon_service.matches("{}").count() { 1 => (), // nominal - 0 => err!(format!("Icon service URL `{icon_service}` has no placeholder \"{{}}\"")), - _ => err!(format!("Icon service URL `{icon_service}` has more than one placeholder \"{{}}\"")), + 0 => err!(crate::i18n::config_icon_service_url_missing_placeholder(locale), icon_service), + _ => err!(crate::i18n::config_icon_service_url_multiple_placeholders(locale), icon_service), } } } @@ -1270,11 +1271,11 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { // Check if the icon redirect code is valid match cfg.icon_redirect_code { 301 | 302 | 307 | 308 => (), - _ => err!("Only HTTP 301/302 and 307/308 redirects are supported"), + _ => err!(crate::i18n::config_icon_redirect_supported_codes(locale)), } if cfg.invitation_expiration_hours < 1 { - err!("`INVITATION_EXPIRATION_HOURS` has a minimum duration of 1 hour") + err!(crate::i18n::config_invitation_expiration_hours_min_1(locale)) } if !(1..=90).contains(&cfg.two_factor_remember_days) { @@ -1283,74 +1284,74 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { // Validate schedule crontab format if !cfg.send_purge_schedule.is_empty() && cfg.send_purge_schedule.parse::().is_err() { - err!("`SEND_PURGE_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_send_purge_schedule_invalid(locale)) } if !cfg.trash_purge_schedule.is_empty() && cfg.trash_purge_schedule.parse::().is_err() { - err!("`TRASH_PURGE_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_trash_purge_schedule_invalid(locale)) } if !cfg.incomplete_2fa_schedule.is_empty() && cfg.incomplete_2fa_schedule.parse::().is_err() { - err!("`INCOMPLETE_2FA_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_incomplete_2fa_schedule_invalid(locale)) } if !cfg.emergency_notification_reminder_schedule.is_empty() && cfg.emergency_notification_reminder_schedule.parse::().is_err() { - err!("`EMERGENCY_NOTIFICATION_REMINDER_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_emergency_notification_reminder_schedule_invalid(locale)) } if !cfg.emergency_request_timeout_schedule.is_empty() && cfg.emergency_request_timeout_schedule.parse::().is_err() { - err!("`EMERGENCY_REQUEST_TIMEOUT_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_emergency_request_timeout_schedule_invalid(locale)) } if !cfg.event_cleanup_schedule.is_empty() && cfg.event_cleanup_schedule.parse::().is_err() { - err!("`EVENT_CLEANUP_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_event_cleanup_schedule_invalid(locale)) } if !cfg.auth_request_purge_schedule.is_empty() && cfg.auth_request_purge_schedule.parse::().is_err() { - err!("`AUTH_REQUEST_PURGE_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_auth_request_purge_schedule_invalid(locale)) } if !cfg.duo_context_purge_schedule.is_empty() && cfg.duo_context_purge_schedule.parse::().is_err() { - err!("`DUO_CONTEXT_PURGE_SCHEDULE` is not a valid cron expression") + err!(crate::i18n::config_duo_context_purge_schedule_invalid(locale)) } if !cfg.purge_incomplete_sso_auth.is_empty() && cfg.purge_incomplete_sso_auth.parse::().is_err() { - err!("`PURGE_INCOMPLETE_SSO_AUTH` is not a valid cron expression") + err!(crate::i18n::config_purge_incomplete_sso_auth_invalid(locale)) } if cfg.login_ratelimit_seconds < 1 { - err!("`LOGIN_RATELIMIT_SECONDS` must be at least 1 second"); + err!(crate::i18n::config_login_ratelimit_seconds_min_1(locale)); } if cfg.login_ratelimit_max_burst < 1 { - err!("`LOGIN_RATELIMIT_MAX_BURST` must be at least 1"); + err!(crate::i18n::config_login_ratelimit_max_burst_min_1(locale)); } if cfg.admin_ratelimit_seconds < 1 { - err!("`ADMIN_RATELIMIT_SECONDS` must be at least 1 second"); + err!(crate::i18n::config_admin_ratelimit_seconds_min_1(locale)); } if cfg.admin_ratelimit_max_burst < 1 { - err!("`ADMIN_RATELIMIT_MAX_BURST` must be at least 1"); + err!(crate::i18n::config_admin_ratelimit_max_burst_min_1(locale)); } if cfg.unauthenticated_ratelimit_seconds < 1 { - err!("`UNAUTHENTICATED_RATELIMIT_SECONDS` must be at least 1 second"); + err!(crate::i18n::config_unauthenticated_ratelimit_seconds_min_1(locale)); } if cfg.unauthenticated_ratelimit_max_burst < 1 { - err!("`UNAUTHENTICATED_RATELIMIT_MAX_BURST` must be at least 1"); + err!(crate::i18n::config_unauthenticated_ratelimit_max_burst_min_1(locale)); } if !cfg.disable_admin_token { match cfg.admin_token.as_ref() { Some(t) if t.starts_with("$argon2") => { if let Err(e) = argon2::password_hash::phc::PasswordHash::new(t) { - err!(format!("The configured Argon2 PHC in `ADMIN_TOKEN` is invalid: '{e}'")) + err!(crate::i18n::config_admin_token_argon2_phc_invalid(locale), e.to_string()) } } Some(_) => { @@ -1371,31 +1372,37 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { Ok(()) } -fn validate_internal_sso_issuer_url(sso_authority: &String) -> Result { +fn validate_internal_sso_issuer_url(sso_authority: &String, locale: &str) -> Result { match openidconnect::IssuerUrl::new(sso_authority.clone()) { - Err(err) => err!(format!("Invalid sso_authority URL ({sso_authority}): {err}")), + Err(err) => err!(crate::i18n::config_sso_authority_url_invalid(locale), format!("{sso_authority}: {err}")), Ok(issuer_url) => Ok(issuer_url), } } -fn validate_internal_sso_redirect_url(sso_callback_path: &String) -> Result { +fn validate_internal_sso_redirect_url( + sso_callback_path: &String, + locale: &str, +) -> Result { match openidconnect::RedirectUrl::new(sso_callback_path.clone()) { - Err(err) => err!(format!("Invalid sso_callback_path ({sso_callback_path} built using `domain`) URL: {err}")), + Err(err) => { + err!(crate::i18n::config_sso_callback_path_url_invalid(locale), format!("{sso_callback_path}: {err}")) + } Ok(redirect_url) => Ok(redirect_url), } } fn validate_sso_master_password_policy( sso_master_password_policy: Option<&String>, + locale: &str, ) -> Result, Error> { let policy = sso_master_password_policy.as_ref().map(|mpp| serde_json::from_str::(mpp)); match policy { None => Ok(None), Some(Ok(jsobject @ serde_json::Value::Object(_))) => Ok(Some(jsobject)), - Some(Ok(_)) => err!("Invalid sso_master_password_policy: parsed value is not a JSON object"), + Some(Ok(_)) => err!(crate::i18n::config_sso_master_password_policy_not_object(locale)), Some(Err(error)) => { - err!(format!("Invalid sso_master_password_policy ({error}), Ensure that it's correctly escaped with ''")) + err!(crate::i18n::config_sso_master_password_policy_invalid(locale), error.to_string()) } } } @@ -1741,6 +1748,16 @@ impl Config { } } + pub fn has_template(&self, name: &str) -> bool { + if self.reload_templates() { + let hb = load_templates(CONFIG.templates_folder()); + hb.has_template(name) + } else { + let hb = &self.inner.read().unwrap().templates; + hb.has_template(name) + } + } + pub fn render_fallback_template(&self, name: &str, data: &T) -> Result { let hb = &self.inner.read().unwrap().templates; hb.render(&format!("fallback_{name}"), data).map_err(Into::into) @@ -1759,15 +1776,18 @@ impl Config { } pub fn sso_issuer_url(&self) -> Result { - validate_internal_sso_issuer_url(&self.sso_authority()) + let locale = self.default_locale(); + validate_internal_sso_issuer_url(&self.sso_authority(), &locale) } pub fn sso_redirect_url(&self) -> Result { - validate_internal_sso_redirect_url(&self.sso_callback_path()) + let locale = self.default_locale(); + validate_internal_sso_redirect_url(&self.sso_callback_path(), &locale) } pub fn sso_master_password_policy_value(&self) -> Option { - validate_sso_master_password_policy(self.sso_master_password_policy().as_ref()).ok().flatten() + let locale = self.default_locale(); + validate_sso_master_password_policy(self.sso_master_password_policy().as_ref(), &locale).ok().flatten() } pub fn sso_scopes_vec(&self) -> Vec { @@ -1793,6 +1813,7 @@ where hb.set_strict_mode(true); // Register helpers hb.register_helper("case", Box::new(case_helper)); + hb.register_helper("t", Box::new(t_helper)); hb.register_helper("to_json", Box::new(to_json)); hb.register_helper("webver", Box::new(webver)); hb.register_helper("vwver", Box::new(vwver)); @@ -1888,6 +1909,35 @@ fn case_helper<'reg, 'rc>( } } +fn t_helper<'reg, 'rc>( + h: &Helper<'rc>, + _r: &'reg Handlebars<'_>, + ctx: &'rc Context, + _rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, +) -> HelperResult { + let key = h.param(0).and_then(|p| p.value().as_str()).ok_or_else(|| { + RenderErrorReason::Other(String::from("Expected string key as first parameter for helper \"t\"")) + })?; + + let locale = h + .hash_get("locale") + .and_then(|v| v.value().as_str()) + .or_else(|| h.param(1).and_then(|p| p.value().as_str())) + .or_else(|| ctx.data().get("lang").and_then(|v| v.as_str())) + .or_else(|| ctx.data().get("locale").and_then(|v| v.as_str())) + .map_or_else(|| CONFIG.default_locale(), str::to_owned); + + if let Some(value) = crate::i18n::tr_lookup(&locale, key) { + out.write(value)?; + } else { + // Keep rendering resilient during incremental migrations. + out.write(key)?; + } + + Ok(()) +} + fn to_json<'reg, 'rc>( h: &Helper<'rc>, _r: &'reg Handlebars<'_>, diff --git a/src/db/mod.rs b/src/db/mod.rs index 2ccd7d48..391203f4 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -218,7 +218,7 @@ impl DbPool { init_stmts: conn_type.get_init_stmts(), })) .build(manager) - .map_res("Failed to create pool")?; + .map_res(crate::i18n::db_failed_create_pool(&CONFIG.default_locale()))?; // Set a global to determine the database more easily throughout the rest of the code if ACTIVE_DB_TYPE.set(conn_type).is_err() { @@ -237,14 +237,15 @@ impl DbPool { let permit = match timeout(duration, Arc::clone(&self.semaphore).acquire_owned()).await { Ok(p) => p.expect("Semaphore should be open"), Err(_) => { - err!("Timeout waiting for database connection"); + err!(crate::i18n::api_db_timeout_waiting_connection(&CONFIG.default_locale())); } }; let p = self.pool.as_ref().expect("DbPool.pool should always be Some()"); let pool = p.clone(); - let c = - run_blocking(move || pool.get_timeout(duration)).await.map_res("Error retrieving connection from pool")?; + let c = run_blocking(move || pool.get_timeout(duration)) + .await + .map_res(crate::i18n::db_error_retrieving_connection_from_pool(&CONFIG.default_locale()))?; Ok(DbConn { conn: Arc::new(Mutex::new(Some(c))), permit: Some(permit), @@ -260,7 +261,7 @@ impl DbConnType { return Ok(DbConnType::Mysql); #[cfg(not(mysql))] - err!("`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled") + err!(crate::i18n::api_db_url_mysql_feature_not_enabled(&CONFIG.default_locale())) // Postgresql } else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") { @@ -268,7 +269,7 @@ impl DbConnType { return Ok(DbConnType::Postgresql); #[cfg(not(postgresql))] - err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled") + err!(crate::i18n::api_db_url_postgresql_feature_not_enabled(&CONFIG.default_locale())) // Sqlite (explicit) } else if url.len() > 7 && &url[..7] == "sqlite:" { @@ -276,7 +277,7 @@ impl DbConnType { return Ok(DbConnType::Sqlite); #[cfg(not(sqlite))] - err!("`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled") + err!(crate::i18n::api_db_url_sqlite_feature_not_enabled(&CONFIG.default_locale())) } // No recognized scheme — assume legacy bare-path SQLite, but the database file must already exist. @@ -286,16 +287,17 @@ impl DbConnType { if std::path::Path::new(url).exists() { return Ok(DbConnType::Sqlite); } - err!(format!( + let msg = format!( "`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \ and no existing SQLite database was found at '{url}'. \ If you intend to use SQLite, use an explicit `sqlite://` scheme in your `DATABASE_URL`. \ Otherwise, check your DATABASE_URL for typos or quoting issues." - )) + ); + err!(msg) } #[cfg(not(sqlite))] - err!("`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://)") + err!(crate::i18n::api_db_url_unknown_scheme(&CONFIG.default_locale())) } pub fn get_init_stmts(&self) -> String { @@ -421,7 +423,7 @@ pub fn backup_sqlite() -> Result { .bind::(&backup_file) .execute(&mut conn) .map(|_| ()) - .map_res("VACUUM INTO failed")?; + .map_res(crate::i18n::db_vacuum_into_failed(&CONFIG.default_locale()))?; Ok(backup_file) } else { diff --git a/src/db/models/archive.rs b/src/db/models/archive.rs index 2330fac4..347a1dc6 100644 --- a/src/db/models/archive.rs +++ b/src/db/models/archive.rs @@ -2,6 +2,7 @@ use chrono::NaiveDateTime; use diesel::prelude::*; use crate::{ + CONFIG, api::EmptyResult, db::{DbConn, schema::archives}, error::MapResult, @@ -52,7 +53,7 @@ impl Archive { .do_update() .set(archives::archived_at.eq(archived_at)) .execute(conn) - .map_res("Error saving archive") + .map_res(crate::i18n::db_error_saving_archive(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(archives::table) @@ -65,7 +66,7 @@ impl Archive { .do_update() .set(archives::archived_at.eq(archived_at)) .execute(conn) - .map_res("Error saving archive") + .map_res(crate::i18n::db_error_saving_archive(&CONFIG.default_locale())) } } } @@ -78,7 +79,7 @@ impl Archive { archives::table.filter(archives::user_uuid.eq(user_uuid)).filter(archives::cipher_uuid.eq(cipher_uuid)), ) .execute(conn) - .map_res("Error deleting archive") + .map_res(crate::i18n::db_error_deleting_archive(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/attachment.rs b/src/db/models/attachment.rs index 659648d0..77a2990b 100644 --- a/src/db/models/attachment.rs +++ b/src/db/models/attachment.rs @@ -89,7 +89,7 @@ impl Attachment { .do_update() .set(self) .execute(conn) - .map_res("Error saving attachment") + .map_res(crate::i18n::db_error_saving_attachment(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(attachments::table) @@ -98,7 +98,7 @@ impl Attachment { .do_update() .set(self) .execute(conn) - .map_res("Error saving attachment") + .map_res(crate::i18n::db_error_saving_attachment(&CONFIG.default_locale())) } } } @@ -110,7 +110,7 @@ impl Attachment { 10, ) .map(|_| ()) - .map_res("Error deleting attachment") + .map_res(crate::i18n::db_error_deleting_attachment(&CONFIG.default_locale())) }) .await?; diff --git a/src/db/models/auth_request.rs b/src/db/models/auth_request.rs index f2b0ecdc..8e4fe128 100644 --- a/src/db/models/auth_request.rs +++ b/src/db/models/auth_request.rs @@ -4,6 +4,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::{ApiResult, EmptyResult}, crypto::ct_eq, db::{DbConn, schema::auth_requests}, @@ -91,7 +92,7 @@ impl AuthRequest { .do_update() .set(self) .execute(conn) - .map_res("Error saving auth_request") + .map_res(crate::i18n::db_error_saving_auth_request(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(auth_requests::table) @@ -100,7 +101,7 @@ impl AuthRequest { .do_update() .set(self) .execute(conn) - .map_res("Error saving auth_request") + .map_res(crate::i18n::db_error_saving_auth_request(&CONFIG.default_locale())) } } } @@ -161,7 +162,7 @@ impl AuthRequest { conn.run(move |conn| { diesel::delete(auth_requests::table.filter(auth_requests::uuid.eq(&self.uuid))) .execute(conn) - .map_res("Error deleting auth request") + .map_res(crate::i18n::db_error_deleting_auth_request(&CONFIG.default_locale())) }) .await } @@ -170,7 +171,7 @@ impl AuthRequest { conn.run(move |conn| { diesel::delete(auth_requests::table.filter(auth_requests::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error deleting auth requests for user") + .map_res(crate::i18n::db_error_deleting_auth_requests_for_user(&CONFIG.default_locale())) }) .await } @@ -185,7 +186,7 @@ impl AuthRequest { .set(auth_requests::authentication_date.eq(now)) .execute(conn) .map(|updated| updated == 1) - .map_res("Error updating auth request") + .map_res(crate::i18n::db_error_updating_auth_request(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/cipher.rs b/src/db/models/cipher.rs index 630146e4..624faa31 100644 --- a/src/db/models/cipher.rs +++ b/src/db/models/cipher.rs @@ -97,10 +97,11 @@ impl Cipher { } pub fn validate_cipher_data(cipher_data: &[CipherData]) -> EmptyResult { + let locale = CONFIG.default_locale(); let mut validation_errors = serde_json::Map::new(); let max_note_size = CONFIG._max_note_size(); let max_note_size_msg = - format!("The field Notes exceeds the maximum encrypted value length of {max_note_size} characters."); + crate::i18n::cipher_notes_exceeds_max_len(&locale).replacen("{}", &max_note_size.to_string(), 1); for (index, cipher) in cipher_data.iter().enumerate() { // Validate the note size and if it is exceeded return a warning if let Some(note) = &cipher.notes @@ -118,10 +119,8 @@ impl Cipher { { validation_errors.insert( format!("Ciphers[{index}].Notes"), - serde_json::to_value([ - "The password history contains a `null` value. Only strings are allowed.", - ]) - .unwrap(), + serde_json::to_value([crate::i18n::cipher_password_history_null_only_strings(&locale)]) + .unwrap(), ); break; } @@ -131,11 +130,11 @@ impl Cipher { if !validation_errors.is_empty() { let err_json = json!({ - "message": "The model state is invalid.", + "message": crate::i18n::cipher_model_state_invalid(&locale), "validationErrors" : validation_errors, "object": "error" }); - err_json!(err_json, "Import validation errors") + err_json!(err_json, crate::i18n::cipher_import_validation_errors(&locale)) } Ok(()) @@ -400,7 +399,10 @@ impl Cipher { 6 => "bankAccount", 7 => "driversLicense", 8 => "passport", - _ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)), + _ => err!( + crate::i18n::db_cipher_invalid_type(&CONFIG.default_locale()), + format!("{}, {}", self.uuid, self.atype) + ), }; json_object[key] = type_data_json; @@ -447,7 +449,7 @@ impl Cipher { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving cipher") + .map_res(crate::i18n::db_error_saving_cipher(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(ciphers::table) @@ -456,7 +458,7 @@ impl Cipher { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving cipher") + .map_res(crate::i18n::db_error_saving_cipher(&CONFIG.default_locale())) } } } @@ -472,7 +474,7 @@ impl Cipher { conn.run(move |conn| { diesel::delete(ciphers::table.filter(ciphers::uuid.eq(&self.uuid))) .execute(conn) - .map_res("Error deleting cipher") + .map_res(crate::i18n::db_error_deleting_cipher(&CONFIG.default_locale())) }) .await } @@ -543,7 +545,7 @@ impl Cipher { if let Some(old_folder) = FolderCipher::find_by_folder_and_cipher(&old_folder, &self.uuid, conn).await { old_folder.delete(conn).await } else { - err!("Couldn't move from previous folder") + err!(crate::i18n::cipher_couldnt_move_from_previous_folder(&CONFIG.default_locale())) } } diff --git a/src/db/models/collection.rs b/src/db/models/collection.rs index 21387e4d..7fb2a661 100644 --- a/src/db/models/collection.rs +++ b/src/db/models/collection.rs @@ -175,7 +175,7 @@ impl Collection { .do_update() .set(self) .execute(conn) - .map_res("Error saving collection") + .map_res(crate::i18n::db_error_saving_collection(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(collections::table) @@ -184,7 +184,7 @@ impl Collection { .do_update() .set(self) .execute(conn) - .map_res("Error saving collection") + .map_res(crate::i18n::db_error_saving_collection(&CONFIG.default_locale())) } } } @@ -198,7 +198,7 @@ impl Collection { conn.run(move |conn| { diesel::delete(collections::table.filter(collections::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error deleting collection") + .map_res(crate::i18n::db_error_deleting_collection(&CONFIG.default_locale())) }) .await } @@ -743,7 +743,7 @@ impl CollectionUser { .do_update() .set(values) .execute(conn) - .map_res("Error adding user to collection") + .map_res(crate::i18n::db_error_adding_user_to_collection(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(users_collections::table) @@ -752,7 +752,7 @@ impl CollectionUser { .do_update() .set(values) .execute(conn) - .map_res("Error adding user to collection") + .map_res(crate::i18n::db_error_adding_user_to_collection(&CONFIG.default_locale())) } } } @@ -767,7 +767,7 @@ impl CollectionUser { .filter(users_collections::collection_uuid.eq(&self.collection_uuid)), ) .execute(conn) - .map_res("Error removing user from collection") + .map_res(crate::i18n::db_error_removing_user_from_collection(&CONFIG.default_locale())) }) .await } @@ -853,7 +853,7 @@ impl CollectionUser { conn.run(move |conn| { diesel::delete(users_collections::table.filter(users_collections::collection_uuid.eq(collection_uuid))) .execute(conn) - .map_res("Error deleting users from collection") + .map_res(crate::i18n::db_error_deleting_users_from_collection(&CONFIG.default_locale())) }) .await } @@ -875,7 +875,7 @@ impl CollectionUser { ), ) .execute(conn) - .map_res("Error removing user from collections")?; + .map_res(crate::i18n::db_error_removing_user_from_collections(&CONFIG.default_locale()))?; } Ok(()) }) @@ -902,7 +902,7 @@ impl CollectionCipher { .on_conflict(diesel::dsl::DuplicatedKeys) .do_nothing() .execute(conn) - .map_res("Error adding cipher to collection") + .map_res(crate::i18n::db_error_adding_cipher_to_collection(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(ciphers_collections::table) @@ -913,7 +913,7 @@ impl CollectionCipher { .on_conflict((ciphers_collections::cipher_uuid, ciphers_collections::collection_uuid)) .do_nothing() .execute(conn) - .map_res("Error adding cipher to collection") + .map_res(crate::i18n::db_error_adding_cipher_to_collection(&CONFIG.default_locale())) } } } @@ -928,7 +928,7 @@ impl CollectionCipher { .filter(ciphers_collections::collection_uuid.eq(collection_uuid)), ) .execute(conn) - .map_res("Error deleting cipher from collection") + .map_res(crate::i18n::db_error_deleting_cipher_from_collection(&CONFIG.default_locale())) }) .await } @@ -937,7 +937,7 @@ impl CollectionCipher { conn.run(move |conn| { diesel::delete(ciphers_collections::table.filter(ciphers_collections::cipher_uuid.eq(cipher_uuid))) .execute(conn) - .map_res("Error removing cipher from collections") + .map_res(crate::i18n::db_error_removing_cipher_from_collections(&CONFIG.default_locale())) }) .await } @@ -946,7 +946,7 @@ impl CollectionCipher { conn.run(move |conn| { diesel::delete(ciphers_collections::table.filter(ciphers_collections::collection_uuid.eq(collection_uuid))) .execute(conn) - .map_res("Error removing ciphers from collection") + .map_res(crate::i18n::db_error_removing_ciphers_from_collection(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/device.rs b/src/db/models/device.rs index 5e5f1f97..b0889938 100644 --- a/src/db/models/device.rs +++ b/src/db/models/device.rs @@ -5,6 +5,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::EmptyResult, crypto, db::{DbConn, schema::devices}, @@ -155,7 +156,7 @@ impl Device { .set(&*self) .execute(conn), 10, - ).map_res("Error saving device") + ).map_res(crate::i18n::db_error_saving_device(&CONFIG.default_locale())) } postgresql, sqlite { crate::util::retry(|| @@ -166,7 +167,7 @@ impl Device { .set(&*self) .execute(conn), 10, - ).map_res("Error saving device") + ).map_res(crate::i18n::db_error_saving_device(&CONFIG.default_locale())) } } } @@ -175,7 +176,7 @@ impl Device { conn.run(move |conn| { diesel::delete(devices::table.filter(devices::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error removing devices for user") + .map_res(crate::i18n::db_error_removing_devices_for_user(&CONFIG.default_locale())) }) .await } @@ -218,7 +219,7 @@ impl Device { .filter(devices::uuid.eq(uuid)) .set(devices::push_token.eq::>(None)) .execute(conn) - .map_res("Error removing push token") + .map_res(crate::i18n::db_error_removing_push_token(&CONFIG.default_locale())) }) .await } @@ -281,7 +282,7 @@ impl Device { .filter(devices::user_uuid.eq(user_uuid)) .set(devices::twofactor_remember.eq::>(None)) .execute(conn) - .map_res("Error removing two factor remember tokens") + .map_res(crate::i18n::db_error_removing_twofactor_remember_tokens(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/emergency_access.rs b/src/db/models/emergency_access.rs index 02c05d5e..fab9dbbc 100644 --- a/src/db/models/emergency_access.rs +++ b/src/db/models/emergency_access.rs @@ -4,6 +4,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::EmptyResult, db::{DbConn, schema::emergency_access}, error::MapResult, @@ -115,14 +116,16 @@ impl EmergencyAccess { pub fn deadline_at(&self) -> Result { if !(EMERGENCY_ACCESS_TIMEOUT_RANGE).contains(&self.wait_time_days) { - err!("Emergency access wait time is out-of-bounds!") + err!(crate::i18n::emergency_access_wait_time_out_of_bounds(&CONFIG.default_locale())) } - let initiated_at = self.recovery_initiated_at.map_res("Emergency access initiation date missing!")?; + let initiated_at = self + .recovery_initiated_at + .map_res(crate::i18n::db_emergency_access_initiation_date_missing(&CONFIG.default_locale()))?; TimeDelta::try_days(i64::from(self.wait_time_days)) .and_then(|w| initiated_at.checked_add_signed(w)) - .map_res("Emergency access deadline is invalid") + .map_res(crate::i18n::db_emergency_access_deadline_invalid(&CONFIG.default_locale())) } pub fn is_recovery_allowed(&self, now: &NaiveDateTime) -> Result { @@ -171,7 +174,7 @@ impl EmergencyAccess { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving emergency access") + .map_res(crate::i18n::db_error_saving_emergency_access(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(emergency_access::table) @@ -180,7 +183,7 @@ impl EmergencyAccess { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving emergency access") + .map_res(crate::i18n::db_error_saving_emergency_access(&CONFIG.default_locale())) } } } @@ -213,8 +216,10 @@ impl EmergencyAccess { match res { Ok(1) => {} // One record updated, which is valid - Ok(_) => err!("Emergency access status was changed already"), - Err(e) => err!("Error updating emergency access status", format!("{e}")), + Ok(_) => err!(crate::i18n::emergency_access_status_changed_already(&CONFIG.default_locale())), + Err(e) => { + err!(crate::i18n::emergency_access_error_updating_status(&CONFIG.default_locale()), format!("{e}")) + } } self.status = to_status; @@ -238,7 +243,7 @@ impl EmergencyAccess { }, 10, ) - .map_res("Error updating emergency access status") + .map_res(crate::i18n::db_error_updating_emergency_access_status(&CONFIG.default_locale())) }) .await } @@ -266,7 +271,7 @@ impl EmergencyAccess { conn.run(move |conn| { diesel::delete(emergency_access::table.filter(emergency_access::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error removing user from emergency access") + .map_res(crate::i18n::db_error_removing_user_from_emergency_access(&CONFIG.default_locale())) }) .await } @@ -398,11 +403,11 @@ impl EmergencyAccess { pub async fn accept_invite(&mut self, grantee_uuid: &UserId, grantee_email: &str, conn: &DbConn) -> EmptyResult { if self.email.is_none() || self.email.as_ref().unwrap() != grantee_email { - err!("User email does not match invite."); + err!(crate::i18n::emergency_access_user_email_mismatch_invite(&CONFIG.default_locale())); } if self.status == EmergencyAccessStatus::Accepted as i32 { - err!("Emergency contact already accepted."); + err!(crate::i18n::emergency_access_contact_already_accepted(&CONFIG.default_locale())); } self.status = EmergencyAccessStatus::Accepted as i32; diff --git a/src/db/models/event.rs b/src/db/models/event.rs index 8dc3a5ad..1c11e991 100644 --- a/src/db/models/event.rs +++ b/src/db/models/event.rs @@ -215,7 +215,7 @@ impl Event { .do_update() .set(self) .execute(conn) - .map_res("Error saving event") + .map_res(crate::i18n::db_error_saving_event(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(event::table) @@ -224,7 +224,7 @@ impl Event { .do_update() .set(self) .execute(conn) - .map_res("Error saving event") + .map_res(crate::i18n::db_error_saving_event(&CONFIG.default_locale())) } } } @@ -266,7 +266,9 @@ impl Event { pub async fn delete(self, conn: &DbConn) -> EmptyResult { conn.run(move |conn| { - diesel::delete(event::table.filter(event::uuid.eq(self.uuid))).execute(conn).map_res("Error deleting event") + diesel::delete(event::table.filter(event::uuid.eq(self.uuid))) + .execute(conn) + .map_res(crate::i18n::db_error_deleting_event(&CONFIG.default_locale())) }) .await } @@ -352,16 +354,16 @@ impl Event { }; let Some(days_to_retain) = TimeDelta::try_days(i64::from(days_to_retain)) else { - err!("Unable to calculate the event retention date, check 'EVENTS_DAYS_RETAIN'") + err!(crate::i18n::api_event_retention_date_calculation_failed(&CONFIG.default_locale())) }; let Some(dt) = Utc::now().naive_utc().checked_sub_signed(days_to_retain) else { - err!("Unable to calculate the event retention date, check 'EVENTS_DAYS_RETAIN'") + err!(crate::i18n::api_event_retention_date_calculation_failed(&CONFIG.default_locale())) }; conn.run(move |conn| { diesel::delete(event::table.filter(event::event_date.lt(dt))) .execute(conn) - .map_res("Error cleaning old events") + .map_res(crate::i18n::db_error_cleaning_old_events(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/favorite.rs b/src/db/models/favorite.rs index ee79857a..8f359374 100644 --- a/src/db/models/favorite.rs +++ b/src/db/models/favorite.rs @@ -1,6 +1,7 @@ use diesel::prelude::*; use crate::{ + CONFIG, api::EmptyResult, db::{DbConn, schema::favorites}, error::MapResult, @@ -45,7 +46,7 @@ impl Favorite { diesel::insert_into(favorites::table) .values((favorites::user_uuid.eq(user_uuid), favorites::cipher_uuid.eq(cipher_uuid))) .execute(conn) - .map_res("Error adding favorite") + .map_res(crate::i18n::db_error_adding_favorite(&CONFIG.default_locale())) }) .await } @@ -58,7 +59,7 @@ impl Favorite { .filter(favorites::cipher_uuid.eq(cipher_uuid)), ) .execute(conn) - .map_res("Error removing favorite") + .map_res(crate::i18n::db_error_removing_favorite(&CONFIG.default_locale())) }) .await } @@ -72,7 +73,7 @@ impl Favorite { conn.run(move |conn| { diesel::delete(favorites::table.filter(favorites::cipher_uuid.eq(cipher_uuid))) .execute(conn) - .map_res("Error removing favorites by cipher") + .map_res(crate::i18n::db_error_removing_favorites_by_cipher(&CONFIG.default_locale())) }) .await } @@ -82,7 +83,7 @@ impl Favorite { conn.run(move |conn| { diesel::delete(favorites::table.filter(favorites::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error removing favorites by user") + .map_res(crate::i18n::db_error_removing_favorites_by_user(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/folder.rs b/src/db/models/folder.rs index adbe993f..d7ad26b0 100644 --- a/src/db/models/folder.rs +++ b/src/db/models/folder.rs @@ -4,6 +4,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::EmptyResult, db::{ DbConn, @@ -84,7 +85,7 @@ impl Folder { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving folder") + .map_res(crate::i18n::db_error_saving_folder(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(folders::table) @@ -93,7 +94,7 @@ impl Folder { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving folder") + .map_res(crate::i18n::db_error_saving_folder(&CONFIG.default_locale())) } } } @@ -105,7 +106,7 @@ impl Folder { conn.run(move |conn| { diesel::delete(folders::table.filter(folders::uuid.eq(&self.uuid))) .execute(conn) - .map_res("Error deleting folder") + .map_res(crate::i18n::db_error_deleting_folder(&CONFIG.default_locale())) }) .await } @@ -145,7 +146,7 @@ impl FolderCipher { .on_conflict(diesel::dsl::DuplicatedKeys) .do_nothing() .execute(conn) - .map_res("Error adding cipher to folder") + .map_res(crate::i18n::db_error_adding_cipher_to_folder(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(folders_ciphers::table) @@ -153,7 +154,7 @@ impl FolderCipher { .on_conflict((folders_ciphers::cipher_uuid, folders_ciphers::folder_uuid)) .do_nothing() .execute(conn) - .map_res("Error adding cipher to folder") + .map_res(crate::i18n::db_error_adding_cipher_to_folder(&CONFIG.default_locale())) } } } @@ -166,7 +167,7 @@ impl FolderCipher { .filter(folders_ciphers::folder_uuid.eq(self.folder_uuid)), ) .execute(conn) - .map_res("Error removing cipher from folder") + .map_res(crate::i18n::db_error_removing_cipher_from_folder(&CONFIG.default_locale())) }) .await } @@ -175,7 +176,7 @@ impl FolderCipher { conn.run(move |conn| { diesel::delete(folders_ciphers::table.filter(folders_ciphers::cipher_uuid.eq(cipher_uuid))) .execute(conn) - .map_res("Error removing cipher from folders") + .map_res(crate::i18n::db_error_removing_cipher_from_folders(&CONFIG.default_locale())) }) .await } @@ -184,7 +185,7 @@ impl FolderCipher { conn.run(move |conn| { diesel::delete(folders_ciphers::table.filter(folders_ciphers::folder_uuid.eq(folder_uuid))) .execute(conn) - .map_res("Error removing ciphers from folder") + .map_res(crate::i18n::db_error_removing_ciphers_from_folder(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/group.rs b/src/db/models/group.rs index c8df7ef2..223d217b 100644 --- a/src/db/models/group.rs +++ b/src/db/models/group.rs @@ -4,6 +4,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::EmptyResult, db::{ DbConn, @@ -172,7 +173,7 @@ impl Group { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving group") + .map_res(crate::i18n::db_error_saving_group(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(groups::table) @@ -181,7 +182,7 @@ impl Group { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving group") + .map_res(crate::i18n::db_error_saving_group(&CONFIG.default_locale())) } } } @@ -287,7 +288,7 @@ impl Group { conn.run(move |conn| { diesel::delete(groups::table.filter(groups::uuid.eq(&self.uuid))) .execute(conn) - .map_res("Error deleting group") + .map_res(crate::i18n::db_error_deleting_group(&CONFIG.default_locale())) }) .await } @@ -308,7 +309,7 @@ impl Group { }, 10, ) - .map_res("Error updating group revision") + .map_res(crate::i18n::db_error_updating_group_revision(&CONFIG.default_locale())) }) .await } @@ -337,7 +338,7 @@ impl CollectionGroup { .do_update() .set(values) .execute(conn) - .map_res("Error adding group to collection") + .map_res(crate::i18n::db_error_adding_group_to_collection(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(collections_groups::table) @@ -346,7 +347,7 @@ impl CollectionGroup { .do_update() .set(values) .execute(conn) - .map_res("Error adding group to collection") + .map_res(crate::i18n::db_error_adding_group_to_collection(&CONFIG.default_locale())) } } } @@ -423,7 +424,7 @@ impl CollectionGroup { .filter(collections_groups::collections_uuid.eq(&self.collections_uuid)) .filter(collections_groups::groups_uuid.eq(&self.groups_uuid)) .execute(conn) - .map_res("Error deleting collection group") + .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale())) }) .await } @@ -438,7 +439,7 @@ impl CollectionGroup { diesel::delete(collections_groups::table) .filter(collections_groups::groups_uuid.eq(group_uuid)) .execute(conn) - .map_res("Error deleting collection group") + .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale())) }) .await } @@ -460,7 +461,7 @@ impl CollectionGroup { diesel::delete(collections_groups::table) .filter(collections_groups::collections_uuid.eq(collection_uuid)) .execute(conn) - .map_res("Error deleting collection group") + .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale())) }) .await } @@ -482,7 +483,7 @@ impl GroupUser { .on_conflict(diesel::dsl::DuplicatedKeys) .do_nothing() .execute(conn) - .map_res("Error adding user to group") + .map_res(crate::i18n::db_error_adding_user_to_group(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(groups_users::table) @@ -490,7 +491,7 @@ impl GroupUser { .on_conflict((groups_users::users_organizations_uuid, groups_users::groups_uuid)) .do_nothing() .execute(conn) - .map_res("Error adding user to group") + .map_res(crate::i18n::db_error_adding_user_to_group(&CONFIG.default_locale())) } } } @@ -583,7 +584,7 @@ impl GroupUser { diesel::delete(groups_users::table) .filter(groups_users::groups_uuid.eq(group_uuid)) .execute(conn) - .map_res("Error deleting group users") + .map_res(crate::i18n::db_error_deleting_group_users(&CONFIG.default_locale())) }) .await } @@ -598,7 +599,7 @@ impl GroupUser { diesel::delete(groups_users::table) .filter(groups_users::users_organizations_uuid.eq(member_uuid)) .execute(conn) - .map_res("Error deleting user groups") + .map_res(crate::i18n::db_error_deleting_user_groups(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/org_policy.rs b/src/db/models/org_policy.rs index 554f51fc..c651d3dc 100644 --- a/src/db/models/org_policy.rs +++ b/src/db/models/org_policy.rs @@ -140,10 +140,10 @@ impl OrgPolicy { .filter(org_policies::uuid.eq(&self.uuid)) .set(&*self) .execute(conn) - .map_res("Error saving org_policy") + .map_res(crate::i18n::db_error_saving_org_policy(&CONFIG.default_locale())) } Err(e) => Err(e.into()), - }.map_res("Error saving org_policy") + }.map_res(crate::i18n::db_error_saving_org_policy(&CONFIG.default_locale())) } postgresql { // We need to make sure we're not going to violate the unique constraint on org_uuid and atype. @@ -155,7 +155,7 @@ impl OrgPolicy { .filter(org_policies::atype.eq(&self.atype)), ) .execute(conn) - .map_res("Error deleting org_policy for insert")?; + .map_res(crate::i18n::db_error_deleting_org_policy_for_insert(&CONFIG.default_locale()))?; diesel::insert_into(org_policies::table) .values(&*self) @@ -163,7 +163,7 @@ impl OrgPolicy { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving org_policy") + .map_res(crate::i18n::db_error_saving_org_policy(&CONFIG.default_locale())) } } } @@ -172,7 +172,7 @@ impl OrgPolicy { conn.run(move |conn| { diesel::delete(org_policies::table.filter(org_policies::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error deleting org_policy") + .map_res(crate::i18n::db_error_deleting_org_policy(&CONFIG.default_locale())) }) .await } @@ -242,7 +242,7 @@ impl OrgPolicy { conn.run(move |conn| { diesel::delete(org_policies::table.filter(org_policies::org_uuid.eq(org_uuid))) .execute(conn) - .map_res("Error deleting org_policy") + .map_res(crate::i18n::db_error_deleting_org_policy(&CONFIG.default_locale())) }) .await } @@ -328,26 +328,30 @@ impl OrgPolicy { if CONFIG.email_2fa_auto_fallback() { two_factor::email::find_and_activate_email_2fa(&m.user_uuid, conn).await?; } else { - err!(format!("Cannot {} because 2FA is required (membership {})", action, m.uuid)); + err!( + crate::i18n::org_policy_cannot_because_2fa_required(&CONFIG.default_locale()), + format!("{}, {}", action, m.uuid) + ); } } // Check if the user is part of another Organization with SingleOrg activated if Self::is_applicable_to_user(&m.user_uuid, OrgPolicyType::SingleOrg, Some(&m.org_uuid), conn).await { - err!(format!( - "Cannot {} because another organization policy forbids it (membership {})", - action, m.uuid - )); + err!( + crate::i18n::org_policy_cannot_because_other_org_policy_forbids(&CONFIG.default_locale()), + format!("{}, {}", action, m.uuid) + ); } if let Some(p) = Self::find_by_org_and_type(&m.org_uuid, OrgPolicyType::SingleOrg, conn).await && p.enabled && Membership::count_accepted_and_confirmed_by_user(&m.user_uuid, &m.org_uuid, conn).await > 0 { - err!(format!( + let msg = format!( "Cannot {} because the organization policy forbids being part of other organization (membership {})", action, m.uuid - )); + ); + err!(msg); } } diff --git a/src/db/models/organization.rs b/src/db/models/organization.rs index 25d03dfc..6d0deaed 100644 --- a/src/db/models/organization.rs +++ b/src/db/models/organization.rs @@ -342,7 +342,10 @@ impl OrganizationApiKey { impl Organization { pub async fn save(&self, conn: &DbConn) -> EmptyResult { if !crate::util::is_valid_email(&self.billing_email) { - err!(format!("BillingEmail {} is not a valid email address", self.billing_email.escape_debug())) + err!( + crate::i18n::db_billing_email_not_valid(&CONFIG.default_locale()), + self.billing_email.escape_debug().to_string() + ) } for member in &Membership::find_by_org(&self.uuid, conn).await { @@ -357,7 +360,7 @@ impl Organization { .do_update() .set(self) .execute(conn) - .map_res("Error saving organization") + .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(organizations::table) @@ -366,7 +369,7 @@ impl Organization { .do_update() .set(self) .execute(conn) - .map_res("Error saving organization") + .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale())) } } } @@ -382,7 +385,7 @@ impl Organization { conn.run(move |conn| { diesel::delete(organizations::table.filter(organizations::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error saving organization") + .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale())) }) .await } @@ -722,7 +725,7 @@ impl Membership { .do_update() .set(self) .execute(conn) - .map_res("Error adding user to organization") + .map_res(crate::i18n::db_error_adding_user_to_organization(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(users_organizations::table) @@ -731,7 +734,7 @@ impl Membership { .do_update() .set(self) .execute(conn) - .map_res("Error adding user to organization") + .map_res(crate::i18n::db_error_adding_user_to_organization(&CONFIG.default_locale())) } } } @@ -745,7 +748,7 @@ impl Membership { conn.run(move |conn| { diesel::delete(users_organizations::table.filter(users_organizations::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error removing user from organization") + .map_res(crate::i18n::db_error_removing_user_from_organization(&CONFIG.default_locale())) }) .await } @@ -850,7 +853,7 @@ impl Membership { .filter(users_organizations::status.eq(MembershipStatus::Invited as i32)) .set(users_organizations::status.eq(MembershipStatus::Accepted as i32)) .execute(conn) - .map_res("Error confirming invitations") + .map_res(crate::i18n::db_error_confirming_invitations(&CONFIG.default_locale())) }) .await } @@ -1154,7 +1157,7 @@ impl OrganizationApiKey { .do_update() .set(self) .execute(conn) - .map_res("Error saving organization") + .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(organization_api_key::table) @@ -1163,7 +1166,7 @@ impl OrganizationApiKey { .do_update() .set(self) .execute(conn) - .map_res("Error saving organization") + .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale())) } } } @@ -1179,7 +1182,9 @@ impl OrganizationApiKey { conn.run(move |conn| { diesel::delete(organization_api_key::table.filter(organization_api_key::org_uuid.eq(org_uuid))) .execute(conn) - .map_res("Error removing organization api key from organization") + .map_res(crate::i18n::db_error_removing_organization_api_key_from_organization( + &CONFIG.default_locale(), + )) }) .await } diff --git a/src/db/models/send.rs b/src/db/models/send.rs index 721378f3..787b942e 100644 --- a/src/db/models/send.rs +++ b/src/db/models/send.rs @@ -213,7 +213,7 @@ impl Send { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving send") + .map_res(crate::i18n::db_error_saving_send(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(sends::table) @@ -222,7 +222,7 @@ impl Send { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving send") + .map_res(crate::i18n::db_error_saving_send(&CONFIG.default_locale())) } } } @@ -283,7 +283,9 @@ impl Send { } conn.run(move |conn| { - diesel::delete(sends::table.filter(sends::uuid.eq(&self.uuid))).execute(conn).map_res("Error deleting send") + diesel::delete(sends::table.filter(sends::uuid.eq(&self.uuid))) + .execute(conn) + .map_res(crate::i18n::db_error_deleting_send(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/sso_auth.rs b/src/db/models/sso_auth.rs index 311e9bf9..5612b29a 100644 --- a/src/db/models/sso_auth.rs +++ b/src/db/models/sso_auth.rs @@ -10,6 +10,7 @@ use diesel::{ }; use crate::{ + CONFIG, api::EmptyResult, db::{DbConn, DbPool, schema::sso_auth}, error::MapResult, @@ -93,7 +94,7 @@ impl SsoAuth { .do_update() .set(self) .execute(conn) - .map_res("Error saving SSO auth") + .map_res(crate::i18n::db_error_saving_sso_auth(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(sso_auth::table) @@ -102,7 +103,7 @@ impl SsoAuth { .do_update() .set(self) .execute(conn) - .map_res("Error saving SSO auth") + .map_res(crate::i18n::db_error_saving_sso_auth(&CONFIG.default_locale())) } } } @@ -134,7 +135,7 @@ impl SsoAuth { conn.run(move |conn| { diesel::delete(sso_auth::table.filter(sso_auth::state.eq(self.state))) .execute(conn) - .map_res("Error deleting sso_auth") + .map_res(crate::i18n::db_error_deleting_sso_auth(&CONFIG.default_locale())) }) .await } @@ -146,11 +147,11 @@ impl SsoAuth { conn.run(move |conn| { diesel::delete(sso_auth::table.filter(sso_auth::created_at.lt(oldest))) .execute(conn) - .map_res("Error deleting expired SSO nonce") + .map_res(crate::i18n::db_error_deleting_expired_sso_nonce(&CONFIG.default_locale())) }) .await } else { - err!("Failed to get DB connection while purging expired sso_auth") + err!(crate::i18n::api_failed_get_db_connection_purging_expired_sso_auth(&CONFIG.default_locale())) } } } diff --git a/src/db/models/two_factor.rs b/src/db/models/two_factor.rs index 051ea4df..89fa4d6e 100644 --- a/src/db/models/two_factor.rs +++ b/src/db/models/two_factor.rs @@ -5,6 +5,7 @@ use webauthn_rs_core::proto::CredentialV3; use webauthn_rs_proto::{AttestationFormat, RegisteredExtensions}; use crate::{ + CONFIG, api::{EmptyResult, core::two_factor::webauthn::WebauthnRegistration}, db::{DbConn, schema::twofactor}, error::MapResult, @@ -93,10 +94,10 @@ impl TwoFactor { .filter(twofactor::uuid.eq(&self.uuid)) .set(self) .execute(conn) - .map_res("Error saving twofactor") + .map_res(crate::i18n::db_error_saving_twofactor(&CONFIG.default_locale())) } Err(e) => Err(e.into()), - }.map_res("Error saving twofactor") + }.map_res(crate::i18n::db_error_saving_twofactor(&CONFIG.default_locale())) } postgresql { // We need to make sure we're not going to violate the unique constraint on user_uuid and atype. @@ -104,7 +105,7 @@ impl TwoFactor { // not support multiple constraints on ON CONFLICT clauses. let _: () = diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(&self.user_uuid)).filter(twofactor::atype.eq(&self.atype))) .execute(conn) - .map_res("Error deleting twofactor for insert")?; + .map_res(crate::i18n::db_error_deleting_twofactor_for_insert(&CONFIG.default_locale()))?; diesel::insert_into(twofactor::table) .values(self) @@ -112,7 +113,7 @@ impl TwoFactor { .do_update() .set(self) .execute(conn) - .map_res("Error saving twofactor") + .map_res(crate::i18n::db_error_saving_twofactor(&CONFIG.default_locale())) } } } @@ -121,7 +122,7 @@ impl TwoFactor { conn.run(move |conn| { diesel::delete(twofactor::table.filter(twofactor::uuid.eq(self.uuid))) .execute(conn) - .map_res("Error deleting twofactor") + .map_res(crate::i18n::db_error_deleting_twofactor(&CONFIG.default_locale())) }) .await } @@ -152,7 +153,7 @@ impl TwoFactor { conn.run(move |conn| { diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error deleting twofactors") + .map_res(crate::i18n::db_error_deleting_twofactors(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/two_factor_duo_context.rs b/src/db/models/two_factor_duo_context.rs index 1a4ae266..7ebfd9d5 100644 --- a/src/db/models/two_factor_duo_context.rs +++ b/src/db/models/two_factor_duo_context.rs @@ -2,6 +2,7 @@ use chrono::Utc; use diesel::prelude::*; use crate::{ + CONFIG, api::EmptyResult, db::{DbConn, schema::twofactor_duo_ctx}, error::MapResult, @@ -43,7 +44,7 @@ impl TwoFactorDuoContext { twofactor_duo_ctx::exp.eq(exp), )) .execute(conn) - .map_res("Error saving context to twofactor_duo_ctx") + .map_res(crate::i18n::db_error_saving_context_twofactor_duo_ctx(&CONFIG.default_locale())) }) .await } @@ -63,7 +64,7 @@ impl TwoFactorDuoContext { conn.run(move |conn| { diesel::delete(twofactor_duo_ctx::table.filter(twofactor_duo_ctx::state.eq(&self.state))) .execute(conn) - .map_res("Error deleting from twofactor_duo_ctx") + .map_res(crate::i18n::db_error_deleting_from_twofactor_duo_ctx(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/two_factor_incomplete.rs b/src/db/models/two_factor_incomplete.rs index e4c7e308..752fcffa 100644 --- a/src/db/models/two_factor_incomplete.rs +++ b/src/db/models/two_factor_incomplete.rs @@ -60,7 +60,7 @@ impl TwoFactorIncomplete { twofactor_incomplete::ip_address.eq(ip.ip.to_string()), )) .execute(conn) - .map_res("Error adding twofactor_incomplete record") + .map_res(crate::i18n::db_error_adding_twofactor_incomplete_record(&CONFIG.default_locale())) }) .await } @@ -106,7 +106,7 @@ impl TwoFactorIncomplete { .filter(twofactor_incomplete::device_uuid.eq(device_uuid)), ) .execute(conn) - .map_res("Error in twofactor_incomplete::delete_by_user_and_device()") + .map_res(crate::i18n::db_error_delete_by_user_and_device_twofactor_incomplete(&CONFIG.default_locale())) }) .await } @@ -115,7 +115,7 @@ impl TwoFactorIncomplete { conn.run(move |conn| { diesel::delete(twofactor_incomplete::table.filter(twofactor_incomplete::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error in twofactor_incomplete::delete_all_by_user()") + .map_res(crate::i18n::db_error_delete_all_by_user_twofactor_incomplete(&CONFIG.default_locale())) }) .await } diff --git a/src/db/models/user.rs b/src/db/models/user.rs index 30541428..dc6a8525 100644 --- a/src/db/models/user.rs +++ b/src/db/models/user.rs @@ -70,6 +70,7 @@ pub struct User { pub avatar_color: Option, pub external_id: Option, // Todo: Needs to be removed in the future, this is not used anymore. + pub locale: Option, pub key_id: Option, } @@ -157,6 +158,7 @@ impl User { avatar_color: None, external_id: None, // Todo: Needs to be removed in the future, this is not used anymore. + locale: None, key_id: None, } @@ -316,7 +318,10 @@ impl User { "emailVerified": self.verified(), "premium": true, "premiumFromOrganization": false, - "culture": "en-US", + "culture": self + .locale + .as_deref() + .map_or_else(|| "en-US".to_owned(), crate::i18n::to_client_culture), "twoFactorEnabled": twofactor_enabled, "key": self.akey, "privateKey": self.private_key, @@ -335,7 +340,7 @@ impl User { pub async fn save(&mut self, conn: &DbConn) -> EmptyResult { if !crate::util::is_valid_email(&self.email) { - err!(format!("User email {} is not a valid email address", self.email.escape_debug())) + err!(crate::i18n::db_user_email_not_valid(&CONFIG.default_locale()), self.email.escape_debug().to_string()) } self.updated_at = Utc::now().naive_utc(); @@ -348,7 +353,7 @@ impl User { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving user") + .map_res(crate::i18n::db_error_saving_user(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(users::table) // Insert or update @@ -357,7 +362,7 @@ impl User { .do_update() .set(&*self) .execute(conn) - .map_res("Error saving user") + .map_res(crate::i18n::db_error_saving_user(&CONFIG.default_locale())) } } } @@ -367,7 +372,7 @@ impl User { if member.atype == MembershipType::Owner && Membership::count_confirmed_by_org_and_type(&member.org_uuid, MembershipType::Owner, conn).await <= 1 { - err!("Can't delete last owner") + err!(crate::i18n::org_cannot_delete_last_owner(&CONFIG.default_locale())) } } @@ -385,7 +390,9 @@ impl User { Invitation::take(&self.email, conn).await; // Delete invitation if any conn.run(move |conn| { - diesel::delete(users::table.filter(users::uuid.eq(&self.uuid))).execute(conn).map_res("Error deleting user") + diesel::delete(users::table.filter(users::uuid.eq(self.uuid))) + .execute(conn) + .map_res(crate::i18n::db_error_deleting_user(&CONFIG.default_locale())) }) .await } @@ -401,7 +408,7 @@ impl User { conn.run(move |conn| { retry(|| diesel::update(users::table).set(users::updated_at.eq(updated_at)).execute(conn), 10) - .map_res("Error updating revision date for all users") + .map_res(crate::i18n::db_error_updating_revision_date_for_all_users(&CONFIG.default_locale())) }) .await } @@ -422,7 +429,7 @@ impl User { }, 10, ) - .map_res("Error updating user revision") + .map_res(crate::i18n::db_error_updating_user_revision(&CONFIG.default_locale())) }) .await } @@ -484,7 +491,10 @@ impl Invitation { pub async fn save(&self, conn: &DbConn) -> EmptyResult { if !crate::util::is_valid_email(&self.email) { - err!(format!("Invitation email {} is not a valid email address", self.email.escape_debug())) + err!( + crate::i18n::db_invitation_email_not_valid(&CONFIG.default_locale()), + self.email.escape_debug().to_string() + ) } db_run! { conn: @@ -496,7 +506,7 @@ impl Invitation { .on_conflict(diesel::dsl::DuplicatedKeys) .do_nothing() .execute(conn) - .map_res("Error saving invitation") + .map_res(crate::i18n::db_error_saving_invitation(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(invitations::table) @@ -504,7 +514,7 @@ impl Invitation { .on_conflict(invitations::email) .do_nothing() .execute(conn) - .map_res("Error saving invitation") + .map_res(crate::i18n::db_error_saving_invitation(&CONFIG.default_locale())) } } } @@ -513,7 +523,7 @@ impl Invitation { conn.run(move |conn| { diesel::delete(invitations::table.filter(invitations::email.eq(self.email))) .execute(conn) - .map_res("Error deleting invitation") + .map_res(crate::i18n::db_error_deleting_invitation(&CONFIG.default_locale())) }) .await } @@ -579,13 +589,13 @@ impl SsoUser { diesel::insert_into(sso_users::table) .values(self) .execute(conn) - .map_res("Error saving SSO user") + .map_res(crate::i18n::db_error_saving_sso_user(&CONFIG.default_locale())) } postgresql, sqlite { diesel::insert_into(sso_users::table) .values(self) .execute(conn) - .map_res("Error saving SSO user") + .map_res(crate::i18n::db_error_saving_sso_user(&CONFIG.default_locale())) } } } @@ -620,7 +630,7 @@ impl SsoUser { conn.run(move |conn| { diesel::delete(sso_users::table.filter(sso_users::user_uuid.eq(user_uuid))) .execute(conn) - .map_res("Error deleting sso user") + .map_res(crate::i18n::db_error_deleting_sso_user(&CONFIG.default_locale())) }) .await } diff --git a/src/db/schema.rs b/src/db/schema.rs index ae1e3216..6fa3c616 100644 --- a/src/db/schema.rs +++ b/src/db/schema.rs @@ -218,6 +218,7 @@ table! { api_key -> Nullable, avatar_color -> Nullable, external_id -> Nullable, + locale -> Nullable, key_id -> Nullable, } } diff --git a/src/http_client.rs b/src/http_client.rs index 6225e233..61f04654 100644 --- a/src/http_client.rs +++ b/src/http_client.rs @@ -24,10 +24,10 @@ pub fn make_http_request(method: reqwest::Method, url: &str) -> Result; +type LocaleCatalog = HashMap; + +static LOCALE_CATALOG: LazyLock = LazyLock::new(load_locale_catalog); +static BUILTIN_LOCALE_CATALOG: LazyLock = LazyLock::new(load_builtin_catalog); +static BUILTIN_LOCALES_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/static/locales"); + +fn key_is_locale_scoped(key: &str) -> bool { + key.starts_with("admin.") || key.starts_with("tpl.") +} + +fn lookup_en<'a>(catalog: &'a LocaleCatalog, key: &str) -> Option<&'a str> { + catalog.get("en").and_then(|m| m.get(key)).map(String::as_str) +} + +pub fn normalize_locale(raw: &str) -> String { + let normalized = raw.trim().replace('_', "-").to_ascii_lowercase(); + if normalized.is_empty() { + "en".to_owned() + } else { + normalized + } +} + +pub fn locale_candidates(default_locale: &str) -> Vec { + let locale = normalize_locale(default_locale); + + let mut candidates = vec![locale.clone()]; + if let Some((lang, _)) = locale.split_once('-') + && !lang.is_empty() + && !candidates.iter().any(|x| x == lang) + { + candidates.push(lang.to_owned()); + } + + if !candidates.iter().any(|x| x == "en") { + candidates.push("en".to_owned()); + } + + candidates +} + +pub fn preferred_from_accept_language(raw: &str) -> Option { + let first = raw.split(',').next()?.trim(); + let locale = first.split(';').next()?.trim(); + if locale.is_empty() || locale == "*" { + None + } else { + Some(normalize_locale(locale)) + } +} + +pub fn resolve_locale(user_locale: Option<&str>, accept_language: Option<&str>, default_locale: &str) -> String { + if let Some(locale) = user_locale.map(normalize_locale).filter(|l| !l.is_empty()) { + return locale; + } + + if let Some(raw_accept) = accept_language + && let Some(locale) = preferred_from_accept_language(raw_accept) + { + return locale; + } + + normalize_locale(default_locale) +} + +pub fn to_client_culture(locale: &str) -> String { + let normalized = normalize_locale(locale); + if let Some((lang, region)) = normalized.split_once('-') { + format!("{}-{}", lang, region.to_ascii_uppercase()) + } else { + normalized + } +} + +pub fn is_russian(locale: &str) -> bool { + locale_candidates(locale).iter().any(|c| c == "ru") +} + +fn parse_locale_map(raw: &str) -> LocaleMap { + serde_json::from_str(raw).unwrap_or_default() +} + +fn merge_locale_map(target: &mut LocaleMap, raw: &str) { + target.extend(parse_locale_map(raw)); +} + +fn load_locale_file(path: &Path) -> Option { + let content = fs::read_to_string(path).ok()?; + Some(parse_locale_map(&content)) +} + +fn load_locale_dir(path: &Path) -> Option { + let mut files = fs::read_dir(path).ok()?.flatten().map(|e| e.path()).collect::>(); + files.sort(); + + let mut merged = LocaleMap::new(); + let mut found_json = false; + + for file in files { + if file.extension().and_then(|ext| ext.to_str()) != Some("json") { + continue; + } + + if let Some(loaded) = load_locale_file(&file) { + found_json = true; + merged.extend(loaded); + } + } + + found_json.then_some(merged) +} + +fn load_builtin_catalog() -> LocaleCatalog { + let mut catalog = LocaleCatalog::new(); + + let mut locale_dirs = BUILTIN_LOCALES_DIR.dirs().collect::>(); + locale_dirs.sort_by_key(|dir| dir.path().to_string_lossy().to_string()); + + for locale_dir in locale_dirs { + let Some(locale_name) = locale_dir.path().file_name().and_then(|name| name.to_str()) else { + continue; + }; + + let mut files = locale_dir.files().collect::>(); + files.sort_by_key(|file| file.path().to_string_lossy().to_string()); + + let mut merged = LocaleMap::new(); + let mut found_json = false; + + for file in files { + if file.path().extension().and_then(|ext| ext.to_str()) != Some("json") { + continue; + } + + if let Some(raw) = file.contents_utf8() { + found_json = true; + merge_locale_map(&mut merged, raw); + } + } + + if found_json { + catalog.insert(normalize_locale(locale_name), merged); + } + } + + catalog +} + +fn load_runtime_catalog_extensions(catalog: &mut LocaleCatalog) { + let locales_dir = storage::join_path(&CONFIG.data_folder(), "locales"); + let Ok(entries) = fs::read_dir(&locales_dir) else { + return; + }; + + let mut paths = entries.flatten().map(|e| e.path()).collect::>(); + paths.sort(); + + for path in paths { + if path.is_dir() { + let Some(locale_name) = path.file_name().and_then(|s| s.to_str()) else { + continue; + }; + + let locale = normalize_locale(locale_name); + if let Some(loaded) = load_locale_dir(&path) { + catalog.entry(locale).or_default().extend(loaded); + } + continue; + } + + if path.extension().and_then(|ext| ext.to_str()) != Some("json") { + continue; + } + + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + + let locale = normalize_locale(stem); + if let Some(loaded) = load_locale_file(&path) { + catalog.entry(locale).or_default().extend(loaded); + } + } +} + +fn load_locale_catalog() -> LocaleCatalog { + // Built-ins define the baseline fallback catalogs bundled with the binary. + let mut catalog = load_builtin_catalog(); + + // Runtime catalogs can be provided either as DATA_FOLDER/locales/.json + // or as modular files under DATA_FOLDER/locales//*.json. + // Runtime values extend or override built-ins and allow adding new languages. + load_runtime_catalog_extensions(&mut catalog); + + catalog +} + +fn tr(locale: &str, key: &str, en_fallback: &'static str, ru_fallback: &'static str) -> &'static str { + if !key_is_locale_scoped(key) { + return lookup_en(&LOCALE_CATALOG, key).unwrap_or(en_fallback); + } + + for candidate in locale_candidates(locale) { + if let Some(value) = LOCALE_CATALOG.get(&candidate).and_then(|m| m.get(key)) { + return value.as_str(); + } + } + + if is_russian(locale) { + ru_fallback + } else { + en_fallback + } +} + +pub fn tr_lookup(locale: &str, key: &str) -> Option<&'static str> { + for candidate in locale_candidates(locale) { + if let Some(value) = LOCALE_CATALOG.get(&candidate).and_then(|m| m.get(key)) { + return Some(value.as_str()); + } + } + + None +} + +fn tr_builtin(locale: &str, key: &str, en_fallback: &'static str, ru_fallback: &'static str) -> &'static str { + if !key_is_locale_scoped(key) { + return lookup_en(&BUILTIN_LOCALE_CATALOG, key).unwrap_or(en_fallback); + } + + for candidate in locale_candidates(locale) { + if let Some(value) = BUILTIN_LOCALE_CATALOG.get(&candidate).and_then(|m| m.get(key)) { + return value.as_str(); + } + } + + if is_russian(locale) { + ru_fallback + } else { + en_fallback + } +} + +macro_rules! localized_msg { + ($fn_name:ident, $key:literal, $en:literal, $ru:literal) => { + pub fn $fn_name(locale: &str) -> &'static str { + tr(locale, $key, $en, $ru) + } + }; +} + +macro_rules! localized_msg_bootstrap { + ($fn_name:ident, $key:literal, $en:literal, $ru:literal) => { + pub fn $fn_name(locale: &str) -> &'static str { + tr_builtin(locale, $key, $en, $ru) + } + }; +} + +localized_msg!( + api_not_found_description, + "api.not_found_description", + "The requested resource could not be found.", + "Запрошенный ресурс не найден." +); +localized_msg!( + admin_login_too_many_requests, + "admin.login_too_many_requests", + "Too many requests, try again later.", + "Слишком много запросов, повторите позже." +); +localized_msg!( + admin_login_invalid_token, + "admin.login_invalid_token", + "Invalid admin token, please try again.", + "Неверный токен администратора, попробуйте снова." +); +localized_msg!(admin_mail_not_enabled, "admin.mail_not_enabled", "Mail is not enabled", "Почта не включена"); +localized_msg!( + admin_cannot_change_last_owner_type, + "admin.cannot_change_last_owner_type", + "Can't change the type of the last owner", + "Нельзя изменить тип последнего владельца" +); +localized_msg!( + admin_backup_only_sqlite, + "admin.backup_only_sqlite", + "Can't back up current DB (Only SQLite supports this feature)", + "Нельзя сделать резервную копию текущей БД (только SQLite поддерживает эту функцию)" +); +localized_msg!( + admin_unable_save_config, + "admin.unable_save_config", + "Unable to save config", + "Не удалось сохранить конфигурацию" +); +localized_msg!( + admin_unable_delete_config, + "admin.unable_delete_config", + "Unable to delete config", + "Не удалось удалить конфигурацию" +); +localized_msg!( + admin_backup_unsuccessful, + "admin.backup_unsuccessful", + "Backup was unsuccessful", + "Резервное копирование завершилось неудачей" +); +localized_msg!(authorization_failed, "auth.authorization_failed", "Authorization failed.", "Ошибка авторизации."); +localized_msg!(identity_sso_required, "identity.sso_required", "SSO sign-in is required", "Требуется вход через SSO."); +localized_msg!( + identity_sso_unavailable, + "identity.sso_unavailable", + "SSO sign-in is not available", + "Вход через SSO недоступен." +); +localized_msg!(identity_invalid_type, "identity.invalid_type", "Invalid type", "Некорректный тип."); +localized_msg!( + identity_unsupported_code_challenge_method, + "identity.unsupported_code_challenge_method", + "Unsupported code challenge method", + "Неподдерживаемый метод code challenge" +); +localized_msg!( + identity_cannot_retrieve_sso_auth, + "identity.cannot_retrieve_sso_auth", + "Cannot retrieve sso_auth", + "Не удалось получить sso_auth" +); +localized_msg!( + identity_sso_session_binding_mismatch, + "identity.sso_session_binding_mismatch", + "SSO session binding mismatch", + "Несоответствие привязки SSO-сессии" +); +localized_msg!( + identity_failed_parse_redirect_uri, + "identity.failed_parse_redirect_uri", + "Failed to parse redirect uri", + "Не удалось разобрать redirect uri" +); +localized_msg!( + auth_invalid_username_or_password, + "auth.invalid_username_or_password", + "Username or password is incorrect. Try again", + "Неверные имя пользователя или пароль. Попробуйте еще раз." +); +localized_msg!( + auth_invalid_username_or_access_code, + "auth.invalid_username_or_access_code", + "Username or access code is incorrect. Try again", + "Неверные имя пользователя или код доступа. Попробуйте еще раз." +); +localized_msg!(auth_user_disabled, "auth.user_disabled", "This user has been disabled", "Пользователь отключен"); +localized_msg!( + auth_verify_email_before_login, + "auth.verify_email_before_login", + "Please verify your email before trying again.", + "Подтвердите email, прежде чем пытаться снова." +); +localized_msg!( + auth_scope_not_supported, + "auth.scope_not_supported", + "Scope not supported", + "Область действия не поддерживается" +); +localized_msg!(auth_malformed_client_id, "auth.malformed_client_id", "Malformed client_id", "Некорректный client_id"); +localized_msg!(auth_invalid_client_id, "auth.invalid_client_id", "Invalid client_id", "Некорректный client_id"); +localized_msg!( + auth_incorrect_client_secret, + "auth.incorrect_client_secret", + "Incorrect client_secret", + "Некорректный client_secret" +); +localized_msg!( + auth_no_2fa_providers, + "auth.no_2fa_providers", + "No enabled and usable two factor providers are available for this account", + "Для этой учетной записи нет включенных и доступных провайдеров двухфакторной аутентификации" +); +localized_msg!( + auth_invalid_twofactor_provider, + "auth.invalid_twofactor_provider", + "Invalid two factor provider", + "Некорректный провайдер двухфакторной аутентификации" +); +localized_msg!( + auth_two_step_token_invalid, + "auth.two_step_token_invalid", + "Two-step token is invalid. Try again.", + "Некорректный токен двухфакторной аутентификации. Попробуйте еще раз." +); +localized_msg!( + auth_no_yubikey_devices, + "auth.no_yubikey_devices", + "No YubiKey devices registered", + "Устройства YubiKey не зарегистрированы" +); +localized_msg!( + auth_no_twofactor_email, + "auth.no_twofactor_email", + "No twofactor email registered", + "Двухфакторная аутентификация по email не настроена" +); +localized_msg!(auth_invalid_password, "auth.invalid_password", "Invalid password", "Неверный пароль"); +localized_msg!( + auth_private_rsa_key_init_once, + "auth.private_rsa_key_init_once", + "PRIVATE_RSA_KEY must only be initialized once", + "PRIVATE_RSA_KEY должен инициализироваться только один раз" +); +localized_msg!( + auth_public_rsa_key_init_once, + "auth.public_rsa_key_init_once", + "PUBLIC_RSA_KEY must only be initialized once", + "PUBLIC_RSA_KEY должен инициализироваться только один раз" +); +localized_msg!( + auth_prelogin_kdf_key_init_once, + "auth.prelogin_kdf_key_init_once", + "PRELOGIN_KDF_KEY must only be initialized once", + "PRELOGIN_KDF_KEY должен инициализироваться только один раз" +); +localized_msg!(auth_error_decoding_jwt, "auth.error_decoding_jwt", "Error decoding JWT", "Ошибка декодирования JWT"); +localized_msg!(auth_token_invalid, "auth.token_invalid", "Token is invalid", "Токен некорректен"); +localized_msg!(auth_issuer_invalid, "auth.issuer_invalid", "Issuer is invalid", "Издатель некорректен"); +localized_msg!(auth_token_expired, "auth.token_expired", "Token has expired", "Срок действия токена истек"); +localized_msg!( + auth_invite_expire_delta_calculation_failed, + "auth.invite_expire_delta_calculation_failed", + "Unable to calculate time delta for invite expire hours. Check `INVITATION_EXPIRATION_HOURS`.", + "Не удалось вычислить интервал для срока приглашения. Проверьте `INVITATION_EXPIRATION_HOURS`." +); +localized_msg!( + auth_invite_expire_date_calculation_failed, + "auth.invite_expire_date_calculation_failed", + "Unable to calculate invitation expire date. Check `INVITATION_EXPIRATION_HOURS`.", + "Не удалось вычислить дату истечения приглашения. Проверьте `INVITATION_EXPIRATION_HOURS`." +); +localized_msg!( + auth_admin_session_delta_calculation_failed, + "auth.admin_session_delta_calculation_failed", + "Unable to calculate time delta for admin session lifetime. Check `ADMIN_SESSION_LIFETIME`.", + "Не удалось вычислить интервал времени жизни сессии администратора. Проверьте `ADMIN_SESSION_LIFETIME`." +); +localized_msg!( + auth_admin_session_lifetime_calculation_failed, + "auth.admin_session_lifetime_calculation_failed", + "Unable to calculate admin session lifetime. Check `ADMIN_SESSION_LIFETIME`.", + "Не удалось вычислить время жизни сессии администратора. Проверьте `ADMIN_SESSION_LIFETIME`." +); +localized_msg!( + auth_collection_id_malformed, + "auth.collection_id_malformed", + "Collection Id is malformed!", + "ID коллекции имеет неверный формат!" +); +localized_msg!( + auth_collection_not_found_or_not_manager, + "auth.collection_not_found_or_not_manager", + "Collection not found", + "Коллекция не найдена" +); +localized_msg!( + auth_user_not_manager_for_collection, + "auth.user_not_manager_for_collection", + "The current user isn't a manager for this collection", + "Текущий пользователь не является менеджером этой коллекции" +); +localized_msg!(auth_missing_scope, "auth.missing_scope", "Missing scope", "Отсутствует scope"); +localized_msg!( + auth_invalid_refresh_token, + "auth.invalid_refresh_token", + "Invalid refresh token", + "Некорректный refresh токен" +); +localized_msg!( + auth_impossible_find_user, + "auth.impossible_find_user", + "Impossible to find user", + "Невозможно найти пользователя" +); +localized_msg!( + auth_sso_now_disabled_login_password, + "auth.sso_now_disabled_login_password", + "SSO is now disabled, Login again using email and master password", + "SSO отключен, войдите снова через email и мастер-пароль" +); +localized_msg!( + auth_sso_now_required_login_again, + "auth.sso_now_required_login_again", + "SSO is now required, Login again", + "Теперь требуется SSO, войдите снова" +); +localized_msg!( + auth_invalid_auth_method_refresh, + "auth.invalid_auth_method_refresh", + "Invalid auth method, cannot refresh token", + "Некорректный метод аутентификации, невозможно обновить токен" +); +localized_msg!( + auth_failed_discover_token_url, + "auth.failed_discover_token_url", + "Failed to discover token_url, cannot proceed", + "Не удалось обнаружить token_url, невозможно продолжить" +); +localized_msg!( + auth_failed_discover_user_info_url, + "auth.failed_discover_user_info_url", + "Failed to discover user_info url, cannot proceed", + "Не удалось обнаружить user_info url, невозможно продолжить" +); +localized_msg!( + auth_pkce_client_challenge_failed, + "auth.pkce_client_challenge_failed", + "PKCE client challenge failed", + "Проверка PKCE challenge клиента не удалась" +); +localized_msg!( + auth_token_response_missing_id_token, + "auth.token_response_missing_id_token", + "Token response did not contain an id_token", + "Ответ токена не содержит id_token" +); +localized_msg!( + auth_invalid_code_cannot_retrieve_sso_auth, + "auth.invalid_code_cannot_retrieve_sso_auth", + "Invalid code cannot retrieve sso auth", + "Некорректный код: не удалось получить sso auth" +); +localized_msg!( + auth_missing_authorization_provider_return, + "auth.missing_authorization_provider_return", + "Missing authorization provider return", + "Отсутствует ответ от провайдера авторизации" +); +localized_msg!( + auth_neither_id_token_nor_userinfo_email, + "auth.neither_id_token_nor_userinfo_email", + "Neither id token nor userinfo contained an email", + "Ни id token, ни userinfo не содержат email" +); +localized_msg!( + auth_non_jwt_access_token_empty_expires_in, + "auth.non_jwt_access_token_empty_expires_in", + "Non jwt access_token and empty expires_in", + "Не-JWT access_token и пустой expires_in" +); +localized_msg!( + auth_no_token_present_while_sso, + "auth.no_token_present_while_sso", + "No token present while in SSO", + "Во время SSO отсутствует токен" +); +localized_msg!( + auth_invalid_utf8_after_base64_decode, + "auth.invalid_utf8_after_base64_decode", + "Invalid utf8 chars after base64 decoding", + "Некорректные utf8-символы после декодирования base64" +); +localized_msg!( + auth_failed_decode_using_base64, + "auth.failed_decode_using_base64", + "Failed to decode using base64", + "Не удалось декодировать с использованием base64" +); +localized_msg!( + auth_unsupported_redirect_uri, + "auth.unsupported_redirect_uri", + "Unsupported redirect uri", + "Неподдерживаемый redirect uri" +); +localized_msg!(auth_unsupported_client, "auth.unsupported_client", "Unsupported client", "Неподдерживаемый клиент"); +localized_msg!( + auth_failed_build_http_client, + "auth.failed_build_http_client", + "Failed to build http client", + "Не удалось создать HTTP-клиент" +); +localized_msg!( + auth_failed_discover_openid_provider, + "auth.failed_discover_openid_provider", + "Failed to discover OpenID provider", + "Не удалось обнаружить OpenID-провайдера" +); +localized_msg!( + auth_no_supported_auth_methods, + "auth.no_supported_auth_methods", + "No supported auth_methods (only basic or request body)", + "Нет поддерживаемых auth_methods (только basic или request body)" +); +localized_msg!( + auth_failed_contact_token_endpoint, + "auth.failed_contact_token_endpoint", + "Failed to contact token endpoint", + "Не удалось обратиться к token endpoint" +); +localized_msg!( + auth_could_not_read_id_token_claims, + "auth.could_not_read_id_token_claims", + "Could not read id_token claims", + "Не удалось прочитать claims id_token" +); +localized_msg!( + auth_request_user_info_endpoint_failed, + "auth.request_user_info_endpoint_failed", + "Request to user_info endpoint failed", + "Запрос к user_info endpoint завершился ошибкой" +); +localized_msg_bootstrap!( + config_password_iterations_min, + "config.password_iterations_min", + "PASSWORD_ITERATIONS should be at least 100000 or higher. The default is 600000!", + "PASSWORD_ITERATIONS должен быть не менее 100000. Значение по умолчанию 600000!" +); +#[cfg(sqlite)] +localized_msg_bootstrap!( + config_sqlite_database_directory_invalid, + "config.sqlite_database_directory_invalid", + "SQLite database directory does not exist or is not a directory", + "Каталог базы данных SQLite не существует или не является каталогом" +); +localized_msg_bootstrap!( + config_ip_header_trusted_proxies_invalid_entry, + "config.ip_header_trusted_proxies_invalid_entry", + "Invalid IP_HEADER_TRUSTED_PROXIES entry, expected an IP or CIDR range", + "Некорректная запись IP_HEADER_TRUSTED_PROXIES, ожидается IP или диапазон CIDR" +); +localized_msg_bootstrap!( + config_database_max_conns_invalid_range, + "config.database_max_conns_invalid_range", + "`DATABASE_MAX_CONNS` contains an invalid value. Ensure it is between 1 and 256.", + "`DATABASE_MAX_CONNS` содержит некорректное значение. Убедитесь, что оно находится в диапазоне от 1 до 256." +); +localized_msg_bootstrap!( + config_database_min_conns_invalid_range, + "config.database_min_conns_invalid_range", + "`DATABASE_MIN_CONNS` contains an invalid value. Ensure it is between 1 and 256.", + "`DATABASE_MIN_CONNS` содержит некорректное значение. Убедитесь, что оно находится в диапазоне от 1 до 256." +); +localized_msg_bootstrap!( + config_database_min_conns_lte_max, + "config.database_min_conns_lte_max", + "`DATABASE_MIN_CONNS` must be less than or equal to `DATABASE_MAX_CONNS`.", + "`DATABASE_MIN_CONNS` должен быть меньше или равен `DATABASE_MAX_CONNS`." +); +localized_msg_bootstrap!( + config_database_timeout_min_1, + "config.database_timeout_min_1", + "`DATABASE_TIMEOUT` must be at least 1 second", + "`DATABASE_TIMEOUT` должен быть не менее 1 секунды" +); +localized_msg_bootstrap!( + config_database_idle_timeout_min_1, + "config.database_idle_timeout_min_1", + "`DATABASE_IDLE_TIMEOUT` must be at least 1 second", + "`DATABASE_IDLE_TIMEOUT` должен быть не менее 1 секунды" +); +localized_msg_bootstrap!( + config_unable_write_log_file, + "config.unable_write_log_file", + "Unable to write to log file", + "Не удалось записать в лог-файл" +); +localized_msg_bootstrap!( + config_signups_domains_whitelist_empty_tokens, + "config.signups_domains_whitelist_empty_tokens", + "`SIGNUPS_DOMAINS_WHITELIST` contains empty tokens", + "`SIGNUPS_DOMAINS_WHITELIST` содержит пустые токены" +); +localized_msg_bootstrap!( + config_org_creation_users_invalid_emails, + "config.org_creation_users_invalid_emails", + "`ORG_CREATION_USERS` contains invalid email addresses", + "`ORG_CREATION_USERS` содержит некорректные email-адреса" +); +localized_msg_bootstrap!( + config_push_relay_uri_must_be_https, + "config.push_relay_uri_must_be_https", + "`PUSH_RELAY_URI` must start with 'https://'.", + "`PUSH_RELAY_URI` должен начинаться с 'https://'." +); +localized_msg_bootstrap!( + config_push_relay_uri_invalid_url, + "config.push_relay_uri_invalid_url", + "Invalid URL format for `PUSH_RELAY_URI`.", + "Неверный формат URL для `PUSH_RELAY_URI`." +); +localized_msg_bootstrap!( + config_push_identity_uri_must_be_https, + "config.push_identity_uri_must_be_https", + "`PUSH_IDENTITY_URI` must start with 'https://'.", + "`PUSH_IDENTITY_URI` должен начинаться с 'https://'." +); +localized_msg_bootstrap!( + config_push_identity_uri_invalid_url, + "config.push_identity_uri_invalid_url", + "Invalid URL format for `PUSH_IDENTITY_URI`.", + "Неверный формат URL для `PUSH_IDENTITY_URI`." +); +localized_msg_bootstrap!( + config_user_attachment_limit_out_of_bounds, + "config.user_attachment_limit_out_of_bounds", + "`USER_ATTACHMENT_LIMIT` is out of bounds", + "`USER_ATTACHMENT_LIMIT` вне допустимых границ" +); +localized_msg_bootstrap!( + config_org_attachment_limit_out_of_bounds, + "config.org_attachment_limit_out_of_bounds", + "`ORG_ATTACHMENT_LIMIT` is out of bounds", + "`ORG_ATTACHMENT_LIMIT` вне допустимых границ" +); +localized_msg_bootstrap!( + config_user_send_limit_out_of_bounds, + "config.user_send_limit_out_of_bounds", + "`USER_SEND_LIMIT` is out of bounds", + "`USER_SEND_LIMIT` вне допустимых границ" +); +localized_msg_bootstrap!( + config_duo_all_options_required, + "config.duo_all_options_required", + "All Duo options need to be set for global Duo support", + "Для глобальной поддержки Duo должны быть заданы все параметры Duo" +); +localized_msg_bootstrap!( + config_sso_required_options_missing, + "config.sso_required_options_missing", + "`SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` and `SSO_AUTHORITY` must be set for SSO support", + "Для поддержки SSO должны быть заданы `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` и `SSO_AUTHORITY`" +); +localized_msg_bootstrap!( + config_yubico_both_credentials_required, + "config.yubico_both_credentials_required", + "Both `YUBICO_CLIENT_ID` and `YUBICO_SECRET_KEY` must be set for Yubikey OTP support", + "Для поддержки Yubikey OTP должны быть заданы и `YUBICO_CLIENT_ID`, и `YUBICO_SECRET_KEY`" +); +localized_msg_bootstrap!( + config_smtp_host_and_from_required, + "config.smtp_host_and_from_required", + "Both `SMTP_HOST` and `SMTP_FROM` need to be set for email support without `USE_SENDMAIL`", + "Для поддержки email без `USE_SENDMAIL` должны быть заданы `SMTP_HOST` и `SMTP_FROM`" +); +localized_msg_bootstrap!( + config_sendmail_command_not_found_in_path, + "config.sendmail_command_not_found_in_path", + "sendmail command was not found in $PATH", + "Команда sendmail не найдена в $PATH" +); +localized_msg_bootstrap!( + config_sendmail_command_not_found_at_path, + "config.sendmail_command_not_found_at_path", + "sendmail command was not found at the configured path", + "Команда sendmail не найдена по указанному пути" +); +localized_msg_bootstrap!( + config_sendmail_command_access_failed, + "config.sendmail_command_access_failed", + "failed to access sendmail command", + "Не удалось получить доступ к команде sendmail" +); +localized_msg_bootstrap!( + config_sendmail_command_is_directory, + "config.sendmail_command_is_directory", + "sendmail command path points to a directory", + "Путь команды sendmail указывает на каталог" +); +localized_msg_bootstrap!( + config_sendmail_command_not_executable, + "config.sendmail_command_not_executable", + "sendmail command is not executable", + "Команда sendmail не является исполняемой" +); +localized_msg_bootstrap!( + config_smtp_from_invalid_email, + "config.smtp_from_invalid_email", + "SMTP_FROM is not a valid email address", + "SMTP_FROM не является корректным email-адресом" +); +localized_msg_bootstrap!( + config_email_token_size_min_6, + "config.email_token_size_min_6", + "`EMAIL_TOKEN_SIZE` has a minimum size of 6", + "`EMAIL_TOKEN_SIZE` должен быть не меньше 6" +); +localized_msg_bootstrap!( + config_email_2fa_requires_mail_transport, + "config.email_2fa_requires_mail_transport", + "To enable email 2FA, a mail transport must be configured", + "Для включения email 2FA должен быть настроен почтовый транспорт" +); +localized_msg_bootstrap!( + config_email_2fa_verified_invite_requires_enable, + "config.email_2fa_verified_invite_requires_enable", + "To enforce email 2FA on verified invitations, email 2fa has to be enabled!", + "Чтобы принудить email 2FA для подтвержденных приглашений, email 2fa должен быть включен!" +); +localized_msg_bootstrap!( + config_email_2fa_fallback_requires_enable, + "config.email_2fa_fallback_requires_enable", + "To use email 2FA as automatic fallback, email 2fa has to be enabled!", + "Чтобы использовать email 2FA как автоматический fallback, email 2fa должен быть включен!" +); +localized_msg_bootstrap!( + config_http_request_block_regex_invalid, + "config.http_request_block_regex_invalid", + "`HTTP_REQUEST_BLOCK_REGEX` is invalid", + "`HTTP_REQUEST_BLOCK_REGEX` некорректен" +); +localized_msg_bootstrap!( + config_icon_service_url_must_start_http, + "config.icon_service_url_must_start_http", + "Icon service URL must start with \"http\"", + "URL сервиса иконок должен начинаться с \"http\"" +); +localized_msg_bootstrap!( + config_icon_service_url_missing_placeholder, + "config.icon_service_url_missing_placeholder", + "Icon service URL has no placeholder \"{{}}\"", + "URL сервиса иконок не содержит плейсхолдера \"{{}}\"" +); +localized_msg_bootstrap!( + config_icon_service_url_multiple_placeholders, + "config.icon_service_url_multiple_placeholders", + "Icon service URL has more than one placeholder \"{{}}\"", + "URL сервиса иконок содержит более одного плейсхолдера \"{{}}\"" +); +localized_msg_bootstrap!( + config_icon_redirect_supported_codes, + "config.icon_redirect_supported_codes", + "Only HTTP 301/302 and 307/308 redirects are supported", + "Поддерживаются только HTTP редиректы 301/302 и 307/308" +); +localized_msg_bootstrap!( + config_invitation_expiration_hours_min_1, + "config.invitation_expiration_hours_min_1", + "`INVITATION_EXPIRATION_HOURS` has a minimum duration of 1 hour", + "`INVITATION_EXPIRATION_HOURS` должен быть не менее 1 часа" +); +localized_msg_bootstrap!( + config_send_purge_schedule_invalid, + "config.send_purge_schedule_invalid", + "`SEND_PURGE_SCHEDULE` is not a valid cron expression", + "`SEND_PURGE_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_trash_purge_schedule_invalid, + "config.trash_purge_schedule_invalid", + "`TRASH_PURGE_SCHEDULE` is not a valid cron expression", + "`TRASH_PURGE_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_incomplete_2fa_schedule_invalid, + "config.incomplete_2fa_schedule_invalid", + "`INCOMPLETE_2FA_SCHEDULE` is not a valid cron expression", + "`INCOMPLETE_2FA_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_emergency_notification_reminder_schedule_invalid, + "config.emergency_notification_reminder_schedule_invalid", + "`EMERGENCY_NOTIFICATION_REMINDER_SCHEDULE` is not a valid cron expression", + "`EMERGENCY_NOTIFICATION_REMINDER_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_emergency_request_timeout_schedule_invalid, + "config.emergency_request_timeout_schedule_invalid", + "`EMERGENCY_REQUEST_TIMEOUT_SCHEDULE` is not a valid cron expression", + "`EMERGENCY_REQUEST_TIMEOUT_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_event_cleanup_schedule_invalid, + "config.event_cleanup_schedule_invalid", + "`EVENT_CLEANUP_SCHEDULE` is not a valid cron expression", + "`EVENT_CLEANUP_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_auth_request_purge_schedule_invalid, + "config.auth_request_purge_schedule_invalid", + "`AUTH_REQUEST_PURGE_SCHEDULE` is not a valid cron expression", + "`AUTH_REQUEST_PURGE_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_duo_context_purge_schedule_invalid, + "config.duo_context_purge_schedule_invalid", + "`DUO_CONTEXT_PURGE_SCHEDULE` is not a valid cron expression", + "`DUO_CONTEXT_PURGE_SCHEDULE` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_purge_incomplete_sso_auth_invalid, + "config.purge_incomplete_sso_auth_invalid", + "`PURGE_INCOMPLETE_SSO_AUTH` is not a valid cron expression", + "`PURGE_INCOMPLETE_SSO_AUTH` содержит некорректное cron-выражение" +); +localized_msg_bootstrap!( + config_login_ratelimit_seconds_min_1, + "config.login_ratelimit_seconds_min_1", + "`LOGIN_RATELIMIT_SECONDS` must be at least 1 second", + "`LOGIN_RATELIMIT_SECONDS` должен быть не менее 1 секунды" +); +localized_msg_bootstrap!( + config_login_ratelimit_max_burst_min_1, + "config.login_ratelimit_max_burst_min_1", + "`LOGIN_RATELIMIT_MAX_BURST` must be at least 1", + "`LOGIN_RATELIMIT_MAX_BURST` должен быть не менее 1" +); +localized_msg_bootstrap!( + config_admin_ratelimit_seconds_min_1, + "config.admin_ratelimit_seconds_min_1", + "`ADMIN_RATELIMIT_SECONDS` must be at least 1 second", + "`ADMIN_RATELIMIT_SECONDS` должен быть не менее 1 секунды" +); +localized_msg_bootstrap!( + config_admin_ratelimit_max_burst_min_1, + "config.admin_ratelimit_max_burst_min_1", + "`ADMIN_RATELIMIT_MAX_BURST` must be at least 1", + "`ADMIN_RATELIMIT_MAX_BURST` должен быть не менее 1" +); +localized_msg_bootstrap!( + config_unauthenticated_ratelimit_seconds_min_1, + "config.unauthenticated_ratelimit_seconds_min_1", + "`UNAUTHENTICATED_RATELIMIT_SECONDS` must be at least 1 second", + "`UNAUTHENTICATED_RATELIMIT_SECONDS` должен быть не менее 1 секунды" +); +localized_msg_bootstrap!( + config_unauthenticated_ratelimit_max_burst_min_1, + "config.unauthenticated_ratelimit_max_burst_min_1", + "`UNAUTHENTICATED_RATELIMIT_MAX_BURST` must be at least 1", + "`UNAUTHENTICATED_RATELIMIT_MAX_BURST` должен быть не менее 1" +); +localized_msg_bootstrap!( + config_admin_token_argon2_phc_invalid, + "config.admin_token_argon2_phc_invalid", + "The configured Argon2 PHC in `ADMIN_TOKEN` is invalid", + "Настроенный Argon2 PHC в `ADMIN_TOKEN` некорректен" +); +localized_msg_bootstrap!( + config_sso_authority_url_invalid, + "config.sso_authority_url_invalid", + "Invalid sso_authority URL", + "Некорректный URL sso_authority" +); +localized_msg_bootstrap!( + config_sso_callback_path_url_invalid, + "config.sso_callback_path_url_invalid", + "Invalid sso_callback_path URL", + "Некорректный URL sso_callback_path" +); +localized_msg_bootstrap!( + config_sso_master_password_policy_invalid, + "config.sso_master_password_policy_invalid", + "Invalid sso_master_password_policy. Ensure that it is correctly escaped with ''", + "Некорректный sso_master_password_policy. Убедитесь, что он корректно экранирован с помощью ''" +); +localized_msg_bootstrap!( + config_sso_master_password_policy_not_object, + "config.sso_master_password_policy_not_object", + "Invalid sso_master_password_policy: parsed value is not a JSON object", + "Некорректный sso_master_password_policy: разобранное значение не является JSON-объектом" +); +localized_msg!( + accounts_email_change_not_allowed, + "accounts.email_change_not_allowed", + "Email change is not allowed.", + "Смена email не разрешена." +); +localized_msg!( + accounts_email_already_in_use, + "accounts.email_already_in_use", + "Email already in use", + "Email уже используется" +); +localized_msg!( + accounts_email_domain_not_allowed, + "accounts.email_domain_not_allowed", + "Email domain not allowed", + "Домен email не разрешен" +); +localized_msg!( + accounts_email_change_mismatch, + "accounts.email_change_mismatch", + "Email change mismatch", + "Несоответствие смены email" +); +localized_msg!( + accounts_no_email_change_pending, + "accounts.no_email_change_pending", + "No email change pending", + "Нет ожидающей смены email" +); +localized_msg!(accounts_token_mismatch, "accounts.token_mismatch", "Token mismatch", "Несоответствие токена"); +localized_msg!( + accounts_cannot_verify_email, + "accounts.cannot_verify_email", + "Cannot verify email address", + "Невозможно подтвердить email адрес" +); +localized_msg!(accounts_no_device_found, "accounts.no_device_found", "No device found", "Устройство не найдено"); +localized_msg!( + accounts_email_verification_token_mismatch, + "accounts.email_verification_token_mismatch", + "Email verification token does not match email", + "Токен подтверждения email не соответствует email" +); +localized_msg!( + accounts_emergency_access_not_enabled, + "accounts.emergency_access_not_enabled", + "Emergency access is not enabled.", + "Экстренный доступ не включен." +); +localized_msg!( + accounts_claim_email_mismatch, + "accounts.claim_email_mismatch", + "Claim email does not match email", + "Email в клейме не соответствует email" +); +localized_msg!( + accounts_claim_emer_id_mismatch, + "accounts.claim_emer_id_mismatch", + "Claim emer_id does not match accept_emergency_access_id", + "emer_id в клейме не соответствует accept_emergency_access_id" +); +localized_msg!( + accounts_claim_org_user_id_mismatch, + "accounts.claim_org_user_id_mismatch", + "Claim org_user_id does not match organization_user_id", + "org_user_id в клейме не соответствует organization_user_id" +); +localized_msg!( + accounts_registration_missing_required_params, + "accounts.registration_missing_required_params", + "Registration is missing required parameters", + "В регистрации отсутствуют обязательные параметры" +); +localized_msg!( + accounts_registration_not_allowed_or_exists, + "accounts.registration_not_allowed_or_exists", + "Registration not allowed or user already exists", + "Регистрация запрещена или пользователь уже существует" +); +localized_msg!( + accounts_password_hints_disabled, + "accounts.password_hints_disabled", + "Password hints have been disabled by the administrator. Remove the hint and try again.", + "Подсказки пароля отключены администратором. Удалите подсказку и попробуйте снова." +); +localized_msg!( + accounts_name_too_long, + "accounts.name_too_long", + "The field Name must be a string with a maximum length of 50.", + "Поле Name должно быть строкой длиной не более 50 символов." +); +localized_msg!( + accounts_registration_email_invite_mismatch, + "accounts.registration_email_invite_mismatch", + "Registration email does not match invite email", + "Email регистрации не совпадает с email приглашения" +); +localized_msg!( + accounts_account_already_initialized, + "accounts.account_already_initialized", + "Account already initialized, cannot set password", + "Учетная запись уже инициализирована, задать пароль нельзя" +); +localized_msg!( + accounts_avatar_color_invalid, + "accounts.avatar_color_invalid", + "The field AvatarColor must be a HTML/Hex color code with a length of 7 characters", + "Поле AvatarColor должно быть HTML/Hex цветом длиной 7 символов" +); +localized_msg!(accounts_user_not_found, "accounts.user_not_found", "User doesn't exist", "Пользователь не существует"); +localized_msg!(accounts_invalid_claim, "accounts.invalid_claim", "Invalid claim", "Некорректный клейм"); +localized_msg!( + accounts_contact_admin_to_delete, + "accounts.contact_admin_to_delete", + "Please contact the administrator to delete your account", + "Свяжитесь с администратором, чтобы удалить учетную запись" +); +localized_msg!( + accounts_password_hint_not_configured, + "accounts.password_hint_not_configured", + "This server is not configured to provide password hints.", + "Этот сервер не настроен для выдачи подсказок пароля." +); +localized_msg!( + accounts_password_hint_is, + "accounts.password_hint_is", + "Your password hint is: {}", + "Ваша подсказка пароля: {}" +); +localized_msg!( + accounts_auth_request_not_found, + "accounts.auth_request_not_found", + "AuthRequest doesn't exist", + "Запрос аутентификации не существует" +); +localized_msg!( + accounts_device_verification_failed, + "accounts.device_verification_failed", + "Device verification failed", + "Проверка устройства не пройдена" +); +localized_msg!( + accounts_auth_request_not_found_or_mismatch, + "accounts.auth_request_not_found_or_mismatch", + "Record not found or user uuid does not match", + "Запись не найдена или uuid пользователя не совпадает" +); +localized_msg!( + accounts_auth_request_duplicate_device, + "accounts.auth_request_duplicate_device", + "An authentication request with the same device already exists", + "Запрос аутентификации для этого устройства уже существует" +); +localized_msg!( + accounts_auth_request_invalid_device_ip_or_code, + "accounts.auth_request_invalid_device_ip_or_code", + "Invalid device, IP or code", + "Некорректное устройство, IP или код" +); +localized_msg!( + accounts_device_should_be_present_before_token_assigned, + "accounts.device_should_be_present_before_token_assigned", + "Device should be present before a token can be assigned", + "Устройство должно существовать до назначения токена" +); +localized_msg!( + accounts_error_saving_device_push_token, + "accounts.error_saving_device_push_token", + "An error occurred while trying to save the device push token", + "Произошла ошибка при сохранении push токена устройства" +); +localized_msg!( + accounts_associated_org_not_found, + "accounts.associated_org_not_found", + "Failed to retrieve the associated organization", + "Не удалось получить связанную организацию" +); +localized_msg!( + accounts_invitation_not_found, + "accounts.invitation_not_found", + "Failed to retrieve the invitation", + "Не удалось получить приглашение" +); +localized_msg!( + accounts_existing_keypair, + "accounts.existing_keypair", + "User has existing keypair", + "У пользователя уже есть существующая ключевая пара" +); +localized_msg!( + accounts_kdf_auth_unlock_mismatch, + "accounts.kdf_auth_unlock_mismatch", + "KDF settings must be equal for authentication and unlock", + "Параметры KDF должны совпадать для аутентификации и разблокировки" +); +localized_msg!( + accounts_invalid_master_password_salt, + "accounts.invalid_master_password_salt", + "Invalid master password salt", + "Некорректная salt для мастер-пароля" +); +localized_msg!(accounts_invalid_request, "accounts.invalid_request", "Invalid request!", "Некорректный запрос!"); +localized_msg!( + accounts_pbkdf2_min_iterations, + "accounts.pbkdf2_min_iterations", + "PBKDF2 KDF iterations must be at least 100000.", + "Количество итераций PBKDF2 должно быть не менее 100000." +); +localized_msg!( + accounts_argon2_min_iterations, + "accounts.argon2_min_iterations", + "Argon2 KDF iterations must be at least 1.", + "Количество итераций Argon2 должно быть не менее 1." +); +localized_msg!( + accounts_argon2_memory_range, + "accounts.argon2_memory_range", + "Argon2 memory must be between 15 MB and 1024 MB.", + "Память Argon2 должна быть в пределах от 15 MB до 1024 MB." +); +localized_msg!( + accounts_argon2_memory_required, + "accounts.argon2_memory_required", + "Argon2 memory parameter is required.", + "Параметр памяти Argon2 обязателен." +); +localized_msg!( + accounts_argon2_parallelism_range, + "accounts.argon2_parallelism_range", + "Argon2 parallelism must be between 1 and 16.", + "Параллелизм Argon2 должен быть в диапазоне от 1 до 16." +); +localized_msg!( + accounts_argon2_parallelism_required, + "accounts.argon2_parallelism_required", + "Argon2 parallelism parameter is required.", + "Параметр параллелизма Argon2 обязателен." +); +localized_msg!( + accounts_rotate_kdf_or_email_change_not_supported, + "accounts.rotate_kdf_or_email_change_not_supported", + "Changing the kdf variant or email is not supported during key rotation", + "Изменение варианта kdf или email не поддерживается во время ротации ключей" +); +localized_msg!( + accounts_rotate_asymmetric_keypair_change_not_supported, + "accounts.rotate_asymmetric_keypair_change_not_supported", + "Changing the asymmetric keypair is not possible during key rotation", + "Изменение асимметричной ключевой пары во время ротации ключей невозможно" +); +localized_msg!( + accounts_rotate_all_ciphers_required, + "accounts.rotate_all_ciphers_required", + "All existing ciphers must be included in the rotation", + "Все существующие шифры должны быть включены в ротацию" +); +localized_msg!( + accounts_rotate_all_folders_required, + "accounts.rotate_all_folders_required", + "All existing folders must be included in the rotation", + "Все существующие папки должны быть включены в ротацию" +); +localized_msg!( + accounts_rotate_all_emergency_access_required, + "accounts.rotate_all_emergency_access_required", + "All existing emergency access keys must be included in the rotation", + "Все существующие ключи экстренного доступа должны быть включены в ротацию" +); +localized_msg!( + accounts_rotate_all_reset_password_required, + "accounts.rotate_all_reset_password_required", + "All existing reset password keys must be included in the rotation", + "Все существующие ключи сброса пароля должны быть включены в ротацию" +); +localized_msg!( + accounts_rotate_all_sends_required, + "accounts.rotate_all_sends_required", + "All existing sends must be included in the rotation", + "Все существующие отправки должны быть включены в ротацию" +); +localized_msg!(accounts_folder_not_found, "accounts.folder_not_found", "Folder doesn't exist", "Папка не существует"); +localized_msg!( + accounts_emergency_access_not_found_or_not_owned, + "accounts.emergency_access_not_found_or_not_owned", + "Emergency access doesn't exist or is not owned by the user", + "Экстренный доступ не существует или не принадлежит пользователю" +); +localized_msg!( + accounts_reset_password_not_found, + "accounts.reset_password_not_found", + "Reset password doesn't exist", + "Сброс пароля не существует" +); +localized_msg!(accounts_send_not_found, "accounts.send_not_found", "Send doesn't exist", "Отправка не существует"); +localized_msg!(accounts_cipher_not_found, "accounts.cipher_not_found", "Cipher doesn't exist", "Шифр не существует"); +localized_msg!( + send_delete_only_policy, + "send.delete_only_policy", + "Due to an Enterprise Policy, you are only able to delete an existing Send.", + "Из-за корпоративной политики вы можете только удалить существующую отправку." +); +localized_msg!( + send_hide_email_policy_forbidden, + "send.hide_email_policy_forbidden", + "Due to an Enterprise Policy, you are not allowed to hide your email address from recipients when creating or editing a Send.", + "Из-за корпоративной политики вам запрещено скрывать свой email от получателей при создании или редактировании отправки." +); +localized_msg!(send_invalid_type, "send.invalid_type", "Invalid Send type", "Некорректный тип отправки"); +localized_msg!( + send_data_not_provided, + "send.data_not_provided", + "Send data not provided", + "Данные отправки не предоставлены" +); +localized_msg!( + send_deletion_date_too_far, + "send.deletion_date_too_far", + "You cannot have a Send with a deletion date that far into the future. Adjust the Deletion Date to a value less than 31 days from now and try again.", + "Нельзя создать отправку с датой удаления так далеко в будущем. Установите дату удаления менее чем через 31 день и повторите попытку." +); +localized_msg!( + send_email_verification_not_supported, + "send.email_verification_not_supported", + "Sends with email verification is not supported", + "Отправки с проверкой email не поддерживаются" +); +localized_msg!(send_not_found, "send.not_found", "Send not found", "Отправка не найдена"); +localized_msg!( + send_invalid_uuid_or_not_owned, + "send.invalid_uuid_or_not_owned", + "Invalid send uuid or does not belong to user", + "Некорректный UUID отправки или она не принадлежит пользователю" +); +localized_msg!( + send_file_use_v2, + "send.file_use_v2", + "File sends should use /api/sends/file/v2", + "Для файловых отправок используйте /api/sends/file/v2" +); +localized_msg!( + send_content_not_file, + "send.content_not_file", + "Send content is not a file", + "Содержимое отправки не является файлом" +); +localized_msg!(send_invalid_length, "send.invalid_length", "Invalid send length", "Некорректная длина отправки"); +localized_msg!( + send_size_negative, + "send.size_negative", + "Send size can't be negative", + "Размер отправки не может быть отрицательным" +); +localized_msg!( + send_file_uploads_disabled, + "send.file_uploads_disabled", + "File uploads are disabled", + "Загрузка файлов отключена" +); +localized_msg!( + send_existing_overflow, + "send.existing_overflow", + "Existing sends overflow", + "Переполнение существующих отправок" +); +localized_msg!(send_size_overflow, "send.size_overflow", "Send size overflow", "Переполнение размера отправки"); +localized_msg!( + send_storage_limit_reached, + "send.storage_limit_reached", + "Send storage limit reached! Delete some sends to free up space", + "Достигнут лимит хранилища отправок! Удалите часть отправок, чтобы освободить место" +); +localized_msg!( + send_storage_limit_exceeded_file, + "send.storage_limit_exceeded_file", + "Send storage limit exceeded with this file", + "Лимит хранилища отправок будет превышен этим файлом" +); +localized_msg!( + send_not_found_unable_save_file, + "send.not_found_unable_save_file", + "Send not found. Unable to save the file.", + "Отправка не найдена. Не удалось сохранить файл." +); +localized_msg!( + send_not_file_type, + "send.not_file_type", + "Send is not a file type send.", + "Отправка не является файловым типом." +); +localized_msg!( + send_unable_decode_json, + "send.unable_decode_json", + "Unable to decode send data as json.", + "Не удалось декодировать данные отправки как JSON." +); +localized_msg!( + send_file_name_mismatch, + "send.file_name_mismatch", + "Send file name does not match.", + "Имя файла отправки не совпадает." +); +localized_msg!( + send_file_name_missing_or_mismatch, + "send.file_name_missing_or_mismatch", + "Send file name does not match or is not provided.", + "Имя файла отправки не совпадает или не предоставлено." +); +localized_msg!( + send_file_mismatch_data, + "send.file_mismatch_data", + "Send file does not match send data.", + "Файл отправки не соответствует данным отправки." +); +localized_msg!( + send_file_size_overflow, + "send.file_size_overflow", + "Send file size overflow.", + "Переполнение размера файла отправки." +); +localized_msg!( + send_file_size_mismatch, + "send.file_size_mismatch", + "Send file size does not match.", + "Размер файла отправки не совпадает." +); +localized_msg!( + send_invalid_send_id_or_not_owned, + "send.invalid_send_id_or_not_owned", + "Send send_id is invalid or does not belong to user", + "Идентификатор send_id некорректен или отправка не принадлежит пользователю" +); +localized_msg!( + send_not_owned_by_user, + "send.not_owned_by_user", + "Send is not owned by user", + "Отправка не принадлежит пользователю" +); +localized_msg!( + send_cannot_change_type, + "send.cannot_change_type", + "Sends can't change type", + "Отправка не может менять тип" +); +localized_msg!( + two_factor_invalid_totp_secret, + "two_factor.invalid_totp_secret", + "Invalid TOTP secret", + "Некорректный TOTP секрет" +); +localized_msg!( + two_factor_invalid_key_length, + "two_factor.invalid_key_length", + "Invalid key length", + "Некорректная длина ключа" +); +localized_msg!( + two_factor_totp_code_not_number, + "two_factor.totp_code_not_number", + "TOTP code is not a number", + "Код TOTP не является числом" +); +localized_msg!( + two_factor_empty_duo_authorization_code, + "two_factor.empty_duo_authorization_code", + "Empty Duo authorization code", + "Пустой код авторизации Duo" +); +localized_msg!( + two_factor_duo_validation_mismatch, + "two_factor.duo_validation_mismatch", + "Error validating Duo authorization, nonce or username mismatch.", + "Ошибка проверки авторизации Duo: nonce или имя пользователя не совпадают." +); +localized_msg!( + two_factor_failed_validate_duo_credentials, + "two_factor.failed_validate_duo_credentials", + "Failed to validate Duo credentials", + "Не удалось проверить учетные данные Duo" +); +localized_msg!( + two_factor_cant_fetch_duo_keys, + "two_factor.cant_fetch_duo_keys", + "Can't fetch Duo keys", + "Не удалось получить ключи Duo" +); +localized_msg!(two_factor_email_disabled, "two_factor.email_disabled", "Email 2FA is disabled", "Email 2FA отключен"); +localized_msg!( + two_factor_auth_request_not_found, + "two_factor.auth_request_not_found", + "AuthRequest doesn't exist", + "AuthRequest не существует" +); +localized_msg!(two_factor_user_not_found, "two_factor.user_not_found", "User not found", "Пользователь не найден"); +localized_msg!( + two_factor_no_auth_request_access_code, + "two_factor.no_auth_request_access_code", + "No auth request access code", + "Нет кода доступа auth request" +); +localized_msg!( + two_factor_invalid_device_ip_or_code, + "two_factor.invalid_device_ip_or_code", + "Invalid device, IP or code", + "Некорректное устройство, IP или код" +); +localized_msg!( + two_factor_no_password_hash_submitted, + "two_factor.no_password_hash_submitted", + "No password hash has been submitted.", + "Хэш пароля не был передан." +); +localized_msg!( + two_factor_no_device_identifier_submitted, + "two_factor.no_device_identifier_submitted", + "No device identifier has been submitted.", + "Идентификатор устройства не был передан." +); +localized_msg!( + two_factor_not_found, + "two_factor.not_found", + "Two factor not found", + "Двухфакторная аутентификация не найдена" +); +localized_msg!(two_factor_token_empty, "two_factor.token_empty", "Token is empty", "Токен пуст"); +localized_msg!( + two_factor_no_token_available, + "two_factor.no_token_available", + "No token available", + "Токен недоступен" +); +localized_msg!(two_factor_token_invalid, "two_factor.token_invalid", "Token is invalid", "Токен некорректен"); +localized_msg!( + two_factor_decode_email_token_data_failed, + "two_factor.decode_email_token_data_failed", + "Could not decode EmailTokenData from string", + "Не удалось декодировать EmailTokenData из строки" +); +localized_msg!( + two_factor_auto_enable_email_requires_verified, + "two_factor.auto_enable_email_requires_verified", + "Auto-enabling of email 2FA failed because the users email address has not been verified!", + "Автовключение email 2FA не удалось, потому что email пользователя не подтвержден!" +); +localized_msg!( + two_factor_user_not_found_exclam, + "two_factor.user_not_found_exclam", + "User not found!", + "Пользователь не найден!" +); +localized_msg!( + two_factor_decode_protected_action_data_failed, + "two_factor.decode_protected_action_data_failed", + "Could not decode ProtectedActionData from string", + "Не удалось декодировать ProtectedActionData из строки" +); +localized_msg!( + two_factor_protected_action_token_not_found, + "two_factor.protected_action_token_not_found", + "Protected action token not found, try sending the code again or restart the process", + "Токен защищенного действия не найден: отправьте код заново или перезапустите процесс" +); +localized_msg!(two_factor_token_expired, "two_factor.token_expired", "Token has expired", "Срок действия токена истек"); +localized_msg!( + two_factor_request_otp_wait_seconds, + "two_factor.request_otp_wait_seconds", + "Please wait {} seconds before requesting another code.", + "Подождите {} секунд перед запросом нового кода." +); +localized_msg!( + two_factor_webauthn_domain_incompatible, + "two_factor.webauthn_domain_incompatible", + "Configured `DOMAIN` is not compatible with Webauthn", + "Настроенный DOMAIN несовместим с WebAuthn" +); +localized_msg!( + two_factor_cannot_recover_challenge, + "two_factor.cannot_recover_challenge", + "Can't recover challenge", + "Не удалось восстановить challenge" +); +localized_msg!( + two_factor_webauthn_data_not_found, + "two_factor.webauthn_data_not_found", + "Webauthn data not found!", + "Данные WebAuthn не найдены!" +); +localized_msg!( + two_factor_webauthn_entry_not_found, + "two_factor.webauthn_entry_not_found", + "Webauthn entry not found", + "Запись WebAuthn не найдена" +); +localized_msg!( + two_factor_error_parsing_u2f_data, + "two_factor.error_parsing_u2f_data", + "Error parsing U2F data", + "Ошибка разбора данных U2F" +); +localized_msg!( + two_factor_no_webauthn_devices_registered, + "two_factor.no_webauthn_devices_registered", + "No Webauthn devices registered", + "Устройства WebAuthn не зарегистрированы" +); +localized_msg!( + two_factor_yubico_support_disabled, + "two_factor.yubico_support_disabled", + "Yubico support is disabled", + "Поддержка Yubico отключена" +); +localized_msg!( + two_factor_yubico_credentials_not_set, + "two_factor.yubico_credentials_not_set", + "`YUBICO_CLIENT_ID` or `YUBICO_SECRET_KEY` environment variable is not set. Yubikey OTP Disabled", + "Переменная окружения YUBICO_CLIENT_ID или YUBICO_SECRET_KEY не установлена. OTP YubiKey отключен" +); +localized_msg!(two_factor_key_required, "two_factor.key_required", "A key is required.", "Требуется ключ."); +localized_msg!( + two_factor_invalid_yubikey_otp_length, + "two_factor.invalid_yubikey_otp_length", + "Invalid Yubikey OTP length", + "Некорректная длина OTP YubiKey" +); +localized_msg!( + two_factor_invalid_yubikey_otp, + "two_factor.invalid_yubikey_otp", + "Invalid Yubikey OTP", + "Некорректный OTP YubiKey" +); +localized_msg!( + two_factor_invalid_yubikey_otp_provided, + "two_factor.invalid_yubikey_otp_provided", + "Invalid Yubikey OTP provided", + "Передан некорректный OTP YubiKey" +); +localized_msg!( + two_factor_given_yubikey_not_registered, + "two_factor.given_yubikey_not_registered", + "Given Yubikey is not registered", + "Указанный YubiKey не зарегистрирован" +); +localized_msg!( + two_factor_failed_verify_otp, + "two_factor.failed_verify_otp", + "Failed to verify OTP", + "Не удалось проверить OTP" +); +localized_msg!( + two_factor_failed_verify_yubikey_against_otp_server, + "two_factor.failed_verify_yubikey_against_otp_server", + "Failed to verify Yubikey against OTP server", + "Не удалось проверить YubiKey через OTP сервер" +); +localized_msg!( + two_factor_totp_key_mismatch_cannot_deactivate, + "two_factor.totp_key_mismatch_cannot_deactivate", + "TOTP key does not match recorded value, cannot deactivate", + "Ключ TOTP не совпадает с сохраненным значением, отключение невозможно" +); +localized_msg!( + two_factor_failed_decode_verification_token, + "two_factor.failed_decode_verification_token", + "Failed to decode verification token", + "Не удалось декодировать verification токен" +); +localized_msg!( + two_factor_duo_error_encoding_jwt, + "two_factor.duo_error_encoding_jwt", + "Error encoding Duo JWT", + "Ошибка кодирования Duo JWT" +); +localized_msg!( + two_factor_duo_error_requesting_health_check, + "two_factor.duo_error_requesting_health_check", + "Error requesting Duo health check", + "Ошибка запроса проверки работоспособности Duo" +); +localized_msg!( + two_factor_duo_health_check_decode_error, + "two_factor.duo_health_check_decode_error", + "Duo health check response decode error", + "Ошибка декодирования ответа проверки работоспособности Duo" +); +localized_msg!( + two_factor_duo_health_check_fail_response, + "two_factor.duo_health_check_fail_response", + "Duo health check FAIL response", + "Ответ FAIL от проверки работоспособности Duo" +); +localized_msg!( + two_factor_duo_health_check_failed_stat, + "two_factor.duo_health_check_failed_stat", + "Duo health check failed with unexpected stat", + "Проверка работоспособности Duo завершилась с неожиданным stat" +); +localized_msg!( + two_factor_duo_error_parsing_authorization_url, + "two_factor.duo_error_parsing_authorization_url", + "Error parsing Duo authorization URL", + "Ошибка разбора URL авторизации Duo" +); +localized_msg!( + two_factor_duo_error_exchanging_code, + "two_factor.duo_error_exchanging_code", + "Error exchanging Duo code", + "Ошибка обмена кода Duo" +); +localized_msg!( + two_factor_duo_failure_response, + "two_factor.duo_failure_response", + "Failure response from Duo", + "Ответ ошибки от Duo" +); +localized_msg!( + two_factor_duo_error_decoding_id_token_response, + "two_factor.duo_error_decoding_id_token_response", + "Error decoding ID token response", + "Ошибка декодирования ответа ID token" +); +localized_msg!( + two_factor_duo_failed_decode_token, + "two_factor.duo_failed_decode_token", + "Failed to decode Duo token", + "Не удалось декодировать токен Duo" +); +localized_msg!( + two_factor_duo_error_parsing_configured_domain_url, + "two_factor.duo_error_parsing_configured_domain_url", + "Error parsing configured domain URL", + "Ошибка разбора настроенного URL домена" +); +localized_msg!( + two_factor_duo_error_constructing_redirect_url, + "two_factor.duo_error_constructing_redirect_url", + "Error constructing Duo redirect URL", + "Ошибка построения URL редиректа Duo" +); +localized_msg!( + two_factor_duo_error_saving_auth_context, + "two_factor.duo_error_saving_auth_context", + "Error saving Duo authentication context", + "Ошибка сохранения контекста аутентификации Duo" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_user, + "two_factor.invalid_verification_token_invalid_user", + "Invalid verification token: Invalid user", + "Некорректный verification токен: неверный пользователь" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_state, + "two_factor.invalid_verification_token_invalid_state", + "Invalid verification token: Invalid state", + "Некорректный verification токен: неверное состояние" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_key, + "two_factor.invalid_verification_token_invalid_key", + "Invalid verification token: Invalid key", + "Некорректный verification токен: неверный ключ" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_duo_data, + "two_factor.invalid_verification_token_invalid_duo_data", + "Invalid verification token: Invalid duo data", + "Некорректный verification токен: неверные данные Duo" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_email, + "two_factor.invalid_verification_token_invalid_email", + "Invalid verification token: Invalid email", + "Некорректный verification токен: неверный email" +); +localized_msg!( + two_factor_invalid_verification_token_invalid_keys, + "two_factor.invalid_verification_token_invalid_keys", + "Invalid verification token: Invalid keys", + "Некорректный verification токен: неверные ключи" +); +localized_msg!( + api_no_validation_provided, + "api.no_validation_provided", + "No validation provided", + "Проверка не предоставлена" +); +localized_msg!(api_invalid_url, "api.invalid_url", "Invalid URL", "Некорректный URL"); +localized_msg!(api_invalid_host, "api.invalid_host", "Invalid host", "Некорректный хост"); +localized_msg!(api_invalid_start_date, "api.invalid_start_date", "Invalid start date", "Некорректная начальная дата"); +localized_msg!(api_invalid_end_date, "api.invalid_end_date", "Invalid end date", "Некорректная конечная дата"); +localized_msg!(api_invalid_event_date, "api.invalid_event_date", "Invalid event date", "Некорректная дата события"); +localized_msg!( + api_template_missing_subject, + "api.template_missing_subject", + "Template doesn't contain subject", + "В шаблоне отсутствует тема" +); +localized_msg!( + api_template_missing_body, + "api.template_missing_body", + "Template doesn't contain body", + "В шаблоне отсутствует тело" +); +localized_msg!( + api_template_more_than_one_body, + "api.template_more_than_one_body", + "Template contains more than one body", + "Шаблон содержит больше одного тела" +); +localized_msg!( + api_failed_build_verify_url_query_params, + "api.failed_build_verify_url_query_params", + "Failed to build verify URL query parameters", + "Не удалось сформировать query-параметры verify URL" +); +localized_msg!( + api_failed_build_invite_url_query_params, + "api.failed_build_invite_url_query_params", + "Failed to build invite URL query parameters", + "Не удалось сформировать query-параметры invite URL" +); +localized_msg!( + api_failed_build_emergency_invite_url_query_params, + "api.failed_build_emergency_invite_url_query_params", + "Failed to build emergency invite URL query parameters", + "Не удалось сформировать query-параметры emergency invite URL" +); +localized_msg!( + api_number_not_fit_i32, + "api.number_not_fit_i32", + "Number does not fit in i32", + "Число не помещается в i32" +); +localized_msg!( + api_event_retention_date_calculation_failed, + "api.event_retention_date_calculation_failed", + "Unable to calculate the event retention date, check 'EVENTS_DAYS_RETAIN'", + "Не удалось вычислить дату хранения событий, проверьте 'EVENTS_DAYS_RETAIN'" +); +localized_msg!( + api_failed_get_db_connection_purging_expired_sso_auth, + "api.failed_get_db_connection_purging_expired_sso_auth", + "Failed to get DB connection while purging expired sso_auth", + "Не удалось получить соединение с БД при очистке устаревших sso_auth" +); +localized_msg!( + api_db_timeout_waiting_connection, + "api.db_timeout_waiting_connection", + "Timeout waiting for database connection", + "Таймаут ожидания соединения с базой данных" +); +localized_msg!( + api_static_file_not_found, + "api.static_file_not_found", + "Static file not found", + "Статический файл не найден" +); +localized_msg!( + api_log_level_format_invalid, + "api.log_level_format_invalid", + "LOG_LEVEL should follow the expected format", + "LOG_LEVEL должен соответствовать ожидаемому формату" +); +localized_msg!( + api_failed_activate_logger, + "api.failed_activate_logger", + "Failed to activate logger", + "Не удалось активировать логгер" +); +localized_msg!( + push_error_get_token_from_server, + "push.error_get_token_from_server", + "Error getting push token from bitwarden server", + "Ошибка получения push токена с сервера bitwarden" +); +localized_msg!( + push_unexpected_token_from_server, + "push.unexpected_token_from_server", + "Unexpected push token received from bitwarden server", + "Получен неожиданный push токен от сервера bitwarden" +); +localized_msg!( + push_error_register_device, + "push.error_register_device", + "An error occurred while proceeding registration of a device", + "Произошла ошибка при регистрации устройства" +); +localized_msg!( + push_error_save_registered_push_uuid, + "push.error_save_registered_push_uuid", + "An error occurred while trying to save the (registered) device push uuid", + "Произошла ошибка при сохранении push uuid зарегистрированного устройства" +); +localized_msg!( + push_error_device_unregistration, + "push.error_device_unregistration", + "An error occurred during device unregistration", + "Произошла ошибка при отмене регистрации устройства" +); +#[cfg(not(mysql))] +localized_msg!( + api_db_url_mysql_feature_not_enabled, + "api.db_url_mysql_feature_not_enabled", + "`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled", + "`DATABASE_URL` указывает на MySQL, но функция 'mysql' не включена" +); +#[cfg(not(postgresql))] +localized_msg!( + api_db_url_postgresql_feature_not_enabled, + "api.db_url_postgresql_feature_not_enabled", + "`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled", + "`DATABASE_URL` указывает на PostgreSQL, но функция 'postgresql' не включена" +); +#[cfg(not(sqlite))] +localized_msg!( + api_db_url_sqlite_feature_not_enabled, + "api.db_url_sqlite_feature_not_enabled", + "`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled", + "`DATABASE_URL` указывает на SQLite, но функция 'sqlite' не включена" +); +#[cfg(not(sqlite))] +localized_msg!( + api_db_url_unknown_scheme, + "api.db_url_unknown_scheme", + "`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://)", + "`DATABASE_URL` не соответствует известным схемам базы данных (mysql://, postgresql://, sqlite://)" +); +localized_msg!( + db_failed_create_pool, + "db.failed_create_pool", + "Failed to create pool", + "Не удалось создать пул соединений" +); +localized_msg!( + db_error_retrieving_connection_from_pool, + "db.error_retrieving_connection_from_pool", + "Error retrieving connection from pool", + "Ошибка получения соединения из пула" +); +#[cfg(sqlite)] +localized_msg!(db_vacuum_into_failed, "db.vacuum_into_failed", "VACUUM INTO failed", "VACUUM INTO завершился ошибкой"); +localized_msg!( + db_error_saving_sso_auth, + "db.error_saving_sso_auth", + "Error saving SSO auth", + "Ошибка сохранения SSO auth" +); +localized_msg!( + db_error_deleting_sso_auth, + "db.error_deleting_sso_auth", + "Error deleting sso_auth", + "Ошибка удаления sso_auth" +); +localized_msg!( + db_error_deleting_expired_sso_nonce, + "db.error_deleting_expired_sso_nonce", + "Error deleting expired SSO nonce", + "Ошибка удаления устаревшего SSO nonce" +); +localized_msg!( + db_error_saving_twofactor, + "db.error_saving_twofactor", + "Error saving twofactor", + "Ошибка сохранения twofactor" +); +#[cfg(postgresql)] +localized_msg!( + db_error_deleting_twofactor_for_insert, + "db.error_deleting_twofactor_for_insert", + "Error deleting twofactor for insert", + "Ошибка удаления twofactor перед вставкой" +); +localized_msg!( + db_error_deleting_twofactor, + "db.error_deleting_twofactor", + "Error deleting twofactor", + "Ошибка удаления twofactor" +); +localized_msg!( + db_error_deleting_twofactors, + "db.error_deleting_twofactors", + "Error deleting twofactors", + "Ошибка удаления twofactors" +); +localized_msg!( + db_error_saving_context_twofactor_duo_ctx, + "db.error_saving_context_twofactor_duo_ctx", + "Error saving context to twofactor_duo_ctx", + "Ошибка сохранения контекста в twofactor_duo_ctx" +); +localized_msg!( + db_error_deleting_from_twofactor_duo_ctx, + "db.error_deleting_from_twofactor_duo_ctx", + "Error deleting from twofactor_duo_ctx", + "Ошибка удаления из twofactor_duo_ctx" +); +localized_msg!( + db_error_adding_twofactor_incomplete_record, + "db.error_adding_twofactor_incomplete_record", + "Error adding twofactor_incomplete record", + "Ошибка добавления записи twofactor_incomplete" +); +localized_msg!( + db_error_delete_by_user_and_device_twofactor_incomplete, + "db.error_delete_by_user_and_device_twofactor_incomplete", + "Error in twofactor_incomplete::delete_by_user_and_device()", + "Ошибка в twofactor_incomplete::delete_by_user_and_device()" +); +localized_msg!( + db_error_delete_all_by_user_twofactor_incomplete, + "db.error_delete_all_by_user_twofactor_incomplete", + "Error in twofactor_incomplete::delete_all_by_user()", + "Ошибка в twofactor_incomplete::delete_all_by_user()" +); +localized_msg!(db_error_saving_archive, "db.error_saving_archive", "Error saving archive", "Ошибка сохранения archive"); +localized_msg!( + db_error_deleting_archive, + "db.error_deleting_archive", + "Error deleting archive", + "Ошибка удаления archive" +); +localized_msg!( + db_error_saving_attachment, + "db.error_saving_attachment", + "Error saving attachment", + "Ошибка сохранения attachment" +); +localized_msg!( + db_error_deleting_attachment, + "db.error_deleting_attachment", + "Error deleting attachment", + "Ошибка удаления attachment" +); +localized_msg!( + db_error_saving_auth_request, + "db.error_saving_auth_request", + "Error saving auth_request", + "Ошибка сохранения auth_request" +); +localized_msg!( + db_error_deleting_auth_request, + "db.error_deleting_auth_request", + "Error deleting auth request", + "Ошибка удаления auth request" +); +localized_msg!( + db_error_deleting_auth_requests_for_user, + "db.error_deleting_auth_requests_for_user", + "Error deleting auth requests for user", + "Ошибка удаления auth request для пользователя" +); +localized_msg!( + db_error_updating_auth_request, + "db.error_updating_auth_request", + "Error updating auth request", + "Ошибка обновления auth request" +); +localized_msg!(db_error_saving_cipher, "db.error_saving_cipher", "Error saving cipher", "Ошибка сохранения cipher"); +localized_msg!(db_error_deleting_cipher, "db.error_deleting_cipher", "Error deleting cipher", "Ошибка удаления cipher"); +localized_msg!( + db_cipher_invalid_type, + "db.cipher_invalid_type", + "Cipher has an invalid type", + "У cipher некорректный тип" +); +localized_msg!( + db_error_saving_collection, + "db.error_saving_collection", + "Error saving collection", + "Ошибка сохранения collection" +); +localized_msg!( + db_error_deleting_collection, + "db.error_deleting_collection", + "Error deleting collection", + "Ошибка удаления collection" +); +localized_msg!( + db_error_adding_user_to_collection, + "db.error_adding_user_to_collection", + "Error adding user to collection", + "Ошибка добавления пользователя в collection" +); +localized_msg!( + db_error_removing_user_from_collection, + "db.error_removing_user_from_collection", + "Error removing user from collection", + "Ошибка удаления пользователя из collection" +); +localized_msg!( + db_error_deleting_users_from_collection, + "db.error_deleting_users_from_collection", + "Error deleting users from collection", + "Ошибка удаления пользователей из collection" +); +localized_msg!( + db_error_removing_user_from_collections, + "db.error_removing_user_from_collections", + "Error removing user from collections", + "Ошибка удаления пользователя из collections" +); +localized_msg!( + db_error_adding_cipher_to_collection, + "db.error_adding_cipher_to_collection", + "Error adding cipher to collection", + "Ошибка добавления cipher в collection" +); +localized_msg!( + db_error_deleting_cipher_from_collection, + "db.error_deleting_cipher_from_collection", + "Error deleting cipher from collection", + "Ошибка удаления cipher из collection" +); +localized_msg!( + db_error_removing_cipher_from_collections, + "db.error_removing_cipher_from_collections", + "Error removing cipher from collections", + "Ошибка удаления cipher из collections" +); +localized_msg!( + db_error_removing_ciphers_from_collection, + "db.error_removing_ciphers_from_collection", + "Error removing ciphers from collection", + "Ошибка удаления ciphers из collection" +); +localized_msg!(db_error_saving_device, "db.error_saving_device", "Error saving device", "Ошибка сохранения device"); +localized_msg!( + db_error_removing_devices_for_user, + "db.error_removing_devices_for_user", + "Error removing devices for user", + "Ошибка удаления устройств пользователя" +); +localized_msg!( + db_error_removing_push_token, + "db.error_removing_push_token", + "Error removing push token", + "Ошибка удаления push token" +); +localized_msg!( + db_error_removing_twofactor_remember_tokens, + "db.error_removing_twofactor_remember_tokens", + "Error removing two factor remember tokens", + "Ошибка удаления токенов запоминания 2FA" +); +localized_msg!(db_error_saving_send, "db.error_saving_send", "Error saving send", "Ошибка сохранения send"); +localized_msg!(db_error_deleting_send, "db.error_deleting_send", "Error deleting send", "Ошибка удаления send"); +localized_msg!(db_error_saving_group, "db.error_saving_group", "Error saving group", "Ошибка сохранения group"); +localized_msg!(db_error_deleting_group, "db.error_deleting_group", "Error deleting group", "Ошибка удаления group"); +localized_msg!( + db_error_updating_group_revision, + "db.error_updating_group_revision", + "Error updating group revision", + "Ошибка обновления ревизии group" +); +localized_msg!( + db_error_adding_group_to_collection, + "db.error_adding_group_to_collection", + "Error adding group to collection", + "Ошибка добавления group в collection" +); +localized_msg!( + db_error_deleting_collection_group, + "db.error_deleting_collection_group", + "Error deleting collection group", + "Ошибка удаления группы из collection" +); +localized_msg!( + db_error_adding_user_to_group, + "db.error_adding_user_to_group", + "Error adding user to group", + "Ошибка добавления пользователя в group" +); +localized_msg!( + db_error_deleting_group_users, + "db.error_deleting_group_users", + "Error deleting group users", + "Ошибка удаления пользователей group" +); +localized_msg!( + db_error_deleting_user_groups, + "db.error_deleting_user_groups", + "Error deleting user groups", + "Ошибка удаления групп пользователя" +); +localized_msg!( + db_error_saving_org_policy, + "db.error_saving_org_policy", + "Error saving org_policy", + "Ошибка сохранения org_policy" +); +#[cfg(postgresql)] +localized_msg!( + db_error_deleting_org_policy_for_insert, + "db.error_deleting_org_policy_for_insert", + "Error deleting org_policy for insert", + "Ошибка удаления org_policy перед вставкой" +); +localized_msg!( + db_error_deleting_org_policy, + "db.error_deleting_org_policy", + "Error deleting org_policy", + "Ошибка удаления org_policy" +); +localized_msg!( + db_error_saving_organization, + "db.error_saving_organization", + "Error saving organization", + "Ошибка сохранения organization" +); +localized_msg!( + db_billing_email_not_valid, + "db.billing_email_not_valid", + "BillingEmail is not a valid email address", + "BillingEmail не является корректным email адресом" +); +localized_msg!( + db_error_adding_user_to_organization, + "db.error_adding_user_to_organization", + "Error adding user to organization", + "Ошибка добавления пользователя в organization" +); +localized_msg!( + db_error_removing_user_from_organization, + "db.error_removing_user_from_organization", + "Error removing user from organization", + "Ошибка удаления пользователя из organization" +); +localized_msg!( + db_error_confirming_invitations, + "db.error_confirming_invitations", + "Error confirming invitations", + "Ошибка подтверждения приглашений" +); +localized_msg!( + db_error_removing_organization_api_key_from_organization, + "db.error_removing_organization_api_key_from_organization", + "Error removing organization api key from organization", + "Ошибка удаления organization api key из organization" +); +localized_msg!(db_error_saving_user, "db.error_saving_user", "Error saving user", "Ошибка сохранения user"); +localized_msg!( + db_user_email_not_valid, + "db.user_email_not_valid", + "User email is not a valid email address", + "Email пользователя не является корректным email адресом" +); +localized_msg!(db_error_deleting_user, "db.error_deleting_user", "Error deleting user", "Ошибка удаления user"); +localized_msg!( + db_error_updating_revision_date_for_all_users, + "db.error_updating_revision_date_for_all_users", + "Error updating revision date for all users", + "Ошибка обновления даты ревизии для всех пользователей" +); +localized_msg!( + db_error_updating_user_revision, + "db.error_updating_user_revision", + "Error updating user revision", + "Ошибка обновления ревизии user" +); +localized_msg!( + db_error_saving_invitation, + "db.error_saving_invitation", + "Error saving invitation", + "Ошибка сохранения invitation" +); +localized_msg!( + db_invitation_email_not_valid, + "db.invitation_email_not_valid", + "Invitation email is not a valid email address", + "Email приглашения не является корректным email адресом" +); +localized_msg!( + db_error_deleting_invitation, + "db.error_deleting_invitation", + "Error deleting invitation", + "Ошибка удаления invitation" +); +localized_msg!( + db_error_saving_sso_user, + "db.error_saving_sso_user", + "Error saving SSO user", + "Ошибка сохранения SSO user" +); +localized_msg!( + db_error_deleting_sso_user, + "db.error_deleting_sso_user", + "Error deleting sso user", + "Ошибка удаления sso user" +); +localized_msg!( + db_emergency_access_initiation_date_missing, + "db.emergency_access_initiation_date_missing", + "Emergency access initiation date missing!", + "Отсутствует дата инициации экстренного доступа!" +); +localized_msg!( + db_emergency_access_deadline_invalid, + "db.emergency_access_deadline_invalid", + "Emergency access deadline is invalid", + "Некорректный срок экстренного доступа" +); +localized_msg!( + db_error_saving_emergency_access, + "db.error_saving_emergency_access", + "Error saving emergency access", + "Ошибка сохранения emergency access" +); +localized_msg!( + db_error_updating_emergency_access_status, + "db.error_updating_emergency_access_status", + "Error updating emergency access status", + "Ошибка обновления статуса emergency access" +); +localized_msg!( + db_error_removing_user_from_emergency_access, + "db.error_removing_user_from_emergency_access", + "Error removing user from emergency access", + "Ошибка удаления пользователя из emergency access" +); +localized_msg!(db_error_saving_event, "db.error_saving_event", "Error saving event", "Ошибка сохранения event"); +localized_msg!(db_error_deleting_event, "db.error_deleting_event", "Error deleting event", "Ошибка удаления event"); +localized_msg!( + db_error_cleaning_old_events, + "db.error_cleaning_old_events", + "Error cleaning old events", + "Ошибка очистки старых событий" +); +localized_msg!( + db_error_adding_favorite, + "db.error_adding_favorite", + "Error adding favorite", + "Ошибка добавления favorite" +); +localized_msg!( + db_error_removing_favorite, + "db.error_removing_favorite", + "Error removing favorite", + "Ошибка удаления favorite" +); +localized_msg!( + db_error_removing_favorites_by_cipher, + "db.error_removing_favorites_by_cipher", + "Error removing favorites by cipher", + "Ошибка удаления favorites по cipher" +); +localized_msg!( + db_error_removing_favorites_by_user, + "db.error_removing_favorites_by_user", + "Error removing favorites by user", + "Ошибка удаления favorites по пользователю" +); +localized_msg!(db_error_saving_folder, "db.error_saving_folder", "Error saving folder", "Ошибка сохранения folder"); +localized_msg!(db_error_deleting_folder, "db.error_deleting_folder", "Error deleting folder", "Ошибка удаления folder"); +localized_msg!( + db_error_adding_cipher_to_folder, + "db.error_adding_cipher_to_folder", + "Error adding cipher to folder", + "Ошибка добавления cipher в folder" +); +localized_msg!( + db_error_removing_cipher_from_folder, + "db.error_removing_cipher_from_folder", + "Error removing cipher from folder", + "Ошибка удаления cipher из folder" +); +localized_msg!( + db_error_removing_cipher_from_folders, + "db.error_removing_cipher_from_folders", + "Error removing cipher from folders", + "Ошибка удаления cipher из folders" +); +localized_msg!( + db_error_removing_ciphers_from_folder, + "db.error_removing_ciphers_from_folder", + "Error removing ciphers from folder", + "Ошибка удаления ciphers из folder" +); +localized_msg!( + mail_sendmail_client_error, + "mail.sendmail_client_error", + "Sendmail client error", + "Ошибка клиента Sendmail" +); +localized_msg!( + mail_sendmail_response_error, + "mail.sendmail_response_error", + "Sendmail response error", + "Ошибка ответа Sendmail" +); +localized_msg!(mail_sendmail_error, "mail.sendmail_error", "Sendmail error", "Ошибка Sendmail"); +localized_msg!(mail_smtp_client_error, "mail.smtp_client_error", "SMTP client error", "Ошибка SMTP-клиента"); +localized_msg!(mail_smtp_4xx_error, "mail.smtp_4xx_error", "SMTP 4xx error", "SMTP ошибка 4xx"); +localized_msg!(mail_smtp_5xx_error, "mail.smtp_5xx_error", "SMTP 5xx error", "SMTP ошибка 5xx"); +localized_msg!(mail_smtp_timeout_error, "mail.smtp_timeout_error", "SMTP timeout error", "SMTP ошибка таймаута"); +localized_msg!( + mail_smtp_encryption_error, + "mail.smtp_encryption_error", + "SMTP encryption error", + "SMTP ошибка шифрования" +); +localized_msg!(mail_smtp_error, "mail.smtp_error", "SMTP error", "Ошибка SMTP"); +localized_msg!( + emergency_access_not_valid, + "emergency_access.not_valid", + "Emergency access not valid.", + "Экстренный доступ недействителен." +); +localized_msg!( + emergency_access_invalid_type, + "emergency_access.invalid_type", + "Invalid emergency access type.", + "Некорректный тип экстренного доступа." +); +localized_msg!( + emergency_access_wait_time_out_of_bounds, + "emergency_access.wait_time_out_of_bounds", + "Emergency access wait time is out-of-bounds!", + "Время ожидания экстренного доступа вне допустимых границ!" +); +localized_msg!( + emergency_access_cannot_set_self, + "emergency_access.cannot_set_self", + "You can not set yourself as an emergency contact.", + "Нельзя указать себя как контакт экстренного доступа." +); +localized_msg!( + emergency_access_email_domain_not_eligible, + "emergency_access.email_domain_not_eligible", + "Email domain not eligible for invitations", + "Домен email не подходит для приглашений" +); +localized_msg!( + emergency_access_grantee_already_accepted_or_confirmed, + "emergency_access.grantee_already_accepted_or_confirmed", + "The grantee user is already accepted or confirmed for emergency access", + "Пользователь-получатель уже принял или подтвердил экстренный доступ" +); +localized_msg!( + emergency_access_email_not_valid, + "emergency_access.email_not_valid", + "Email not valid.", + "Email некорректен." +); +localized_msg!( + emergency_access_grantee_not_found, + "emergency_access.grantee_not_found", + "Grantee user not found.", + "Пользователь-получатель не найден." +); +localized_msg!( + emergency_access_claim_email_mismatch, + "emergency_access.claim_email_mismatch", + "Claim email does not match current users email", + "Email в claim не совпадает с текущим email пользователя" +); +localized_msg!( + emergency_access_invited_user_not_found, + "emergency_access.invited_user_not_found", + "Invited user not found", + "Приглашенный пользователь не найден" +); +localized_msg!( + emergency_access_grantor_not_found, + "emergency_access.grantor_not_found", + "Grantor user not found.", + "Пользователь-грантор не найден." +); +localized_msg!( + emergency_access_invitation_error, + "emergency_access.invitation_error", + "Emergency access invitation error.", + "Ошибка приглашения экстренного доступа." +); +localized_msg!( + emergency_access_kdf_mismatch_grantor, + "emergency_access.kdf_mismatch_grantor", + "KDF settings do not match the grantor account", + "Параметры KDF не совпадают с учетной записью грантора" +); +localized_msg!( + emergency_access_invalid_request, + "emergency_access.invalid_request", + "Invalid request!", + "Некорректный запрос!" +); +localized_msg!( + emergency_access_not_enabled, + "emergency_access.not_enabled", + "Emergency access is not enabled.", + "Экстренный доступ не включен." +); +localized_msg!( + emergency_access_status_changed_already, + "emergency_access.status_changed_already", + "Emergency access status was changed already", + "Статус экстренного доступа уже был изменен" +); +localized_msg!( + emergency_access_error_updating_status, + "emergency_access.error_updating_status", + "Error updating emergency access status", + "Ошибка обновления статуса экстренного доступа" +); +localized_msg!( + emergency_access_user_email_mismatch_invite, + "emergency_access.user_email_mismatch_invite", + "User email does not match invite.", + "Email пользователя не совпадает с приглашением." +); +localized_msg!( + emergency_access_contact_already_accepted, + "emergency_access.contact_already_accepted", + "Emergency contact already accepted.", + "Контакт экстренного доступа уже принял приглашение." +); +localized_msg!( + emergency_access_grantee_user_not_exists, + "emergency_access.grantee_user_not_exists", + "Grantee user does not exist", + "Пользователь-получатель не существует" +); +localized_msg!( + emergency_access_grantee_user_already_invited, + "emergency_access.grantee_user_already_invited", + "Grantee user already invited", + "Пользователь-получатель уже приглашен" +); +localized_msg!(folder_invalid, "folder.invalid", "Invalid folder", "Некорректная папка"); +localized_msg!( + folder_not_found_or_not_owned, + "folder.not_found_or_not_owned", + "Folder does not exist or belongs to another user", + "Папка не существует или принадлежит другому пользователю" +); +localized_msg!( + org_error_lookup_organization_short, + "org.error_lookup_organization_short", + "Error looking up organization", + "Ошибка при поиске организации" +); +localized_msg!(org_not_found_short, "org.not_found_short", "Organization not found.", "Организация не найдена."); +localized_msg!( + org_user_already_accepted_invite, + "org.user_already_accepted_invite", + "User already accepted the invitation", + "Пользователь уже принял приглашение" +); +localized_msg!( + org_user_already_in_organization, + "org.user_already_in_organization", + "User already in organization", + "Пользователь уже в организации" +); +localized_msg!( + org_error_sending_invite, + "org.error_sending_invite", + "Error sending invite", + "Ошибка отправки приглашения" +); +localized_msg!( + org_error_sending_user_reset_password_email, + "org.error_sending_user_reset_password_email", + "Error sending user reset password email", + "Ошибка отправки email о сбросе пароля пользователя" +); +localized_msg!( + org_policy_cannot_because_2fa_required, + "org.policy_cannot_because_2fa_required", + "Cannot proceed because 2FA is required", + "Невозможно выполнить действие, так как требуется 2FA" +); +localized_msg!( + org_policy_cannot_because_other_org_policy_forbids, + "org.policy_cannot_because_other_org_policy_forbids", + "Cannot proceed because another organization policy forbids it", + "Невозможно выполнить действие, так как это запрещено политикой другой организации" +); +localized_msg!(cipher_not_found, "cipher.not_found", "Cipher doesn't exist", "Шифр не существует"); +localized_msg!( + cipher_not_owned_by_user, + "cipher.not_owned_by_user", + "Cipher is not owned by user", + "Шифр не принадлежит пользователю" +); +localized_msg!( + cipher_personal_vault_restricted, + "cipher.personal_vault_restricted", + "Due to an Enterprise Policy, you are restricted from saving items to your personal vault.", + "Из-за корпоративной политики вам запрещено сохранять элементы в личном хранилище." +); +localized_msg!( + cipher_client_copy_outdated, + "cipher.client_copy_outdated", + "The client copy of this cipher is out of date. Resync the client and try again.", + "Локальная копия этого шифра устарела. Синхронизируйте клиент и попробуйте снова." +); +localized_msg!( + cipher_organization_mismatch, + "cipher.organization_mismatch", + "Organization mismatch. Please resync the client before updating the cipher", + "Несоответствие организации. Синхронизируйте клиент перед обновлением шифра" +); +localized_msg!( + cipher_no_permission_add_item_to_org, + "cipher.no_permission_add_item_to_org", + "You don't have permission to add item to organization", + "У вас нет прав добавлять элемент в организацию" +); +localized_msg!( + cipher_no_permission_add_cipher_direct_to_org, + "cipher.no_permission_add_cipher_direct_to_org", + "You don't have permission to add cipher directly to organization", + "У вас нет прав добавлять шифр напрямую в организацию" +); +localized_msg!(cipher_invalid_type, "cipher.invalid_type", "Invalid type", "Некорректный тип"); +localized_msg!(cipher_data_missing, "cipher.data_missing", "Data missing", "Отсутствуют данные"); +localized_msg!( + cipher_notes_exceeds_max_len, + "cipher.notes_exceeds_max_len", + "The field Notes exceeds the maximum encrypted value length of {} characters.", + "Поле Notes превышает максимальную длину зашифрованного значения: {} символов." +); +localized_msg!( + cipher_password_history_null_only_strings, + "cipher.password_history_null_only_strings", + "The password history contains a `null` value. Only strings are allowed.", + "История паролей содержит значение `null`. Допускаются только строки." +); +localized_msg!( + cipher_model_state_invalid, + "cipher.model_state_invalid", + "The model state is invalid.", + "Состояние модели некорректно." +); +localized_msg!( + cipher_import_validation_errors, + "cipher.import_validation_errors", + "Import validation errors", + "Ошибки валидации импорта" +); +localized_msg!( + cipher_not_write_accessible, + "cipher.not_write_accessible", + "Cipher is not write accessible", + "Шифр недоступен для записи" +); +localized_msg!( + cipher_collection_cannot_be_changed, + "cipher.collection_cannot_be_changed", + "Collection cannot be changed", + "Коллекцию нельзя изменить" +); +localized_msg!( + cipher_not_owned_by_org, + "cipher.not_owned_by_org", + "Cipher is not owned by an organization", + "Шифр не принадлежит организации" +); +localized_msg!( + cipher_invalid_collection_id, + "cipher.invalid_collection_id", + "Invalid collection ID provided", + "Указан некорректный ID коллекции" +); +localized_msg!( + cipher_no_rights_modify_collection, + "cipher.no_rights_modify_collection", + "No rights to modify the collection", + "Недостаточно прав для изменения коллекции" +); +localized_msg!( + cipher_organization_id_required, + "cipher.organization_id_required", + "Cipher OrganizationId is required.", + "Требуется OrganizationId для шифра." +); +localized_msg!( + cipher_at_least_one_collection_required, + "cipher.at_least_one_collection_required", + "You must select at least one collection.", + "Нужно выбрать хотя бы одну коллекцию." +); +localized_msg!( + cipher_at_least_one_cipher_required, + "cipher.at_least_one_cipher_required", + "You must select at least one cipher.", + "Нужно выбрать хотя бы один шифр." +); +localized_msg!( + cipher_request_missing_ids, + "cipher.request_missing_ids", + "Request missing ids field", + "В запросе отсутствует поле ids" +); +localized_msg!(cipher_not_accessible, "cipher.not_accessible", "Cipher is not accessible", "Шифр недоступен"); +localized_msg!( + cipher_neither_user_nor_org_owned, + "cipher.neither_user_nor_org_owned", + "Cipher is neither owned by a user nor an organization", + "Шифр не принадлежит ни пользователю, ни организации" +); +localized_msg!( + cipher_attachments_disabled, + "cipher.attachments_disabled", + "Attachments are disabled", + "Вложения отключены" +); +localized_msg!( + cipher_attachment_size_overflow, + "cipher.attachment_size_overflow", + "Attachment size overflow", + "Переполнение размера вложения" +); +localized_msg!( + cipher_attachment_storage_limit_reached, + "cipher.attachment_storage_limit_reached", + "Attachment storage limit reached! Delete some attachments to free up space", + "Достигнут лимит хранилища вложений! Удалите часть вложений, чтобы освободить место" +); +localized_msg!( + cipher_attachment_size_negative, + "cipher.attachment_size_negative", + "Attachment size can't be negative", + "Размер вложения не может быть отрицательным" +); +localized_msg!( + cipher_max_file_size_525mb, + "cipher.max_file_size_525mb", + "Max file size is 525 MB.", + "Максимальный размер файла 525 MB." +); +localized_msg!( + cipher_attachment_storage_limit_exceeded_file, + "cipher.attachment_storage_limit_exceeded_file", + "Attachment storage limit exceeded with this file", + "Лимит хранилища вложений будет превышен этим файлом" +); +localized_msg!( + cipher_attachment_size_mismatch, + "cipher.attachment_size_mismatch", + "Attachment size mismatch", + "Несоответствие размера вложения" +); +localized_msg!( + cipher_attachment_data_size_overflow, + "cipher.attachment_data_size_overflow", + "Attachment data size overflow", + "Переполнение размера данных вложения" +); +localized_msg!( + cipher_invalid_attachment_size_max, + "cipher.invalid_attachment_size_max", + "Invalid attachment size max", + "Некорректный максимальный размер вложения" +); +localized_msg!( + cipher_invalid_attachment_size_min, + "cipher.invalid_attachment_size_min", + "Invalid attachment size min", + "Некорректный минимальный размер вложения" +); +localized_msg!( + cipher_no_filename_provided, + "cipher.no_filename_provided", + "No filename provided", + "Имя файла не предоставлено" +); +localized_msg!( + cipher_no_attachment_key_provided, + "cipher.no_attachment_key_provided", + "No attachment key provided", + "Ключ вложения не предоставлен" +); +localized_msg!( + cipher_attachment_not_belong_to_cipher, + "cipher.attachment_not_belong_to_cipher", + "Attachment doesn't belong to cipher", + "Вложение не принадлежит этому шифру" +); +localized_msg!( + cipher_attachment_not_found, + "cipher.attachment_not_found", + "Attachment doesn't exist", + "Вложение не найдено" +); +localized_msg!( + cipher_no_permission_purge_org_vault, + "cipher.no_permission_purge_org_vault", + "You don't have permission to purge the organization vault", + "У вас нет прав очищать хранилище организации" +); +localized_msg!( + cipher_cannot_be_deleted_by_user, + "cipher.cannot_be_deleted_by_user", + "Cipher can't be deleted by user", + "Пользователь не может удалить этот шифр" +); +localized_msg!( + cipher_cannot_be_restored_by_user, + "cipher.cannot_be_restored_by_user", + "Cipher can't be restored by user", + "Пользователь не может восстановить этот шифр" +); +localized_msg!( + cipher_attachment_from_other_cipher, + "cipher.attachment_from_other_cipher", + "Attachment from other cipher", + "Вложение относится к другому шифру" +); +localized_msg!( + cipher_cannot_delete_by_user, + "cipher.cannot_delete_by_user", + "Cipher cannot be deleted by user", + "Этот шифр нельзя удалить пользователю" +); +localized_msg!( + cipher_not_accessible_for_current_user, + "cipher.not_accessible_for_current_user", + "Cipher is not accessible for the current user", + "Шифр недоступен текущему пользователю" +); +localized_msg!( + cipher_couldnt_move_from_previous_folder, + "cipher.couldnt_move_from_previous_folder", + "Couldn't move from previous folder", + "Не удалось переместить из предыдущей папки" +); +localized_msg!(org_not_found, "org.not_found", "Organization not found", "Организация не найдена"); +localized_msg!( + org_member_required, + "org.member_required", + "You need to be a Member of the Organization to call this endpoint", + "Для вызова этого endpoint необходимо быть участником организации" +); +localized_msg!( + org_user_not_part, + "org.user_not_part", + "User is not part of organization", + "Пользователь не состоит в организации" +); +localized_msg!(org_invalid_type, "org.invalid_type", "Invalid type", "Некорректный тип"); +localized_msg!( + org_only_owners_invite_privileged, + "org.only_owners_invite_privileged", + "Only Owners can invite Managers, Admins or Owners", + "Только владельцы могут приглашать менеджеров, администраторов или владельцев" +); +localized_msg!( + org_user_not_member, + "org.user_not_member", + "The specified user isn't a member of the organization", + "Указанный пользователь не является участником организации" +); +localized_msg!( + org_only_owners_confirm_privileged, + "org.only_owners_confirm_privileged", + "Only Owners can confirm Managers, Admins or Owners", + "Только владельцы могут подтверждать менеджеров, администраторов или владельцев" +); +localized_msg!( + org_user_invalid_state, + "org.user_invalid_state", + "User in invalid state", + "Пользователь в недопустимом состоянии" +); +localized_msg!( + org_only_owners_grant_remove_privileged, + "org.only_owners_grant_remove_privileged", + "Only Owners can grant and remove Admin or Owner privileges", + "Только владельцы могут выдавать или удалять права администратора/владельца" +); +localized_msg!( + org_only_owners_edit_owner_users, + "org.only_owners_edit_owner_users", + "Only Owners can edit Owner users", + "Только владельцы могут редактировать пользователей-владельцев" +); +localized_msg!( + org_cannot_delete_last_owner, + "org.cannot_delete_last_owner", + "Can't delete the last owner", + "Нельзя удалить последнего владельца" +); +localized_msg!( + org_user_not_invited, + "org.user_not_invited", + "The user hasn't been invited to the organization.", + "Пользователь не был приглашен в организацию." +); +localized_msg!( + org_user_already_accepted_or_confirmed, + "org.user_already_accepted_or_confirmed", + "The user is already accepted or confirmed to the organization", + "Пользователь уже принял приглашение или подтвержден в организации" +); +localized_msg!(org_user_not_found, "org.user_not_found", "User not found.", "Пользователь не найден."); +localized_msg!( + org_invitations_not_allowed, + "org.invitations_not_allowed", + "Invitations are not allowed.", + "Приглашения не разрешены." +); +localized_msg!( + org_key_or_userid_not_set, + "org.key_or_userid_not_set", + "Key or UserId is not set, unable to process request", + "Ключ или UserId не задан, невозможно обработать запрос" +); +localized_msg!( + org_user_to_delete_not_member, + "org.user_to_delete_not_member", + "User to delete isn't member of the organization", + "Удаляемый пользователь не является участником организации" +); +localized_msg!( + org_only_owners_delete_admin_owner, + "org.only_owners_delete_admin_owner", + "Only Owners can delete Admins or Owners", + "Только владельцы могут удалять администраторов или владельцев" +); +localized_msg!( + org_cannot_revoke_yourself, + "org.cannot_revoke_yourself", + "You cannot revoke yourself", + "Нельзя отозвать самого себя" +); +localized_msg!( + org_only_owners_revoke_owners, + "org.only_owners_revoke_owners", + "Only owners can revoke other owners", + "Только владельцы могут отзывать других владельцев" +); +localized_msg!( + org_must_have_confirmed_owner, + "org.must_have_confirmed_owner", + "Organization must have at least one confirmed owner", + "В организации должен быть хотя бы один подтвержденный владелец" +); +localized_msg!( + org_user_already_revoked, + "org.user_already_revoked", + "User is already revoked", + "Пользователь уже отозван" +); +localized_msg!( + org_user_not_found_in_org, + "org.user_not_found_in_org", + "User not found in organization", + "Пользователь не найден в организации" +); +localized_msg!( + org_cannot_restore_yourself, + "org.cannot_restore_yourself", + "You cannot restore yourself", + "Нельзя восстановить самого себя" +); +localized_msg!( + org_only_owners_restore_owners, + "org.only_owners_restore_owners", + "Only owners can restore other owners", + "Только владельцы могут восстанавливать других владельцев" +); +localized_msg!( + org_user_already_active, + "org.user_already_active", + "User is already active", + "Пользователь уже активен" +); +localized_msg!(org_groups_disabled, "org.groups_disabled", "Group support is disabled", "Поддержка групп отключена"); +localized_msg!(org_group_not_found, "org.group_not_found", "Group not found", "Группа не найдена"); +localized_msg!( + org_password_reset_not_enrolled, + "org.password_reset_not_enrolled", + "Password reset not or not correctly enrolled", + "Сброс пароля не подключен или настроен некорректно" +); +localized_msg!( + org_user_must_be_confirmed_for_reset, + "org.user_must_be_confirmed_for_reset", + "Organization user must be confirmed for password reset functionality", + "Пользователь организации должен быть подтвержден для функции сброса пароля" +); +localized_msg!( + org_kdf_settings_do_not_match_user, + "org.kdf_settings_do_not_match_user", + "KDF settings do not match the user account", + "Настройки KDF не совпадают с учетной записью пользователя" +); +localized_msg!( + org_no_permission_reset_user_password, + "org.no_permission_reset_user_password", + "No permission to reset this user's password", + "Нет прав для сброса пароля этого пользователя" +); +localized_msg!( + org_password_reset_not_supported_email_disabled, + "org.password_reset_not_supported_email_disabled", + "Password reset is not supported on an email-disabled instance.", + "Сброс пароля не поддерживается, если email отключен на инстансе." +); +localized_msg!(org_policy_not_found, "org.policy_not_found", "Policy not found", "Политика не найдена"); +localized_msg!( + org_reset_password_policy_not_enabled, + "org.reset_password_policy_not_enabled", + "Reset password policy not enabled", + "Политика сброса пароля не включена" +); +localized_msg!( + org_reset_password_withdraw_blocked_by_policy, + "org.reset_password_withdraw_blocked_by_policy", + "Reset password can't be withdrawn due to an enterprise policy", + "Нельзя отключить сброс пароля из-за политики организации" +); +localized_msg!( + org_cannot_leave_last_owner, + "org.cannot_leave_last_owner", + "The last owner can't leave", + "Последний владелец не может покинуть организацию" +); +localized_msg!( + org_no_permission_create_collections, + "org.no_permission_create_collections", + "You don't have permission to create collections", + "У вас нет прав для создания коллекций" +); +localized_msg!(org_collection_not_found, "org.collection_not_found", "Collection not found", "Коллекция не найдена"); +localized_msg!( + org_keys_already_exist, + "org.keys_already_exist", + "Organization Keys already exist", + "Ключи организации уже существуют" +); +localized_msg!( + org_invitation_issued_to_different_account, + "org.invitation_issued_to_different_account", + "Invitation was issued to a different account", + "Приглашение было выдано для другой учетной записи" +); +localized_msg!( + org_error_accepting_invitation, + "org.error_accepting_invitation", + "Error accepting the invitation", + "Ошибка при принятии приглашения" +); +localized_msg!( + org_claim_mismatch_user_id, + "org.claim_mismatch_user_id", + "Claim does not match user_id", + "Клейм не соответствует user_id" +); +localized_msg!( + org_claim_mismatch_org_id, + "org.claim_mismatch_org_id", + "Claim does not match the org_id", + "Клейм не соответствует org_id" +); +localized_msg!( + org_claim_mismatch_member_id, + "org.claim_mismatch_member_id", + "Claim does not match the member_id", + "Клейм не соответствует member_id" +); +localized_msg!( + org_reset_password_key_required, + "org.reset_password_key_required", + "Reset password key is required, but not provided.", + "Ключ сброса пароля обязателен, но не предоставлен." +); +localized_msg!(org_invalid_group, "org.invalid_group", "Invalid group", "Некорректная группа"); +localized_msg!(org_invalid_member, "org.invalid_member", "Invalid member", "Некорректный участник"); +localized_msg!(org_invalid_collection, "org.invalid_collection", "Invalid collection", "Некорректная коллекция"); +localized_msg!( + org_user_not_allowed_create, + "org.user_not_allowed_create", + "User not allowed to create organizations", + "Пользователю запрещено создавать организации" +); +localized_msg!( + org_single_org_policy_prohibits_membership, + "org.single_org_policy_prohibits_membership", + "You may not create an organization. You belong to an organization which has a policy that prohibits you from being a member of any other organization.", + "Вы не можете создать организацию. Вы состоите в организации, политика которой запрещает быть участником других организаций." +); +localized_msg!( + org_error_lookup_organization, + "org.error_lookup_organization", + "Error looking up organization.", + "Ошибка при поиске организации." +); +localized_msg!( + org_error_lookup_user, + "org.error_lookup_user", + "Error looking up user.", + "Ошибка при поиске пользователя." +); +localized_msg!( + org_member_id_required, + "org.member_id_required", + "Member id is required", + "Требуется идентификатор участника" +); +localized_msg!( + org_token_org_mismatch, + "org.token_org_mismatch", + "Token doesn't match request organization", + "Токен не соответствует запрошенной организации" +); +localized_msg!( + org_single_org_policy_required_for_reset, + "org.single_org_policy_required_for_reset", + "Single Organization policy is not enabled. It is mandatory for this policy to be enabled.", + "Политика Single Organization не включена. Для этого действия она должна быть включена." +); +localized_msg!( + org_account_recovery_policy_blocks_disable, + "org.account_recovery_policy_blocks_disable", + "Account recovery policy is enabled. It is not allowed to disable this policy.", + "Политика восстановления учетной записи включена. Отключение этой политики не допускается." +); + +#[cfg(test)] +mod tests { + use super::{ + locale_candidates, normalize_locale, preferred_from_accept_language, resolve_locale, to_client_culture, + }; + + #[test] + fn normalize_empty_to_en() { + assert_eq!(normalize_locale(" "), "en"); + } + + #[test] + fn normalize_underscored_locale() { + assert_eq!(normalize_locale("RU_ru"), "ru-ru"); + } + + #[test] + fn candidates_keep_region_and_language() { + assert_eq!(locale_candidates("pt-BR"), vec!["pt-br", "pt", "en"]); + } + + #[test] + fn candidates_from_language_only() { + assert_eq!(locale_candidates("ru"), vec!["ru", "en"]); + } + + #[test] + fn parse_accept_language_first_entry() { + assert_eq!(preferred_from_accept_language("uk-UA,uk;q=0.9,en;q=0.8"), Some("uk-ua".to_owned())); + } + + #[test] + fn resolve_locale_priority_user_then_accept_then_default() { + assert_eq!(resolve_locale(Some("ru_RU"), Some("uk-UA,uk;q=0.9"), "en"), "ru-ru"); + assert_eq!(resolve_locale(None, Some("uk-UA,uk;q=0.9"), "en"), "uk-ua"); + assert_eq!(resolve_locale(None, None, "en"), "en"); + } + + #[test] + fn client_culture_uses_uppercase_region() { + assert_eq!(to_client_culture("en-us"), "en-US"); + assert_eq!(to_client_culture("ru"), "ru"); + } +} diff --git a/src/mail.rs b/src/mail.rs index 14294213..1fb007c8 100644 --- a/src/mail.rs +++ b/src/mail.rs @@ -19,6 +19,7 @@ use crate::{ }, db::models::{Device, DeviceType, EmergencyAccessId, MembershipId, OrganizationId, User, UserId}, error::Error, + i18n, util::upcase_first, }; @@ -118,61 +119,112 @@ fn sanitize_data(data: &mut serde_json::Value) { } } +#[allow(dead_code)] fn get_text(template_name: &'static str, data: serde_json::Value) -> Result<(String, String, String), Error> { + get_text_for_locale(template_name, data, None) +} + +fn get_text_for_locale( + template_name: &'static str, + data: serde_json::Value, + locale_override: Option<&str>, +) -> Result<(String, String, String), Error> { let mut data = data; sanitize_data(&mut data); - let (subject_html, body_html) = get_template(&format!("{template_name}.html"), &data)?; - let (_subject_text, body_text) = get_template(template_name, &data)?; + + let resolved_locale = + locale_override.map_or_else(|| i18n::normalize_locale(&CONFIG.default_locale()), i18n::normalize_locale); + + if let serde_json::Value::Object(map) = &mut data { + map.entry("lang".to_owned()).or_insert_with(|| serde_json::Value::String(resolved_locale)); + } + + let (subject_html, body_html) = get_template(&format!("{template_name}.html"), &data, locale_override)?; + let (_subject_text, body_text) = get_template(template_name, &data, locale_override)?; Ok((subject_html, body_html, body_text)) } -fn get_template(template_name: &str, data: &serde_json::Value) -> Result<(String, String), Error> { - let text = CONFIG.render_template(template_name, data)?; +fn get_template( + template_name: &str, + data: &serde_json::Value, + locale_override: Option<&str>, +) -> Result<(String, String), Error> { + let template_name = get_localized_email_template_name(template_name, locale_override); + let text = CONFIG.render_template(&template_name, data)?; let mut text_split = text.split(""); let subject = if let Some(s) = text_split.next() { s.trim().to_owned() } else { - err!("Template doesn't contain subject") + err!(i18n::api_template_missing_subject(&CONFIG.default_locale())) }; let body = if let Some(s) = text_split.next() { s.trim().to_owned() } else { - err!("Template doesn't contain body") + err!(i18n::api_template_missing_body(&CONFIG.default_locale())) }; if text_split.next().is_some() { - err!("Template contains more than one body"); + err!(i18n::api_template_more_than_one_body(&CONFIG.default_locale())); } Ok((subject, body)) } +fn get_localized_email_template_name(template_name: &str, locale_override: Option<&str>) -> String { + let preferred_locale = + locale_override.map_or_else(|| i18n::normalize_locale(&CONFIG.default_locale()), i18n::normalize_locale); + + for locale in i18n::locale_candidates(&preferred_locale) { + let Some(rest) = template_name.strip_prefix("email/") else { + return template_name.to_owned(); + }; + + let localized = format!("email/{locale}/{rest}"); + if CONFIG.has_template(&localized) { + return localized; + } + } + + template_name.to_owned() +} + +#[allow(dead_code)] pub async fn send_password_hint(address: &str, hint: Option) -> EmptyResult { + send_password_hint_for_locale(address, hint, None).await +} + +pub async fn send_password_hint_for_locale(address: &str, hint: Option, locale: Option<&str>) -> EmptyResult { let template_name = if hint.is_some() { "email/pw_hint_some" } else { "email/pw_hint_none" }; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( template_name, json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "hint": hint, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_delete_account(address: &str, user_id: &UserId) -> EmptyResult { + send_delete_account_for_locale(address, user_id, None).await +} + +pub async fn send_delete_account_for_locale(address: &str, user_id: &UserId, locale: Option<&str>) -> EmptyResult { let claims = generate_delete_claims(user_id.to_string())?; let delete_token = encode_jwt(&claims); - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/delete_account", json!({ "url": CONFIG.domain(), @@ -181,16 +233,22 @@ pub async fn send_delete_account(address: &str, user_id: &UserId) -> EmptyResult "email": percent_encode(address.as_bytes(), NON_ALPHANUMERIC).to_string(), "token": delete_token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_verify_email(address: &str, user_id: &UserId) -> EmptyResult { + send_verify_email_for_locale(address, user_id, None).await +} + +pub async fn send_verify_email_for_locale(address: &str, user_id: &UserId, locale: Option<&str>) -> EmptyResult { let claims = generate_verify_email_claims(user_id)?; let verify_email_token = encode_jwt(&claims); - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/verify_email", json!({ "url": CONFIG.domain(), @@ -199,19 +257,25 @@ pub async fn send_verify_email(address: &str, user_id: &UserId) -> EmptyResult { "email": percent_encode(address.as_bytes(), NON_ALPHANUMERIC).to_string(), "token": verify_email_token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_register_verify_email(email: &str, token: &str) -> EmptyResult { + send_register_verify_email_for_locale(email, token, None).await +} + +pub async fn send_register_verify_email_for_locale(email: &str, token: &str, locale: Option<&str>) -> EmptyResult { let mut query = url::Url::parse("https://query.builder").unwrap(); query.query_pairs_mut().append_pair("email", email).append_pair("token", token).append_pair("fromEmail", "true"); let Some(query_string) = query.query() else { - err!("Failed to build verify URL query parameters") + err!(i18n::api_failed_build_verify_url_query_params(&CONFIG.default_locale())) }; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/register_verify_email", json!({ // `url.Url` would place the anchor `#` after the query parameters @@ -219,28 +283,40 @@ pub async fn send_register_verify_email(email: &str, token: &str) -> EmptyResult "img_src": CONFIG._smtp_img_src(), "email": email, }), + locale, )?; send_email(email, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_welcome(address: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_welcome_for_locale(address, None).await +} + +pub async fn send_welcome_for_locale(address: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/welcome", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_welcome_must_verify(address: &str, user_id: &UserId) -> EmptyResult { + send_welcome_must_verify_for_locale(address, user_id, None).await +} + +pub async fn send_welcome_must_verify_for_locale(address: &str, user_id: &UserId, locale: Option<&str>) -> EmptyResult { let claims = generate_verify_email_claims(user_id)?; let verify_email_token = encode_jwt(&claims); - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/welcome_must_verify", json!({ "url": CONFIG.domain(), @@ -248,32 +324,49 @@ pub async fn send_welcome_must_verify(address: &str, user_id: &UserId) -> EmptyR "user_id": user_id, "token": verify_email_token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_2fa_removed_from_org(address: &str, org_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_2fa_removed_from_org_for_locale(address, org_name, None).await +} + +pub async fn send_2fa_removed_from_org_for_locale(address: &str, org_name: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/send_2fa_removed_from_org", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "org_name": org_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_single_org_removed_from_org(address: &str, org_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_single_org_removed_from_org_for_locale(address, org_name, None).await +} + +pub async fn send_single_org_removed_from_org_for_locale( + address: &str, + org_name: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/send_single_org_removed_from_org", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "org_name": org_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await @@ -322,10 +415,10 @@ pub async fn send_invite( } let Some(query_string) = query.query() else { - err!("Failed to build invite URL query parameters") + err!(i18n::api_failed_build_invite_url_query_params(&CONFIG.default_locale())) }; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/send_org_invite", json!({ // `url.Url` would place the anchor `#` after the query parameters @@ -333,17 +426,30 @@ pub async fn send_invite( "img_src": CONFIG._smtp_img_src(), "org_name": org_name, }), + user.locale.as_deref(), )?; send_email(&user.email, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_invite( address: &str, user_id: UserId, emer_id: EmergencyAccessId, grantor_name: &str, grantor_email: &str, +) -> EmptyResult { + send_emergency_access_invite_for_locale(address, user_id, emer_id, grantor_name, grantor_email, None).await +} + +pub async fn send_emergency_access_invite_for_locale( + address: &str, + user_id: UserId, + emer_id: EmergencyAccessId, + grantor_name: &str, + grantor_email: &str, + locale: Option<&str>, ) -> EmptyResult { let claims = generate_emergency_access_invite_claims( user_id, @@ -365,10 +471,10 @@ pub async fn send_emergency_access_invite( } let Some(query_string) = query.query() else { - err!("Failed to build emergency invite URL query parameters") + err!(i18n::api_failed_build_emergency_invite_url_query_params(&CONFIG.default_locale())) }; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/send_emergency_access_invite", json!({ // `url.Url` would place the anchor `#` after the query parameters @@ -376,57 +482,99 @@ pub async fn send_emergency_access_invite( "img_src": CONFIG._smtp_img_src(), "grantor_name": grantor_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_invite_accepted(address: &str, grantee_email: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_invite_accepted_for_locale(address, grantee_email, None).await +} + +pub async fn send_emergency_access_invite_accepted_for_locale( + address: &str, + grantee_email: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_invite_accepted", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "grantee_email": grantee_email, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_invite_confirmed(address: &str, grantor_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_invite_confirmed_for_locale(address, grantor_name, None).await +} + +pub async fn send_emergency_access_invite_confirmed_for_locale( + address: &str, + grantor_name: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_invite_confirmed", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "grantor_name": grantor_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_recovery_approved(address: &str, grantor_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_recovery_approved_for_locale(address, grantor_name, None).await +} + +pub async fn send_emergency_access_recovery_approved_for_locale( + address: &str, + grantor_name: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_recovery_approved", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "grantor_name": grantor_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_recovery_initiated( address: &str, grantee_name: &str, atype: &str, wait_time_days: &i32, ) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_recovery_initiated_for_locale(address, grantee_name, atype, wait_time_days, None).await +} + +pub async fn send_emergency_access_recovery_initiated_for_locale( + address: &str, + grantee_name: &str, + atype: &str, + wait_time_days: &i32, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_recovery_initiated", json!({ "url": CONFIG.domain(), @@ -435,18 +583,30 @@ pub async fn send_emergency_access_recovery_initiated( "atype": atype, "wait_time_days": wait_time_days, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_recovery_reminder( address: &str, grantee_name: &str, atype: &str, days_left: &str, ) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_recovery_reminder_for_locale(address, grantee_name, atype, days_left, None).await +} + +pub async fn send_emergency_access_recovery_reminder_for_locale( + address: &str, + grantee_name: &str, + atype: &str, + days_left: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_recovery_reminder", json!({ "url": CONFIG.domain(), @@ -455,26 +615,47 @@ pub async fn send_emergency_access_recovery_reminder( "atype": atype, "days_left": days_left, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_recovery_rejected(address: &str, grantor_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_recovery_rejected_for_locale(address, grantor_name, None).await +} + +pub async fn send_emergency_access_recovery_rejected_for_locale( + address: &str, + grantor_name: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_recovery_rejected", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "grantor_name": grantor_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_emergency_access_recovery_timed_out(address: &str, grantee_name: &str, atype: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_emergency_access_recovery_timed_out_for_locale(address, grantee_name, atype, None).await +} + +pub async fn send_emergency_access_recovery_timed_out_for_locale( + address: &str, + grantee_name: &str, + atype: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/emergency_access_recovery_timed_out", json!({ "url": CONFIG.domain(), @@ -482,13 +663,24 @@ pub async fn send_emergency_access_recovery_timed_out(address: &str, grantee_nam "grantee_name": grantee_name, "atype": atype, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_invite_accepted(new_user_email: &str, address: &str, org_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_invite_accepted_for_locale(new_user_email, address, org_name, None).await +} + +pub async fn send_invite_accepted_for_locale( + new_user_email: &str, + address: &str, + org_name: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/invite_accepted", json!({ "url": CONFIG.domain(), @@ -496,27 +688,45 @@ pub async fn send_invite_accepted(new_user_email: &str, address: &str, org_name: "email": new_user_email, "org_name": org_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_invite_confirmed(address: &str, org_name: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_invite_confirmed_for_locale(address, org_name, None).await +} + +pub async fn send_invite_confirmed_for_locale(address: &str, org_name: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/invite_confirmed", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "org_name": org_name, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_new_device_logged_in(address: &str, ip: &str, dt: &NaiveDateTime, device: &Device) -> EmptyResult { + send_new_device_logged_in_for_locale(address, ip, dt, device, None).await +} + +pub async fn send_new_device_logged_in_for_locale( + address: &str, + ip: &str, + dt: &NaiveDateTime, + device: &Device, + locale: Option<&str>, +) -> EmptyResult { let fmt = "%A, %B %_d, %Y at %r %Z"; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/new_device_logged_in", json!({ "url": CONFIG.domain(), @@ -526,14 +736,25 @@ pub async fn send_new_device_logged_in(address: &str, ip: &str, dt: &NaiveDateTi "device_type": DeviceType::from_i32(device.atype).to_string(), "datetime": crate::util::format_naive_datetime_local(dt, fmt), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_recover_twofactor(address: &str, ip: &str, dt: &NaiveDateTime) -> EmptyResult { + send_recover_twofactor_for_locale(address, ip, dt, None).await +} + +pub async fn send_recover_twofactor_for_locale( + address: &str, + ip: &str, + dt: &NaiveDateTime, + locale: Option<&str>, +) -> EmptyResult { let fmt = "%A, %B %_d, %Y at %r %Z"; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/recover_twofactor", json!({ "url": CONFIG.domain(), @@ -541,20 +762,33 @@ pub async fn send_recover_twofactor(address: &str, ip: &str, dt: &NaiveDateTime) "ip": ip, "datetime": crate::util::format_naive_datetime_local(dt, fmt), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_incomplete_2fa_login( address: &str, ip: &str, dt: &NaiveDateTime, device_name: &str, device_type: &str, +) -> EmptyResult { + send_incomplete_2fa_login_for_locale(address, ip, dt, device_name, device_type, None).await +} + +pub async fn send_incomplete_2fa_login_for_locale( + address: &str, + ip: &str, + dt: &NaiveDateTime, + device_name: &str, + device_type: &str, + locale: Option<&str>, ) -> EmptyResult { let fmt = "%A, %B %_d, %Y at %r %Z"; - let (subject, body_html, body_text) = get_text( + let (subject, body_html, body_text) = get_text_for_locale( "email/incomplete_2fa_login", json!({ "url": CONFIG.domain(), @@ -565,39 +799,61 @@ pub async fn send_incomplete_2fa_login( "datetime": crate::util::format_naive_datetime_local(dt, fmt), "time_limit": CONFIG.incomplete_2fa_time_limit(), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_token(address: &str, token: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_token_for_locale(address, token, None).await +} + +pub async fn send_token_for_locale(address: &str, token: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/twofactor_email", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "token": token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_change_email(address: &str, token: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_change_email_for_locale(address, token, None).await +} + +pub async fn send_change_email_for_locale(address: &str, token: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/change_email", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "token": token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_change_email_existing(address: &str, acting_address: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_change_email_existing_for_locale(address, acting_address, None).await +} + +pub async fn send_change_email_existing_for_locale( + address: &str, + acting_address: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/change_email_existing", json!({ "url": CONFIG.domain(), @@ -605,13 +861,23 @@ pub async fn send_change_email_existing(address: &str, acting_address: &str) -> "existing_address": address, "acting_address": acting_address, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_change_email_invited(address: &str, acting_address: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_change_email_invited_for_locale(address, acting_address, None).await +} + +pub async fn send_change_email_invited_for_locale( + address: &str, + acting_address: &str, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/change_email_invited", json!({ "url": CONFIG.domain(), @@ -619,35 +885,49 @@ pub async fn send_change_email_invited(address: &str, acting_address: &str) -> E "existing_address": address, "acting_address": acting_address, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_sso_change_email(address: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_sso_change_email_for_locale(address, None).await +} + +pub async fn send_sso_change_email_for_locale(address: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/sso_change_email", json!({ "url": format!("{}/#/settings/account", CONFIG.domain()), "img_src": CONFIG._smtp_img_src(), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_test(address: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_test_for_locale(address, None).await +} + +pub async fn send_test_for_locale(address: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/smtp_test", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_admin_account_recovery( address: &str, user_name: &str, @@ -656,7 +936,28 @@ pub async fn send_admin_account_recovery( reset_2fa: bool, fallback_2fa_email: bool, ) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_admin_account_recovery_for_locale( + address, + user_name, + org_name, + reset_password, + reset_2fa, + fallback_2fa_email, + None, + ) + .await +} + +pub async fn send_admin_account_recovery_for_locale( + address: &str, + user_name: &str, + org_name: &str, + reset_password: bool, + reset_2fa: bool, + fallback_2fa_email: bool, + locale: Option<&str>, +) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/admin_account_recovery", json!({ "url": CONFIG.domain(), @@ -667,18 +968,25 @@ pub async fn send_admin_account_recovery( "reset_2fa": reset_2fa, "fallback_2fa_email": fallback_2fa_email, }), + locale, )?; send_email(address, &subject, body_html, body_text).await } +#[allow(dead_code)] pub async fn send_protected_action_token(address: &str, token: &str) -> EmptyResult { - let (subject, body_html, body_text) = get_text( + send_protected_action_token_for_locale(address, token, None).await +} + +pub async fn send_protected_action_token_for_locale(address: &str, token: &str, locale: Option<&str>) -> EmptyResult { + let (subject, body_html, body_text) = get_text_for_locale( "email/protected_action", json!({ "url": CONFIG.domain(), "img_src": CONFIG._smtp_img_src(), "token": token, }), + locale, )?; send_email(address, &subject, body_html, body_text).await @@ -692,13 +1000,13 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult { Err(e) => { if e.is_client() { debug!("Sendmail client error: {e:?}"); - err!(format!("Sendmail client error: {e}")); + err!(i18n::mail_sendmail_client_error(&CONFIG.default_locale()), e.to_string()); } else if e.is_response() { debug!("Sendmail response error: {e:?}"); - err!(format!("Sendmail response error: {e}")); + err!(i18n::mail_sendmail_response_error(&CONFIG.default_locale()), e.to_string()); } debug!("Sendmail error: {e:?}"); - err!(format!("Sendmail error: {e}")); + err!(i18n::mail_sendmail_error(&CONFIG.default_locale()), e.to_string()); } } } else { @@ -708,10 +1016,10 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult { Err(e) => { if e.is_client() { debug!("SMTP client error: {e:#?}"); - err!(format!("SMTP client error: {e}")); + err!(i18n::mail_smtp_client_error(&CONFIG.default_locale()), e.to_string()); } else if e.is_transient() { debug!("SMTP 4xx error: {e:#?}"); - err!(format!("SMTP 4xx error: {e}")); + err!(i18n::mail_smtp_4xx_error(&CONFIG.default_locale()), e.to_string()); } else if e.is_permanent() { debug!("SMTP 5xx error: {e:#?}"); let mut msg = e.to_string(); @@ -719,16 +1027,16 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult { if msg.contains("(535)") { msg = format!("{msg} - Authentication credentials invalid"); } - err!(format!("SMTP 5xx error: {msg}")); + err!(i18n::mail_smtp_5xx_error(&CONFIG.default_locale()), msg); } else if e.is_timeout() { debug!("SMTP timeout error: {e:#?}"); - err!(format!("SMTP timeout error: {e}")); + err!(i18n::mail_smtp_timeout_error(&CONFIG.default_locale()), e.to_string()); } else if e.is_tls() { debug!("SMTP encryption error: {e:#?}"); - err!(format!("SMTP encryption error: {e}")); + err!(i18n::mail_smtp_encryption_error(&CONFIG.default_locale()), e.to_string()); } debug!("SMTP error: {e:#?}"); - err!(format!("SMTP error: {e}")); + err!(i18n::mail_smtp_error(&CONFIG.default_locale()), e.to_string()); } } } diff --git a/src/main.rs b/src/main.rs index 76c561f2..71b907dd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -56,6 +56,7 @@ mod crypto; #[macro_use] mod db; mod http_client; +mod i18n; mod mail; mod ratelimit; mod sso; @@ -262,7 +263,7 @@ fn init_logging() -> Result { (level, levels_override) } else { - err!(format!("LOG_LEVEL should follow the format info,vaultwarden::api::icons=debug, invalid: {config_str}")) + err!(i18n::api_log_level_format_invalid(&CONFIG.default_locale()), config_str) }; // Depending on the main log level we either want to disable or enable logging for hickory. @@ -386,7 +387,7 @@ fn init_logging() -> Result { } if let Err(err) = logger.apply() { - err!(format!("Failed to activate logger: {err}")) + err!(i18n::api_failed_activate_logger(&CONFIG.default_locale()), err.to_string()) } // Catch panics and log them instead of default output to StdErr diff --git a/src/sso.rs b/src/sso.rs index cc3b51f1..fbbc437a 100644 --- a/src/sso.rs +++ b/src/sso.rs @@ -174,10 +174,16 @@ pub fn decode_state(base64_state: &str) -> ApiResult { if let Ok(valid) = String::from_utf8(vec) { OIDCState(valid) } else { - err!(format!("Invalid utf8 chars in {} after base64 decoding", base64_state.escape_debug())) + err!( + crate::i18n::auth_invalid_utf8_after_base64_decode(&CONFIG.default_locale()), + base64_state.escape_debug().to_string() + ) } } else { - err!(format!("Failed to decode {} using base64", base64_state.escape_debug())) + err!( + crate::i18n::auth_failed_decode_using_base64(&CONFIG.default_locale()), + base64_state.escape_debug().to_string() + ) }; Ok(state) @@ -202,11 +208,14 @@ pub async fn authorize_url( "mobile" => "bitwarden://sso-callback".to_owned(), "cli" => { let Some(uri) = localhost_redirect_uri else { - err!(format!("Unsupported redirect uri {}", raw_redirect_uri.escape_debug())) + err!( + crate::i18n::auth_unsupported_redirect_uri(&CONFIG.default_locale()), + raw_redirect_uri.escape_debug().to_string() + ) }; uri } - _ => err!(format!("Unsupported client {}", client_id.escape_debug())), + _ => err!(crate::i18n::auth_unsupported_client(&CONFIG.default_locale()), client_id.escape_debug().to_string()), }; let (auth_url, sso_auth) = Client::authorize_url(state, client_challenge, redirect_uri, binding_hash).await?; @@ -253,7 +262,7 @@ pub async fn exchange_code( use openidconnect::OAuth2TokenResponse; let Some(mut sso_auth) = SsoAuth::find_by_code(code, conn).await else { - err!("Invalid code cannot retrieve sso auth") + err!(crate::i18n::auth_invalid_code_cannot_retrieve_sso_auth(&CONFIG.default_locale())) }; if let Some(authenticated_user) = sso_auth.auth_response.clone() { @@ -274,7 +283,7 @@ pub async fn exchange_code( } (None, _) => { sso_auth.delete(conn).await?; - err!("Missing authorization provider return"); + err!(crate::i18n::auth_missing_authorization_provider_return(&CONFIG.default_locale())); } }; @@ -284,7 +293,7 @@ pub async fn exchange_code( let user_info = client.user_info(token_response.access_token().to_owned()).await?; let email = match id_claims.email().or(user_info.email()) { - None => err!("Neither id token nor userinfo contained an email"), + None => err!(crate::i18n::auth_neither_id_token_nor_userinfo_email(&CONFIG.default_locale())), Some(e) => e.to_string().to_lowercase(), }; @@ -350,7 +359,7 @@ pub async fn redeem( match (decode_token_claims("access_token", &auth_user.access_token), auth_user.expires_in) { (Ok(ap), _) => (ap.nbf(), ap.exp), (Err(_), Some(exp)) => (now.timestamp(), (now + exp).timestamp()), - _ => err!("Non jwt access_token and empty expires_in"), + _ => err!(crate::i18n::auth_non_jwt_access_token_empty_expires_in(&CONFIG.default_locale())), }; let access_claims = @@ -378,7 +387,7 @@ pub fn create_auth_tokens( let (ap_nbf, ap_exp) = match (decode_token_claims("access_token", &access_token), expires_in) { (Ok(ap), _) => (ap.nbf(), ap.exp), (Err(_), Some(exp)) => (now.timestamp(), (now + exp).timestamp()), - _ => err!("Non jwt access_token and empty expires_in"), + _ => err!(crate::i18n::auth_non_jwt_access_token_empty_expires_in(&CONFIG.default_locale())), }; let access_claims = @@ -474,6 +483,6 @@ pub async fn exchange_refresh_token( create_auth_tokens_impl(device, None, access_claims, access_token) } - None => err!("No token present while in SSO"), + None => err!(crate::i18n::auth_no_token_present_while_sso(&CONFIG.default_locale())), } } diff --git a/src/sso_client.rs b/src/sso_client.rs index a66d75f6..6975d4d3 100644 --- a/src/sso_client.rs +++ b/src/sso_client.rs @@ -112,12 +112,14 @@ impl Client { let issuer_url = CONFIG.sso_issuer_url()?; let http_client = match OidcHttpClient::new() { - Err(err) => err!(format!("Failed to build http client: {err}")), + Err(err) => err!(crate::i18n::auth_failed_build_http_client(&CONFIG.default_locale()), err.to_string()), Ok(client) => client, }; let provider_metadata = match CoreProviderMetadata::discover_async(issuer_url, &http_client).await { - Err(err) => err!(format!("Failed to discover OpenID provider: {err}")), + Err(err) => { + err!(crate::i18n::auth_failed_discover_openid_provider(&CONFIG.default_locale()), err.to_string()) + } Ok(metadata) => metadata, }; @@ -133,20 +135,20 @@ impl Client { } else if am.contains(&CoreClientAuthMethod::ClientSecretPost) { base_client = base_client.set_auth_type(AuthType::RequestBody); } else { - err!(format!("No supported auth_methods (only basic or request body), advertised: {am:?}")); + err!(crate::i18n::auth_no_supported_auth_methods(&CONFIG.default_locale()), format!("{am:?}")); } } let token_uri = if let Some(uri) = base_client.token_uri() { uri.clone() } else { - err!("Failed to discover token_url, cannot proceed") + err!(crate::i18n::auth_failed_discover_token_url(&CONFIG.default_locale())) }; let user_info_url = if let Some(url) = base_client.user_info_url() { url.clone() } else { - err!("Failed to discover user_info url, cannot proceed") + err!(crate::i18n::auth_failed_discover_user_info_url(&CONFIG.default_locale())) }; let core_client = base_client @@ -217,7 +219,7 @@ impl Client { let verifier = PkceCodeVerifier::new(client_verifier.to_string()); let challenge = PkceCodeChallenge::from_code_verifier_sha256(&verifier); if challenge.as_str() != &*sso_auth.client_challenge { - err!("PKCE client challenge failed") + err!(crate::i18n::auth_pkce_client_challenge_failed(&CONFIG.default_locale())) } Ok(()) } @@ -251,12 +253,14 @@ impl Client { } match exchange.request_async(&self.http_client).await { - Err(err) => err!(format!("Failed to contact token endpoint: {:?}", err)), + Err(err) => { + err!(crate::i18n::auth_failed_contact_token_endpoint(&CONFIG.default_locale()), format!("{err:?}")) + } Ok(token_response) => { let oidc_nonce = Nonce::new(sso_auth.nonce.clone()); let Some(id_token) = token_response.extra_fields().id_token() else { - err!("Token response did not contain an id_token") + err!(crate::i18n::auth_token_response_missing_id_token(&CONFIG.default_locale())) }; if CONFIG.sso_debug_tokens() { @@ -270,7 +274,10 @@ impl Client { Ok(claims) => claims.clone(), Err(err) => { Self::invalidate(); - err!(format!("Could not read id_token claims, {err}")); + err!( + crate::i18n::auth_could_not_read_id_token_claims(&CONFIG.default_locale()), + err.to_string() + ); } }; @@ -281,7 +288,9 @@ impl Client { pub async fn user_info(&self, access_token: AccessToken) -> ApiResult { match self.core_client.user_info(access_token, None).request_async(&self.http_client).await { - Err(err) => err!(format!("Request to user_info endpoint failed: {err}")), + Err(err) => { + err!(crate::i18n::auth_request_user_info_endpoint_failed(&CONFIG.default_locale()), err.to_string()) + } Ok(user_info) => Ok(user_info), } } diff --git a/src/static/scripts/admin.js b/src/static/scripts/admin.js index fa949a40..109e784a 100644 --- a/src/static/scripts/admin.js +++ b/src/static/scripts/admin.js @@ -1,6 +1,8 @@ "use strict"; /* exported BASE_URL, _post, _delete */ +const tAdmin = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key; + function getBaseUrl() { // If the base URL is `https://vaultwarden.example.com/base/path/admin/`, // `window.location.href` should have one of the following forms: @@ -51,10 +53,10 @@ function _fetch(method, url, successMsg, errMsg, body, reload_page = true) { if (respJson.errorModel && respJson.errorModel.message) { return respJson.errorModel.message; } else { - return Promise.reject({ body: `${respStatus} - ${respStatusText}\n\nUnknown error`, error: true }); + return Promise.reject({ body: `${respStatus} - ${respStatusText}\n\n${tAdmin("unknown_error")}`, error: true }); } } catch (e) { - return Promise.reject({ body: `${respStatus} - ${respStatusText}\n\n[Catch] ${e}`, error: true }); + return Promise.reject({ body: `${respStatus} - ${respStatusText}\n\n[${tAdmin("catch_error")}] ${e}`, error: true }); } }).then(apiMsg => { msg(`${errMsg}\n${apiMsg}`, reload_page); diff --git a/src/static/scripts/admin_diagnostics.js b/src/static/scripts/admin_diagnostics.js index 1d2f6605..cead6d81 100644 --- a/src/static/scripts/admin_diagnostics.js +++ b/src/static/scripts/admin_diagnostics.js @@ -1,6 +1,8 @@ "use strict"; /* global BASE_URL:readable, bootstrap:readable */ +const tDiag = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key; + var dnsCheck = false; var timeCheck = false; var ntpTimeCheck = false; @@ -80,83 +82,83 @@ async function generateSupportString(event, dj) { event.stopPropagation(); // Health check Markdown emoji, if something is a failure or not - const chk = v => v ? "true :white_check_mark:" : "false :x:"; + const chk = v => v ? tDiag("check_true") : tDiag("check_false"); // Yes/No Markdown emoji, if something is not a failure, but just yes or no - const yn = v => v ? "yes :heavy_plus_sign:" : "no :heavy_minus_sign:"; + const yn = v => v ? tDiag("yes_emoji") : tDiag("no_emoji"); const template_overrides = dj.template_overrides !== "" ? ` (${dj.template_overrides})` : ""; - let supportString = "### Your environment (Generated via diagnostics page)\n\n"; - - supportString += `* Vaultwarden version: v${dj.current_release}\n`; - supportString += `* Web-vault version: v${dj.active_web_release}\n`; - supportString += `* OS/Arch: ${dj.host_os}/${dj.host_arch}\n`; - supportString += `* Running within a container: ${yn(dj.running_within_container)} (Base: ${dj.container_base_image})\n`; - supportString += `* Database type: ${dj.db_type}\n`; - supportString += `* Database version: ${dj.db_version}\n`; - supportString += `* Uses config.json: ${yn(dj.config_file_status !== "NotFound")}`; + let supportString = `${tDiag("support_title")}\n\n`; + + supportString += `${tDiag("vw_version")}: v${dj.current_release}\n`; + supportString += `${tDiag("web_vault_version")}: v${dj.active_web_release}\n`; + supportString += `${tDiag("os_arch")}: ${dj.host_os}/${dj.host_arch}\n`; + supportString += `${tDiag("running_container")}: ${yn(dj.running_within_container)} (Base: ${dj.container_base_image})\n`; + supportString += `${tDiag("db_type")}: ${dj.db_type}\n`; + supportString += `${tDiag("db_version")}: ${dj.db_version}\n`; + supportString += `${tDiag("uses_config_json")}: ${yn(dj.config_file_status !== "NotFound")}`; supportString += dj.config_file_status !== "NotFound" ? ` (Valid: ${chk(dj.config_file_status === "Loaded")})\n` : "\n"; - supportString += `* Environment variables are valid: ${chk(dj.invalid_env_vars == "")}\n`; - supportString += `* Uses custom templates: ${yn(dj.template_overrides !== "")}${template_overrides}\n`; - supportString += `* Uses a reverse proxy: ${yn(dj.ip_header_exists)}\n`; + supportString += `${tDiag("env_valid")}: ${chk(dj.invalid_env_vars == "")}\n`; + supportString += `${tDiag("uses_custom_templates")}: ${yn(dj.template_overrides !== "")}${template_overrides}\n`; + supportString += `${tDiag("uses_reverse_proxy")}: ${yn(dj.ip_header_exists)}\n`; if (dj.ip_header_exists) { - supportString += `* IP Header check: ${chk(dj.ip_header_match)} (${dj.ip_header_name})\n`; + supportString += `${tDiag("ip_header_check")}: ${chk(dj.ip_header_match)} (${dj.ip_header_name})\n`; } - supportString += `* Internet access: ${chk(dj.has_http_access)}\n`; - supportString += `* Internet access via a proxy: ${yn(dj.uses_proxy)}\n`; - supportString += `* DNS Check: ${chk(dnsCheck)}\n`; + supportString += `${tDiag("internet_access")}: ${chk(dj.has_http_access)}\n`; + supportString += `${tDiag("internet_access_proxy")}: ${yn(dj.uses_proxy)}\n`; + supportString += `${tDiag("dns_check")}: ${chk(dnsCheck)}\n`; if (dj.tz_env !== "") { - supportString += `* TZ environment: ${dj.tz_env}\n`; + supportString += `${tDiag("tz_env")}: ${dj.tz_env}\n`; } - supportString += `* Browser/Server Time Check: ${chk(timeCheck)}\n`; - supportString += `* Server/NTP Time Check: ${chk(ntpTimeCheck)}\n`; - supportString += `* Domain Configuration Check: ${chk(domainCheck)}\n`; - supportString += `* HTTPS Check: ${chk(httpsCheck)}\n`; + supportString += `${tDiag("browser_server_time_check")}: ${chk(timeCheck)}\n`; + supportString += `${tDiag("server_ntp_time_check")}: ${chk(ntpTimeCheck)}\n`; + supportString += `${tDiag("domain_check")}: ${chk(domainCheck)}\n`; + supportString += `${tDiag("https_check")}: ${chk(httpsCheck)}\n`; if (dj.enable_websocket) { - supportString += `* Websocket Check: ${chk(websocketCheck)}\n`; + supportString += `${tDiag("websocket_check")}: ${chk(websocketCheck)}\n`; } else { - supportString += "* Websocket Check: disabled\n"; + supportString += `${tDiag("websocket_check")}: ${tDiag("websocket_disabled")}\n`; } - supportString += `* HTTP Response Checks: ${chk(httpResponseCheck)}\n`; + supportString += `${tDiag("http_response_checks")}: ${chk(httpResponseCheck)}\n`; if (dj.invalid_feature_flags != "") { - supportString += "* Invalid feature flags: true :x:\n"; + supportString += `${tDiag("invalid_feature_flags_line")}\n`; } const jsonResponse = await fetch(`${BASE_URL}/admin/diagnostics/config`, { "headers": { "Accept": "application/json" } }); if (!jsonResponse.ok) { - alert("Generation failed: " + jsonResponse.statusText); + alert(`${tDiag("generation_failed_prefix")} ${jsonResponse.statusText}`); throw new Error(jsonResponse); } const configJson = await jsonResponse.json(); // Start Config and Details section within a details block which is collapsed by default - supportString += "\n### Config & Details (Generated via diagnostics page)\n\n"; - supportString += "
Show Config & Details\n"; + supportString += `\n${tDiag("support_details_title")}\n\n`; + supportString += `${tDiag("support_details_summary")}\n`; // Show invalid environment variables if they exists if (dj.invalid_env_vars != "") { - supportString += `\n**Invalid environment variables:** ${dj.invalid_env_vars}\n`; + supportString += `\n${tDiag("invalid_env_vars")} ${dj.invalid_env_vars}\n`; } // Add overrides if they exists if (dj.overrides != "") { - supportString += `\n**Environment settings which are overridden:** ${dj.overrides}\n`; + supportString += `\n${tDiag("overridden_env_settings")} ${dj.overrides}\n`; } if (dj.invalid_feature_flags != "") { - supportString += `\n**Invalid feature flags:** ${dj.invalid_feature_flags}\n`; + supportString += `\n${tDiag("invalid_feature_flags")} ${dj.invalid_feature_flags}\n`; } // Add http response check messages if they exists if (httpResponseCheck === false) { - supportString += "\n**Failed HTTP Checks:**\n"; + supportString += `\n${tDiag("failed_http_checks")}\n`; // We use `innerText` here since that will convert
into new-lines supportString += "\n```yaml\n" + document.getElementById("http-response-errors").innerText.trim() + "\n```\n"; } // Add the current config in json form - supportString += "\n**Config:**\n"; + supportString += `\n${tDiag("config_header")}\n`; supportString += "\n```json\n" + JSON.stringify(configJson, undefined, 2) + "\n```\n"; supportString += "\n
\n"; @@ -314,9 +316,9 @@ async function checkHttpResponse() { // Check and validate the default API header responses let apiErrors = checkSecurityHeaders(apiConfig.headers); if (apiErrors.length >= 1) { - respErrorElm.innerHTML += "API calls:
"; + respErrorElm.innerHTML += `${tDiag("api_calls")}:
`; apiErrors.forEach((errMsg) => { - respErrorElm.innerHTML += `Header: ${errMsg}
`; + respErrorElm.innerHTML += `${tDiag("header_prefix")}: ${errMsg}
`; }); } @@ -329,38 +331,38 @@ async function checkHttpResponse() { } }); if (connectorErrors.length >= 1) { - respErrorElm.innerHTML += "2FA Connector calls:
"; + respErrorElm.innerHTML += `${tDiag("connector_calls")}:
`; connectorErrors.forEach((errMsg) => { - respErrorElm.innerHTML += `Header: ${errMsg}
`; + respErrorElm.innerHTML += `${tDiag("header_prefix")}: ${errMsg}
`; }); } // Check specific error code responses if they are not re-written by a reverse proxy let responseErrors = []; if (notFound.status !== 404 || notFound.text.indexOf("return to the web-vault") === -1) { - responseErrors.push("404 (Not Found) HTML is invalid"); + responseErrors.push(tDiag("err_404_html_invalid")); } if (notFoundApi.status !== 404 || notFoundApi.text.indexOf("\"message\":\"Testing error 404 response\",") === -1) { - responseErrors.push("404 (Not Found) JSON is invalid"); + responseErrors.push(tDiag("err_404_json_invalid")); } if (badRequest.status !== 400 || badRequest.text.indexOf("\"message\":\"Testing error 400 response\",") === -1) { - responseErrors.push("400 (Bad Request) is invalid"); + responseErrors.push(tDiag("err_400_invalid")); } if (unauthorized.status !== 401 || unauthorized.text.indexOf("\"message\":\"Testing error 401 response\",") === -1) { - responseErrors.push("401 (Unauthorized) is invalid"); + responseErrors.push(tDiag("err_401_invalid")); } if (forbidden.status !== 403 || forbidden.text.indexOf("\"message\":\"Testing error 403 response\",") === -1) { - responseErrors.push("403 (Forbidden) is invalid"); + responseErrors.push(tDiag("err_403_invalid")); } if (responseErrors.length >= 1) { - respErrorElm.innerHTML += "HTTP error responses:
"; + respErrorElm.innerHTML += `${tDiag("http_error_responses")}:
`; responseErrors.forEach((errMsg) => { - respErrorElm.innerHTML += `Response to: ${errMsg}
`; + respErrorElm.innerHTML += `${tDiag("response_to_prefix")}: ${errMsg}
`; }); } diff --git a/src/static/scripts/admin_i18n_loader.js b/src/static/scripts/admin_i18n_loader.js new file mode 100644 index 00000000..52287d1e --- /dev/null +++ b/src/static/scripts/admin_i18n_loader.js @@ -0,0 +1,54 @@ +"use strict"; + +(function loadAdminI18n() { + const normalizeLocale = raw => String(raw || "").trim().replace(/_/g, "-").toLowerCase() || "en"; + + const localeCandidates = locale => { + const normalized = normalizeLocale(locale); + const candidates = [normalized]; + + const sep = normalized.indexOf("-"); + if (sep > 0) { + const lang = normalized.slice(0, sep); + if (lang && !candidates.includes(lang)) { + candidates.push(lang); + } + } + + if (!candidates.includes("en")) { + candidates.push("en"); + } + + return candidates; + }; + + const localeFromHtml = document.documentElement.getAttribute("lang"); + const locales = localeCandidates(localeFromHtml || "en"); + + const pathname = window.location.pathname || ""; + const adminPos = pathname.indexOf("/admin"); + const basePath = adminPos !== -1 ? pathname.substring(0, adminPos) : ""; + + window.VW_ADMIN_I18N = window.VW_ADMIN_I18N || {}; + window.VW_ADMIN_I18N_READY = (async () => { + for (const locale of locales) { + const url = `${basePath}/vw_static/locales/${locale}/admin_ui.json`; + try { + const resp = await fetch(url, { + method: "GET", + credentials: "same-origin", + cache: "no-cache" + }); + + if (!resp.ok) { + continue; + } + + window.VW_ADMIN_I18N = await resp.json(); + return; + } catch (_e) { + // Try next locale candidate. + } + } + })(); +})(); diff --git a/src/static/scripts/admin_organizations.js b/src/static/scripts/admin_organizations.js index 0aa57dcd..623271e9 100644 --- a/src/static/scripts/admin_organizations.js +++ b/src/static/scripts/admin_organizations.js @@ -1,6 +1,8 @@ "use strict"; /* global DataTable, _post:readable, BASE_URL:readable, reload:readable, jdenticon:readable */ +const tOrgs = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key; + function deleteOrganization(event) { event.preventDefault(); event.stopPropagation(); @@ -8,22 +10,22 @@ function deleteOrganization(event) { const org_name = event.target.dataset.vwOrgName; const billing_email = event.target.dataset.vwBillingEmail; if (!org_uuid) { - alert("Required parameters not found!"); + alert(tOrgs("required_params_not_found")); return false; } // First make sure the user wants to delete this organization - const continueDelete = confirm(`WARNING: All data of this organization (${org_name}) will be lost!\nMake sure you have a backup, this cannot be undone!`); + const continueDelete = confirm(`${tOrgs("warn_delete_org_prefix")} (${org_name}) ${tOrgs("warn_delete_org_suffix")}`); if (continueDelete == true) { - const input_org_uuid = prompt(`To delete the organization "${org_name} (${billing_email})", please type the organization uuid below.`); + const input_org_uuid = prompt(`${tOrgs("prompt_delete_org_prefix")} "${org_name} (${billing_email})", ${tOrgs("prompt_type_org_uuid")}`); if (input_org_uuid != null) { if (input_org_uuid == org_uuid) { _post(`${BASE_URL}/admin/organizations/${org_uuid}/delete`, - "Organization deleted correctly", - "Error deleting organization" + tOrgs("org_delete_ok"), + tOrgs("org_delete_error") ); } else { - alert("Wrong organization uuid, please try again"); + alert(tOrgs("wrong_org_uuid_retry")); } } } @@ -40,17 +42,42 @@ function initActions() { } // onLoad events -document.addEventListener("DOMContentLoaded", (/*event*/) => { +document.addEventListener("DOMContentLoaded", async (/*event*/) => { + if (window.VW_ADMIN_I18N_READY) { + await window.VW_ADMIN_I18N_READY; + } + const columnCount = document.getElementById("orgs-table").querySelectorAll("thead th").length; new DataTable("#orgs-table", { "drawCallback": function () { initActions(); }, + "language": { + "search": tOrgs("datatable_search"), + "emptyTable": tOrgs("datatable_empty_table"), + "info": tOrgs("datatable_info"), + "infoEmpty": tOrgs("datatable_info_empty"), + "infoFiltered": tOrgs("datatable_info_filtered"), + "lengthMenu": tOrgs("datatable_length_menu"), + "loadingRecords": tOrgs("datatable_loading_records"), + "processing": tOrgs("datatable_processing"), + "zeroRecords": tOrgs("datatable_zero_records"), + "paginate": { + "first": tOrgs("datatable_paginate_first"), + "last": tOrgs("datatable_paginate_last"), + "next": tOrgs("datatable_paginate_next"), + "previous": tOrgs("datatable_paginate_previous") + }, + "aria": { + "orderable": tOrgs("datatable_aria_orderable"), + "orderableReverse": tOrgs("datatable_aria_orderable_reverse") + } + }, "stateSave": true, "responsive": true, "lengthMenu": [ [-1, 5, 10, 25, 50], - ["All", 5, 10, 25, 50] + [tOrgs("datatable_all"), 5, 10, 25, 50] ], "pageLength": -1, // Default show all "columnDefs": [{ diff --git a/src/static/scripts/admin_settings.js b/src/static/scripts/admin_settings.js index 9061719e..119fea3a 100644 --- a/src/static/scripts/admin_settings.js +++ b/src/static/scripts/admin_settings.js @@ -1,11 +1,13 @@ "use strict"; /* global _post:readable, BASE_URL:readable */ +const tSettings = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key; + function smtpTest(event) { event.preventDefault(); event.stopPropagation(); if (formHasChanges(config_form)) { - alert("Config has been changed but not yet saved.\nPlease save the changes first before sending a test email."); + alert(tSettings("config_changed_unsaved")); return false; } @@ -19,8 +21,8 @@ function smtpTest(event) { const data = JSON.stringify({ "email": test_email.value }); _post(`${BASE_URL}/admin/test/smtp`, - "SMTP Test email sent correctly", - "Error sending SMTP test email", + tSettings("smtp_test_ok"), + tSettings("smtp_test_error"), data, false ); } @@ -45,8 +47,8 @@ function getFormData() { function saveConfig(event) { const data = JSON.stringify(getFormData()); _post(`${BASE_URL}/admin/config`, - "Config saved correctly", - "Error saving config", + tSettings("config_save_ok"), + tSettings("config_save_error"), data ); event.preventDefault(); @@ -56,16 +58,15 @@ function deleteConf(event) { event.preventDefault(); event.stopPropagation(); const input = prompt( - "This will remove all user configurations, and restore the defaults and the " + - "values set by the environment. This operation could be dangerous. Type 'DELETE' to proceed:" + tSettings("delete_config_prompt") ); if (input === "DELETE") { _post(`${BASE_URL}/admin/config/delete`, - "Config deleted correctly", - "Error deleting config" + tSettings("config_delete_ok"), + tSettings("config_delete_error") ); } else { - alert("Wrong input, please try again"); + alert(tSettings("wrong_input_retry")); } } @@ -73,8 +74,8 @@ function backupDatabase(event) { event.preventDefault(); event.stopPropagation(); _post(`${BASE_URL}/admin/config/backup_db`, - "Backup created successfully", - "Error creating backup", null, false + tSettings("backup_create_ok"), + tSettings("backup_create_error"), null, false ); } @@ -121,7 +122,8 @@ function submitTestEmailOnEnter() { function colorRiskSettings() { const risk_items = document.getElementsByClassName("col-form-label"); Array.from(risk_items).forEach((el) => { - if (el.textContent.toLowerCase().includes("risks") ) { + const label = el.textContent.toLowerCase(); + if (label.includes("risks") || label.includes("риск")) { el.parentElement.className += " alert-danger"; } }); diff --git a/src/static/scripts/admin_users.js b/src/static/scripts/admin_users.js index 63ee2d7b..82937f17 100644 --- a/src/static/scripts/admin_users.js +++ b/src/static/scripts/admin_users.js @@ -1,24 +1,26 @@ "use strict"; /* global DataTable, _post:readable, _delete:readable, BASE_URL:readable, reload:readable, jdenticon:readable */ +const tUsers = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key; + function deleteUser(event) { event.preventDefault(); event.stopPropagation(); const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const input_email = prompt(`To delete user "${email}", please type the email below`); + const input_email = prompt(`${tUsers("prompt_delete_user_prefix")} "${email}", ${tUsers("prompt_type_email_below")}`); if (input_email != null) { if (input_email == email) { _post(`${BASE_URL}/admin/users/${id}/delete`, - "User deleted correctly", - "Error deleting user" + tUsers("user_deleted_ok"), + tUsers("user_deleted_error") ); } else { - alert("Wrong email, please try again"); + alert(tUsers("wrong_email_retry")); } } } @@ -29,18 +31,18 @@ function deleteSSOUser(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const input_email = prompt(`To delete user "${email}" SSO association, please type the email below`); + const input_email = prompt(`${tUsers("prompt_delete_user_sso_prefix")} "${email}" ${tUsers("prompt_delete_user_sso_suffix")}`); if (input_email != null) { if (input_email == email) { _delete(`${BASE_URL}/admin/users/${id}/sso`, - "User SSO association deleted correctly", - "Error deleting user SSO association" + tUsers("user_sso_deleted_ok"), + tUsers("user_sso_deleted_error") ); } else { - alert("Wrong email, please try again"); + alert(tUsers("wrong_email_retry")); } } } @@ -51,14 +53,14 @@ function remove2fa(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const confirmed = confirm(`Are you sure you want to remove 2FA for "${email}"?`); + const confirmed = confirm(`${tUsers("confirm_remove_2fa_prefix")} "${email}"?`); if (confirmed) { _post(`${BASE_URL}/admin/users/${id}/remove-2fa`, - "2FA removed correctly", - "Error removing 2FA" + tUsers("remove_2fa_ok"), + tUsers("remove_2fa_error") ); } } @@ -69,14 +71,14 @@ function deauthUser(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const confirmed = confirm(`Are you sure you want to deauthorize sessions for "${email}"?`); + const confirmed = confirm(`${tUsers("confirm_deauth_prefix")} "${email}"?`); if (confirmed) { _post(`${BASE_URL}/admin/users/${id}/deauth`, - "Sessions deauthorized correctly", - "Error deauthorizing sessions" + tUsers("deauth_ok"), + tUsers("deauth_error") ); } } @@ -87,14 +89,14 @@ function disableUser(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const confirmed = confirm(`Are you sure you want to disable user "${email}"? This will also deauthorize their sessions.`); + const confirmed = confirm(`${tUsers("confirm_disable_user_prefix")} "${email}"? ${tUsers("confirm_disable_user_suffix")}`); if (confirmed) { _post(`${BASE_URL}/admin/users/${id}/disable`, - "User disabled successfully", - "Error disabling user" + tUsers("user_disable_ok"), + tUsers("user_disable_error") ); } } @@ -105,14 +107,14 @@ function enableUser(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const confirmed = confirm(`Are you sure you want to enable user "${email}"?`); + const confirmed = confirm(`${tUsers("confirm_enable_user_prefix")} "${email}"?`); if (confirmed) { _post(`${BASE_URL}/admin/users/${id}/enable`, - "User enabled successfully", - "Error enabling user" + tUsers("user_enable_ok"), + tUsers("user_enable_error") ); } } @@ -121,8 +123,8 @@ function updateRevisions(event) { event.preventDefault(); event.stopPropagation(); _post(`${BASE_URL}/admin/users/update_revision`, - "Success, clients will sync next time they connect", - "Error forcing clients to sync" + tUsers("sync_clients_ok"), + tUsers("sync_clients_error") ); } @@ -135,8 +137,8 @@ function inviteUser(event) { }); email.value = ""; _post(`${BASE_URL}/admin/invite`, - "User invited correctly", - "Error inviting user", + tUsers("invite_user_ok"), + tUsers("invite_user_error"), data ); } @@ -147,34 +149,34 @@ function resendUserInvite(event) { const id = event.target.parentNode.dataset.vwUserUuid; const email = event.target.parentNode.dataset.vwUserEmail; if (!id || !email) { - alert("Required parameters not found!"); + alert(tUsers("required_params_not_found")); return false; } - const confirmed = confirm(`Are you sure you want to resend invitation for "${email}"?`); + const confirmed = confirm(`${tUsers("confirm_resend_invite_prefix")} "${email}"?`); if (confirmed) { _post(`${BASE_URL}/admin/users/${id}/invite/resend`, - "Invite sent successfully", - "Error resend invite" + tUsers("resend_invite_ok"), + tUsers("resend_invite_error") ); } } const ORG_TYPES = { "0": { - "name": "Owner", + "name": tUsers("role_owner"), "bg": "orange", "font": "black" }, "1": { - "name": "Admin", + "name": tUsers("role_admin"), "bg": "blueviolet" }, "2": { - "name": "User", + "name": tUsers("role_user"), "bg": "blue" }, "4": { - "name": "Manager", + "name": tUsers("role_manager"), "bg": "green" }, }; @@ -213,8 +215,8 @@ function updateUserOrgType(event) { const data = JSON.stringify(Object.fromEntries(new FormData(event.target).entries())); _post(`${BASE_URL}/admin/users/org_type`, - "Updated organization type of the user successfully", - "Error updating organization type of the user", + tUsers("user_org_type_update_ok"), + tUsers("user_org_type_update_error"), data ); } @@ -276,7 +278,11 @@ DataTable.ext.type.order["date-iso-pre"] = function (a) { }; // onLoad events -document.addEventListener("DOMContentLoaded", (/*event*/) => { +document.addEventListener("DOMContentLoaded", async (/*event*/) => { + if (window.VW_ADMIN_I18N_READY) { + await window.VW_ADMIN_I18N_READY; + } + DataTable.ext.type.detect.unshift(function (data) { if (typeof data !== "string") { return null; } return data.indexOf("data-sort-type=\"date-iso\"") !== -1 @@ -290,11 +296,32 @@ document.addEventListener("DOMContentLoaded", (/*event*/) => { "drawCallback": function () { initUserTable(); }, + "language": { + "search": tUsers("datatable_search"), + "emptyTable": tUsers("datatable_empty_table"), + "info": tUsers("datatable_info"), + "infoEmpty": tUsers("datatable_info_empty"), + "infoFiltered": tUsers("datatable_info_filtered"), + "lengthMenu": tUsers("datatable_length_menu"), + "loadingRecords": tUsers("datatable_loading_records"), + "processing": tUsers("datatable_processing"), + "zeroRecords": tUsers("datatable_zero_records"), + "paginate": { + "first": tUsers("datatable_paginate_first"), + "last": tUsers("datatable_paginate_last"), + "next": tUsers("datatable_paginate_next"), + "previous": tUsers("datatable_paginate_previous") + }, + "aria": { + "orderable": tUsers("datatable_aria_orderable"), + "orderableReverse": tUsers("datatable_aria_orderable_reverse") + } + }, "stateSave": true, "responsive": true, "lengthMenu": [ [-1, 2, 5, 10, 25, 50], - ["All", 2, 5, 10, 25, 50] + [tUsers("datatable_all"), 2, 5, 10, 25, 50] ], "pageLength": -1, // Default show all "columnDefs": [{ diff --git a/src/static/templates/404.hbs b/src/static/templates/404.hbs index 064dc5a1..0662c9fb 100644 --- a/src/static/templates/404.hbs +++ b/src/static/templates/404.hbs @@ -1,11 +1,11 @@ - + - Page not found! + {{t "web.404.title" locale=lang}} @@ -16,7 +16,7 @@
Vaultwarden