Browse Source

feat(i18n): implement locale discovery and template/admin localization

Add compile-time locale catalog discovery with include_dir and runtime overlay support from DATA_FOLDER/locales. Integrate Handlebars translation helper and admin locale dictionary serving/loading. Keep API/client compatibility by limiting locale-scoped keys to admin/templates surfaces.
pull/7913/head
Oneill26 3 weeks ago
parent
commit
a31df690b4
  1. 9
      .env.template
  2. 20
      Cargo.lock
  3. 3
      Cargo.toml
  4. 133
      src/api/admin.rs
  5. 226
      src/api/core/accounts.rs
  6. 173
      src/api/core/ciphers.rs
  7. 157
      src/api/core/emergency_access.rs
  8. 23
      src/api/core/events.rs
  9. 6
      src/api/core/folders.rs
  10. 18
      src/api/core/mod.rs
  11. 540
      src/api/core/organizations.rs
  12. 4
      src/api/core/public.rs
  13. 85
      src/api/core/sends.rs
  14. 10
      src/api/core/two_factor/authenticator.rs
  15. 7
      src/api/core/two_factor/duo.rs
  16. 54
      src/api/core/two_factor/duo_oidc.rs
  17. 63
      src/api/core/two_factor/email.rs
  18. 7
      src/api/core/two_factor/mod.rs
  19. 18
      src/api/core/two_factor/protected_actions.rs
  20. 12
      src/api/core/two_factor/webauthn.rs
  21. 23
      src/api/core/two_factor/yubikey.rs
  22. 187
      src/api/identity.rs
  23. 4
      src/api/mod.rs
  24. 11
      src/api/push.rs
  25. 91
      src/api/web.rs
  26. 89
      src/auth.rs
  27. 18
      src/auth/two_factor.rs
  28. 196
      src/config.rs
  29. 24
      src/db/mod.rs
  30. 7
      src/db/models/archive.rs
  31. 6
      src/db/models/attachment.rs
  32. 11
      src/db/models/auth_request.rs
  33. 26
      src/db/models/cipher.rs
  34. 26
      src/db/models/collection.rs
  35. 11
      src/db/models/device.rs
  36. 27
      src/db/models/emergency_access.rs
  37. 14
      src/db/models/event.rs
  38. 9
      src/db/models/favorite.rs
  39. 17
      src/db/models/folder.rs
  40. 27
      src/db/models/group.rs
  41. 30
      src/db/models/org_policy.rs
  42. 27
      src/db/models/organization.rs
  43. 8
      src/db/models/send.rs
  44. 11
      src/db/models/sso_auth.rs
  45. 13
      src/db/models/two_factor.rs
  46. 5
      src/db/models/two_factor_duo_context.rs
  47. 6
      src/db/models/two_factor_incomplete.rs
  48. 40
      src/db/models/user.rs
  49. 1
      src/db/schema.rs
  50. 4
      src/http_client.rs
  51. 3129
      src/i18n.rs
  52. 406
      src/mail.rs
  53. 5
      src/main.rs
  54. 29
      src/sso.rs
  55. 29
      src/sso_client.rs
  56. 6
      src/static/scripts/admin.js
  57. 94
      src/static/scripts/admin_diagnostics.js
  58. 54
      src/static/scripts/admin_i18n_loader.js
  59. 43
      src/static/scripts/admin_organizations.js
  60. 28
      src/static/scripts/admin_settings.js
  61. 111
      src/static/scripts/admin_users.js
  62. 16
      src/static/templates/404.hbs
  63. 31
      src/static/templates/admin/base.hbs
  64. 192
      src/static/templates/admin/diagnostics.hbs
  65. 8
      src/static/templates/admin/login.hbs
  66. 28
      src/static/templates/admin/organizations.hbs
  67. 77
      src/static/templates/admin/settings.hbs
  68. 74
      src/static/templates/admin/users.hbs
  69. 8
      src/static/templates/email/admin_account_recovery.hbs
  70. 8
      src/static/templates/email/admin_account_recovery.html.hbs
  71. 6
      src/static/templates/email/change_email.hbs
  72. 6
      src/static/templates/email/change_email.html.hbs
  73. 6
      src/static/templates/email/change_email_existing.hbs
  74. 6
      src/static/templates/email/change_email_existing.html.hbs
  75. 12
      src/static/templates/email/change_email_invited.hbs
  76. 12
      src/static/templates/email/change_email_invited.html.hbs
  77. 8
      src/static/templates/email/delete_account.hbs
  78. 8
      src/static/templates/email/delete_account.html.hbs
  79. 8
      src/static/templates/email/emergency_access_invite_accepted.hbs
  80. 8
      src/static/templates/email/emergency_access_invite_accepted.html.hbs
  81. 6
      src/static/templates/email/emergency_access_invite_confirmed.hbs
  82. 6
      src/static/templates/email/emergency_access_invite_confirmed.html.hbs
  83. 4
      src/static/templates/email/emergency_access_recovery_approved.hbs
  84. 4
      src/static/templates/email/emergency_access_recovery_approved.html.hbs
  85. 6
      src/static/templates/email/emergency_access_recovery_initiated.hbs
  86. 6
      src/static/templates/email/emergency_access_recovery_initiated.html.hbs
  87. 4
      src/static/templates/email/emergency_access_recovery_rejected.hbs
  88. 4
      src/static/templates/email/emergency_access_recovery_rejected.html.hbs
  89. 6
      src/static/templates/email/emergency_access_recovery_reminder.hbs
  90. 6
      src/static/templates/email/emergency_access_recovery_reminder.html.hbs
  91. 4
      src/static/templates/email/emergency_access_recovery_timed_out.hbs
  92. 4
      src/static/templates/email/emergency_access_recovery_timed_out.html.hbs
  93. 14
      src/static/templates/email/incomplete_2fa_login.hbs
  94. 14
      src/static/templates/email/incomplete_2fa_login.html.hbs
  95. 6
      src/static/templates/email/invite_accepted.hbs
  96. 8
      src/static/templates/email/invite_accepted.html.hbs
  97. 6
      src/static/templates/email/invite_confirmed.hbs
  98. 8
      src/static/templates/email/invite_confirmed.html.hbs
  99. 14
      src/static/templates/email/new_device_logged_in.hbs
  100. 14
      src/static/templates/email/new_device_logged_in.html.hbs

9
.env.template

@ -210,6 +210,15 @@
## For public server (URL with path) ## For public server (URL with path)
# DOMAIN=https://domain.tld/vw # 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/<locale>.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. ## Controls whether users are allowed to create Bitwarden Sends.
## This setting applies globally to all users. ## This setting applies globally to all users.
## To control this on a per-org basis instead, use the "Disable Send" org policy. ## To control this on a per-org basis instead, use the "Disable Send" org policy.

20
Cargo.lock

@ -2665,6 +2665,25 @@ dependencies = [
"icu_properties", "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]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.9.3" version = "1.9.3"
@ -5911,6 +5930,7 @@ dependencies = [
"hickory-resolver", "hickory-resolver",
"html5gum", "html5gum",
"http 1.5.0", "http 1.5.0",
"include_dir",
"ipnet", "ipnet",
"job_scheduler_ng", "job_scheduler_ng",
"jsonwebtoken", "jsonwebtoken",

3
Cargo.toml

@ -105,9 +105,10 @@ tokio-util = { version = "0.7.20", features = ["compat"] }
# A generic serialization/deserialization framework # A generic serialization/deserialization framework
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
include_dir = "0.7.4"
# A safe, extensible ORM and Query builder # 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" diesel_migrations = "2.3.2"
derive_more = { version = "2.1.1", features = [ derive_more = { version = "2.1.1", features = [

133
src/api/admin.rs

@ -19,7 +19,7 @@ use crate::{
core::{log_event, two_factor}, core::{log_event, two_factor},
push_logout_to_relay, unregister_push_device, 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, config::ConfigBuilder,
db::{ db::{
ACTIVE_DB_TYPE, DbConn, DbConnType, backup_sqlite, get_sql_server_version, 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()) 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)] #[derive(Responder)]
enum AdminResponse { enum AdminResponse {
#[response(status = 200)] #[response(status = 200)]
@ -153,25 +168,36 @@ enum AdminResponse {
#[catch(401)] #[catch(401)]
fn admin_login(request: &Request<'_>) -> ApiResult<Html<String>> { fn admin_login(request: &Request<'_>) -> ApiResult<Html<String>> {
let locale =
crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale());
if request.format() == Some(&MediaType::JSON) { 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::<std::path::PathBuf>(0..).unwrap_or_default().display().to_string(); let redirect = request.segments::<std::path::PathBuf>(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<Html<String>> { fn render_admin_login(msg: Option<&str>, redirect: Option<&str>, locale: &str) -> ApiResult<Html<String>> {
// If there is an error, show it // 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!({ let json = json!({
"page_content": "admin/login", "page_content": page_content,
"error": msg, "error": msg,
"redirect": redirect, "redirect": redirect,
"urlpath": CONFIG.domain_path() "urlpath": CONFIG.domain_path(),
"lang": locale,
}); });
// Return the page // 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)) Ok(Html(text))
} }
@ -182,10 +208,12 @@ struct LoginForm {
} }
#[post("/", format = "application/x-www-form-urlencoded", data = "<data>")] #[post("/", format = "application/x-www-form-urlencoded", data = "<data>")]
#[allow(clippy::needless_pass_by_value)]
fn post_admin_login( fn post_admin_login(
data: Form<LoginForm>, data: Form<LoginForm>,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ip: ClientIp, ip: ClientIp,
locale: RequestLocale,
secure: Secure, secure: Secure,
) -> Result<Redirect, AdminResponse> { ) -> Result<Redirect, AdminResponse> {
let data = data.into_inner(); let data = data.into_inner();
@ -193,8 +221,9 @@ fn post_admin_login(
if crate::ratelimit::check_limit_admin(&ip.ip).is_err() { if crate::ratelimit::check_limit_admin(&ip.ip).is_err() {
return Err(AdminResponse::TooManyRequests(render_admin_login( 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(), 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 // If the token received is valid, generate JWT and save it as a cookie
let claims = match generate_admin_claims() { let claims = match generate_admin_claims() {
Ok(claims) => 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); let jwt = encode_jwt(&claims);
@ -218,13 +253,14 @@ fn post_admin_login(
if let Some(redirect) = redirect { if let Some(redirect) = redirect {
Ok(Redirect::to(format!("{}{redirect}", admin_path()))) Ok(Redirect::to(format!("{}{redirect}", admin_path())))
} else { } else {
Err(AdminResponse::Ok(render_admin_page())) Err(AdminResponse::Ok(render_admin_page(&locale.locale)))
} }
} else { } else {
error!("Invalid admin token. IP: {}", ip.ip); error!("Invalid admin token. IP: {}", ip.ip);
Err(AdminResponse::Unauthorized(render_admin_login( 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(), redirect.as_deref(),
&locale.locale,
))) )))
} }
} }
@ -256,41 +292,46 @@ struct AdminTemplateData {
logged_in: bool, logged_in: bool,
urlpath: String, urlpath: String,
sso_enabled: bool, sso_enabled: bool,
lang: String,
} }
impl AdminTemplateData { impl AdminTemplateData {
fn new(page_content: &str, page_data: Value) -> Self { fn new(page_content: &str, page_data: Value, locale: &str) -> Self {
Self { Self {
page_content: String::from(page_content), page_content: localized_admin_template_name(page_content, locale),
page_data: Some(page_data), page_data: Some(page_data),
logged_in: true, logged_in: true,
urlpath: CONFIG.domain_path(), urlpath: CONFIG.domain_path(),
sso_enabled: CONFIG.sso_enabled(), sso_enabled: CONFIG.sso_enabled(),
lang: locale.to_owned(),
} }
} }
fn render(self) -> Result<String, Error> { fn render(self) -> Result<String, Error> {
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<Html<String>> { fn render_admin_page(locale: &str) -> ApiResult<Html<String>> {
let settings_json = json!({ let settings_json = json!({
"config": CONFIG.prepare_json(), "config": CONFIG.prepare_json(),
"can_backup": *CAN_BACKUP, "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)) Ok(Html(text))
} }
#[get("/")] #[get("/")]
fn admin_page(_token: AdminToken) -> ApiResult<Html<String>> { #[allow(clippy::needless_pass_by_value)]
render_admin_page() fn admin_page(_token: AdminToken, locale: RequestLocale) -> ApiResult<Html<String>> {
render_admin_page(&locale.locale)
} }
#[get("/", rank = 2)] #[get("/", rank = 2)]
fn admin_page_login() -> ApiResult<Html<String>> { #[allow(clippy::needless_pass_by_value)]
render_admin_login(None, None) fn admin_page_login(locale: RequestLocale) -> ApiResult<Html<String>> {
render_admin_login(None, None, &locale.locale)
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@ -338,13 +379,13 @@ async fn invite_user(data: Json<InviteData>, _token: AdminToken, conn: DbConn) -
} }
#[post("/test/smtp", format = "application/json", data = "<data>")] #[post("/test/smtp", format = "application/json", data = "<data>")]
async fn test_smtp(data: Json<InviteData>, _token: AdminToken) -> EmptyResult { async fn test_smtp(data: Json<InviteData>, _token: AdminToken, locale: RequestLocale) -> EmptyResult {
let data: InviteData = data.into_inner(); let data: InviteData = data.into_inner();
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
mail::send_test(&data.email).await mail::send_test_for_locale(&data.email, Some(&locale.locale)).await
} else { } 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<Value> {
} }
#[get("/users/overview")] #[get("/users/overview")]
async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<String>> { async fn users_overview(_token: AdminToken, locale: RequestLocale, conn: DbConn) -> ApiResult<Html<String>> {
let users = User::get_all(&conn).await; let users = User::get_all(&conn).await;
let mut users_json = Vec::with_capacity(users.len()); let mut users_json = Vec::with_capacity(users.len());
for (u, sso_u) in users { for (u, sso_u) in users {
@ -393,7 +434,7 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<Stri
users_json.push(usr); users_json.push(usr);
} }
let text = AdminTemplateData::new("admin/users", json!(users_json)).render()?; let text = AdminTemplateData::new("admin/users", json!(users_json), &locale.locale).render()?;
Ok(Html(text)) Ok(Html(text))
} }
@ -557,24 +598,29 @@ struct MembershipTypeData {
} }
#[post("/users/org_type", format = "application/json", data = "<data>")] #[post("/users/org_type", format = "application/json", data = "<data>")]
async fn update_membership_type(data: Json<MembershipTypeData>, token: AdminToken, conn: DbConn) -> EmptyResult { async fn update_membership_type(
data: Json<MembershipTypeData>,
token: AdminToken,
locale: RequestLocale,
conn: DbConn,
) -> EmptyResult {
let data: MembershipTypeData = data.into_inner(); 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 let Some(mut member_to_edit) = Membership::find_by_user_and_org(&data.user_uuid, &data.org_uuid, &conn).await
else { 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()) { let new_type = if let Some(new_type) = MembershipType::from_str(&data.user_type.into_string()) {
new_type as i32 new_type as i32
} else { } else {
err!("Invalid type") err!(crate::i18n::org_invalid_type(&locale.locale))
}; };
if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner { if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner {
// Removing owner permission, check that there is at least one other confirmed 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 { 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")] #[get("/organizations/overview")]
async fn organizations_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<String>> { async fn organizations_overview(_token: AdminToken, locale: RequestLocale, conn: DbConn) -> ApiResult<Html<String>> {
let organizations = Organization::get_all(&conn).await; let organizations = Organization::get_all(&conn).await;
let mut organizations_json = Vec::with_capacity(organizations.len()); let mut organizations_json = Vec::with_capacity(organizations.len());
for o in organizations { for o in organizations {
@ -617,13 +663,14 @@ async fn organizations_overview(_token: AdminToken, conn: DbConn) -> ApiResult<H
organizations_json.push(org); organizations_json.push(org);
} }
let text = AdminTemplateData::new("admin/organizations", json!(organizations_json)).render()?; let text = AdminTemplateData::new("admin/organizations", json!(organizations_json), &locale.locale).render()?;
Ok(Html(text)) Ok(Html(text))
} }
#[post("/organizations/<org_id>/delete", format = "application/json")] #[post("/organizations/<org_id>/delete", format = "application/json")]
async fn delete_organization(org_id: OrganizationId, _token: AdminToken, conn: DbConn) -> EmptyResult { 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 org.delete(&conn).await
} }
@ -759,7 +806,12 @@ fn folder_has_hbs_files(dir: &std::path::Path) -> bool {
} }
#[get("/diagnostics")] #[get("/diagnostics")]
async fn diagnostics(_token: AdminToken, ip_header: IpHeader, conn: DbConn) -> ApiResult<Html<String>> { async fn diagnostics(
_token: AdminToken,
locale: RequestLocale,
ip_header: IpHeader,
conn: DbConn,
) -> ApiResult<Html<String>> {
use chrono::prelude::*; use chrono::prelude::*;
use std::net::ToSocketAddrs; 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 "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)) Ok(Html(text))
} }
@ -845,7 +897,7 @@ fn get_diagnostics_http(code: u16, _token: AdminToken) -> EmptyResult {
async fn post_config(data: Json<ConfigBuilder>, _token: AdminToken) -> EmptyResult { async fn post_config(data: Json<ConfigBuilder>, _token: AdminToken) -> EmptyResult {
let data: ConfigBuilder = data.into_inner(); let data: ConfigBuilder = data.into_inner();
if let Err(e) = CONFIG.update_config(data, true).await { 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(()) Ok(())
} }
@ -853,20 +905,21 @@ async fn post_config(data: Json<ConfigBuilder>, _token: AdminToken) -> EmptyResu
#[post("/config/delete", format = "application/json")] #[post("/config/delete", format = "application/json")]
async fn delete_config(_token: AdminToken) -> EmptyResult { async fn delete_config(_token: AdminToken) -> EmptyResult {
if let Err(e) = CONFIG.delete_user_config().await { 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(()) Ok(())
} }
#[post("/config/backup_db", format = "application/json")] #[post("/config/backup_db", format = "application/json")]
fn backup_db(_token: AdminToken) -> ApiResult<String> { #[allow(clippy::needless_pass_by_value)]
fn backup_db(_token: AdminToken, locale: RequestLocale) -> ApiResult<String> {
if *CAN_BACKUP { if *CAN_BACKUP {
match backup_sqlite() { match backup_sqlite() {
Ok(f) => Ok(format!("Backup to '{f}' was successful")), 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 { } else {
err!("Can't back up current DB (Only SQLite supports this feature)"); err!(crate::i18n::admin_backup_only_sqlite(&locale.locale));
} }
} }

226
src/api/core/accounts.rs

@ -248,9 +248,9 @@ fn clean_password_hint(password_hint: Option<&String>) -> Option<String> {
} }
} }
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() { 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(()) Ok(())
} }
@ -267,7 +267,7 @@ async fn is_email_2fa_required(member_id: Option<MembershipId>, conn: &DbConn) -
false false
} }
pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult { pub async fn register(data: Json<RegisterData>, conn: DbConn, locale: &str) -> JsonResult {
let data: RegisterData = data.into_inner(); let data: RegisterData = data.into_inner();
let email = data.email.to_lowercase(); let email = data.email.to_lowercase();
@ -290,7 +290,7 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
(Some(email_verification_token), None, None, None, None) => { (Some(email_verification_token), None, None, None, None) => {
let claims = crate::auth::decode_register_verify(email_verification_token)?; let claims = crate::auth::decode_register_verify(email_verification_token)?;
if claims.sub != data.email { 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 // 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<RegisterData>, conn: DbConn) -> JsonResult {
// Emergency access registration // Emergency access registration
(None, Some(accept_emergency_access_id), Some(accept_emergency_access_invite_token), None, None) => { (None, Some(accept_emergency_access_id), Some(accept_emergency_access_invite_token), None, None) => {
if !CONFIG.emergency_access_allowed() { 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)?; let claims = crate::auth::decode_emergency_access_invite(accept_emergency_access_invite_token)?;
if claims.email != data.email { 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 { 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)); pending_emergency_access = Some((accept_emergency_access_id, claims));
@ -320,18 +320,18 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
let claims = decode_invite(org_invite_token)?; let claims = decode_invite(org_invite_token)?;
if claims.email != data.email { 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 { 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 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<RegisterData>, conn: DbConn) -> JsonResult {
if let Some(ref name) = name if let Some(ref name) = name
&& name.len() > 50 && 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 // Check against the password hint setting here so if it fails, the user
// can retry without losing their invitation below. // can retry without losing their invitation below.
let password_hint = clean_password_hint(data.master_password_hint.as_ref()); 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 { let mut user = match User::find_by_mail(&email, &conn).await {
Some(user) => { Some(user) => {
if !user.password_hash.is_empty() { 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() { if let Some(token) = data.org_invite_token.as_ref() {
@ -361,7 +361,7 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
email_verified = true; email_verified = true;
user user
} else { } 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 { } else if Invitation::take(&email, &conn).await {
Membership::accept_user_invitations(&user.uuid, &conn).await?; Membership::accept_user_invitations(&user.uuid, &conn).await?;
@ -372,7 +372,7 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
{ {
user user
} else { } else {
err!("Registration not allowed or user already exists") err!(crate::i18n::accounts_registration_not_allowed_or_exists(locale))
} }
} }
None => { None => {
@ -385,7 +385,7 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
{ {
User::new(&email, None) User::new(&email, None)
} else { } 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<RegisterData>, conn: DbConn) -> JsonResult {
// Make sure we don't leave a lingering invitation. // Make sure we don't leave a lingering invitation.
Invitation::take(&email, &conn).await; Invitation::take(&email, &conn).await;
user.locale = Some(crate::i18n::normalize_locale(locale));
set_kdf_data(&mut user, data.kdf())?; set_kdf_data(&mut user, data.kdf())?;
user.set_password(&data.hash(), Some(data.key()), true, None, &conn).await?; user.set_password(&data.hash(), Some(data.key()), true, None, &conn).await?;
@ -414,11 +416,11 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
if CONFIG.signups_verify() && !email_verified { 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:#?}"); error!("Error sending welcome email: {e:#?}");
} }
user.last_verifying_at = Some(user.created_at); 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:#?}"); error!("Error sending welcome email: {e:#?}");
} }
@ -444,16 +446,17 @@ pub async fn register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
#[post("/accounts/set-password", data = "<data>")] #[post("/accounts/set-password", data = "<data>")]
async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn: DbConn) -> JsonResult { async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: SetPasswordData = data.into_inner(); let data: SetPasswordData = data.into_inner();
let locale = &headers.locale;
let mut user = headers.user; let mut user = headers.user;
if user.private_key.is_some() || !user.password_hash.is_empty() { 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, // Check against the password hint setting here so if it fails,
// the user can retry without losing their invitation below. // the user can retry without losing their invitation below.
let password_hint = clean_password_hint(data.master_password_hint.as_ref()); 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)?; set_kdf_data(&mut user, &data.kdf)?;
@ -477,18 +480,18 @@ async fn post_set_password(data: Json<SetPasswordData>, headers: Headers, conn:
&& identifier != crate::api::admin::FAKE_ADMIN_UUID && identifier != crate::api::admin::FAKE_ADMIN_UUID
{ {
let Some(org) = Organization::find_by_uuid(&identifier.into(), &conn).await else { 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 { 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?; accept_org_invite(&user, membership, None, &conn).await?;
} }
if CONFIG.mail_enabled() { 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 { } else {
Membership::accept_user_invitations(&user.uuid, &conn).await?; Membership::accept_user_invitations(&user.uuid, &conn).await?;
} }
@ -510,7 +513,7 @@ async fn profile(headers: Headers, conn: DbConn) -> Json<Value> {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct ProfileData { struct ProfileData {
// culture: String, // Ignored, always use en-US culture: Option<String>,
name: String, name: String,
} }
@ -526,11 +529,14 @@ async fn post_profile(data: Json<ProfileData>, headers: Headers, conn: DbConn) -
// Check if the length of the username exceeds 50 characters (Same is Upstream Bitwarden) // 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 // This also prevents issues with very long usernames causing to large JWT's. See #2419
if data.name.len() > 50 { 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; let mut user = headers.user;
user.name = data.name; user.name = data.name;
if let Some(culture) = data.culture {
user.locale = Some(crate::i18n::normalize_locale(&culture));
}
user.save(&conn).await?; user.save(&conn).await?;
Ok(Json(user.to_json(&conn).await)) Ok(Json(user.to_json(&conn).await))
@ -552,7 +558,7 @@ async fn put_avatar(data: Json<AvatarData>, headers: Headers, conn: DbConn) -> J
if let Some(color) = &data.avatar_color if let Some(color) = &data.avatar_color
&& color.len() != 7 && 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; let mut user = headers.user;
@ -602,7 +608,7 @@ async fn post_keys(data: Json<KeysData>, headers: Headers, conn: DbConn) -> Json
let mut user = headers.user; let mut user = headers.user;
if user.private_key.is_some() || user.public_key.is_some() { 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); user.private_key = Some(data.encrypted_private_key);
@ -636,7 +642,7 @@ async fn post_password(data: Json<ChangePassData>, headers: Headers, conn: DbCon
let user = headers.user; let user = headers.user;
if !user.check_valid_password(&data.master_password_hash) { 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; 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<ChangePassData>, headers: Headers, conn: DbCon
let (new_master_password_hash, new_key) = let (new_master_password_hash, new_key) =
if let (Some(unlock_data), Some(authentication_data)) = (data.unlock_data, data.authentication_data) { if let (Some(unlock_data), Some(authentication_data)) = (data.unlock_data, data.authentication_data) {
if authentication_data.kdf != unlock_data.kdf { 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 { 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) (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) { } else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) {
(new_master_password_hash, new_key) (new_master_password_hash, new_key)
} else { } else {
err!("Invalid request!") err!(crate::i18n::accounts_invalid_request(&headers.locale))
}; };
let mut user = user; let mut user = user;
user.password_hint = clean_password_hint(data.master_password_hint.as_ref()); 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( user.set_password(
&new_master_password_hash, &new_master_password_hash,
@ -688,29 +694,30 @@ async fn post_password(data: Json<ChangePassData>, headers: Headers, conn: DbCon
} }
fn set_kdf_data(user: &mut User, data: &KDFData) -> EmptyResult { 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 { 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 == UserKdfType::Argon2id as i32 {
if data.kdf_iterations < 1 { 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 let Some(m) = data.kdf_memory {
if !(15..=1024).contains(&m) { 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; user.client_kdf_memory = data.kdf_memory;
} else { } else {
err!("Argon2 memory parameter is required.") err!(crate::i18n::accounts_argon2_memory_required(locale))
} }
if let Some(p) = data.kdf_parallelism { if let Some(p) = data.kdf_parallelism {
if !(1..=16).contains(&p) { 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; user.client_kdf_parallelism = data.kdf_parallelism;
} else { } else {
err!("Argon2 parallelism parameter is required.") err!(crate::i18n::accounts_argon2_parallelism_required(locale))
} }
} else { } else {
user.client_kdf_memory = None; user.client_kdf_memory = None;
@ -735,12 +742,13 @@ pub(super) struct AuthenticationData {
impl AuthenticationData { impl AuthenticationData {
pub(super) fn check(&self, user: &User, unlock: &UnlockData) -> EmptyResult { pub(super) fn check(&self, user: &User, unlock: &UnlockData) -> EmptyResult {
let locale = &CONFIG.default_locale();
if self.kdf != unlock.kdf { 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 { 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(()) Ok(())
@ -768,7 +776,7 @@ async fn post_kdf(data: Json<ChangeKdfData>, headers: Headers, conn: DbConn, nt:
let data: ChangeKdfData = data.into_inner(); let data: ChangeKdfData = data.into_inner();
if !headers.user.check_valid_password(&data.master_password_hash) { 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)?; data.authentication_data.check(&headers.user, &data.unlock_data)?;
@ -870,16 +878,17 @@ fn validate_keydata(
existing_sends: &[Send], existing_sends: &[Send],
user: &User, user: &User,
) -> EmptyResult { ) -> EmptyResult {
let locale = &CONFIG.default_locale();
if user.client_kdf_type != data.account_unlock_data.master_password_unlock_data.kdf_type 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_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_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.client_kdf_parallelism != data.account_unlock_data.master_password_unlock_data.kdf_parallelism
|| user.email != data.account_unlock_data.master_password_unlock_data.email || 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) { 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 // 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()) .filter_map(|c| c.id.as_ref())
.collect::<HashSet<&CipherId>>(); .collect::<HashSet<&CipherId>>();
if !provided_cipher_ids.is_superset(&existing_cipher_ids) { 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 // Check that we're correctly rotating all the user's folders
@ -900,7 +909,7 @@ fn validate_keydata(
let provided_folder_ids = let provided_folder_ids =
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>(); data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
if !provided_folder_ids.is_superset(&existing_folder_ids) { 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 // Check that we're correctly rotating all the user's emergency access keys
@ -913,7 +922,7 @@ fn validate_keydata(
.map(|ea| &ea.id) .map(|ea| &ea.id)
.collect::<HashSet<&EmergencyAccessId>>(); .collect::<HashSet<&EmergencyAccessId>>();
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) { 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 // 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) .map(|rp| &rp.organization_id)
.collect::<HashSet<&OrganizationId>>(); .collect::<HashSet<&OrganizationId>>();
if !provided_reset_password_ids.is_superset(&existing_reset_password_ids) { 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 // Check that we're correctly rotating all the user's sends
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>(); let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>(); let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
if !provided_send_ids.is_superset(&existing_send_ids) { 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(()) Ok(())
@ -945,7 +954,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
let data: KeyData = data.into_inner(); let data: KeyData = data.into_inner();
if !headers.user.check_valid_password(&data.old_master_key_authentication_hash) { 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 // Validate the import before continuing
@ -982,7 +991,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
// See: https://github.com/bitwarden/clients/issues/8453 // See: https://github.com/bitwarden/clients/issues/8453
if let Some(folder_id) = folder_data.id { if let Some(folder_id) = folder_data.id {
let Some(saved_folder) = existing_folders.iter_mut().find(|f| f.uuid == folder_id) else { 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; saved_folder.name = folder_data.name;
@ -995,7 +1004,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
let Some(saved_emergency_access) = let Some(saved_emergency_access) =
existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id) existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id)
else { 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); saved_emergency_access.key_encrypted = Some(emergency_access_data.key_encrypted);
@ -1007,7 +1016,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
let Some(membership) = let Some(membership) =
existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id) existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id)
else { 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); membership.reset_password_key = Some(reset_password_data.reset_password_key);
@ -1017,7 +1026,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
// Update send data // Update send data
for send_data in data.account_data.sends { 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 { 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 // Like upstream, only the key changes on rotation
@ -1031,7 +1040,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
let Some(saved_cipher) = let Some(saved_cipher) =
cipher_data.id.as_ref().and_then(|id| existing_ciphers.iter_mut().find(|c| &c.uuid == id)) cipher_data.id.as_ref().and_then(|id| existing_ciphers.iter_mut().find(|c| &c.uuid == id))
else { 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 // Prevent triggering cipher updates via WebSockets by settings UpdateType::None
@ -1108,14 +1117,14 @@ struct EmailTokenData {
#[post("/accounts/email-token", data = "<data>")] #[post("/accounts/email-token", data = "<data>")]
async fn post_email_token(data: Json<EmailTokenData>, headers: Headers, conn: DbConn) -> EmptyResult { async fn post_email_token(data: Json<EmailTokenData>, headers: Headers, conn: DbConn) -> EmptyResult {
if !CONFIG.email_change_allowed() { 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 data: EmailTokenData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
if !user.check_valid_password(&data.master_password_hash) { 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 { 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<EmailTokenData>, headers: Headers, conn: Db
if existing_user.password_hash.is_empty() { if existing_user.password_hash.is_empty() {
// inform an invited user about how to delete their temporary account if the // 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 // 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:#?}"); error!("Error sending change-email-invited email: {e:#?}");
} }
} else { } else {
// inform existing user about the failed attempt to change their mail address // 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:#?}"); 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) { 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); let token = crypto::generate_email_token(6);
if CONFIG.mail_enabled() { 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:#?}"); error!("Error sending change-email email: {e:#?}");
} }
} else { } else {
@ -1170,36 +1185,36 @@ struct ChangeEmailData {
#[post("/accounts/email", data = "<data>")] #[post("/accounts/email", data = "<data>")]
async fn post_email(data: Json<ChangeEmailData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { async fn post_email(data: Json<ChangeEmailData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
if !CONFIG.email_change_allowed() { 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 data: ChangeEmailData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
if !user.check_valid_password(&data.master_password_hash) { 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() { 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 let Some(ref val) = user.email_new {
if val != &data.new_email { if val != &data.new_email {
err!("Email change mismatch"); err!(crate::i18n::accounts_email_change_mismatch(&headers.locale));
} }
} else { } else {
err!("No email change pending") err!(crate::i18n::accounts_no_email_change_pending(&headers.locale))
} }
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
// Only check the token if we sent out an email... // Only check the token if we sent out an email...
if let Some(ref val) = user.email_new_token { if let Some(ref val) = user.email_new_token {
if *val != data.token.into_string() { if *val != data.token.into_string() {
err!("Token mismatch"); err!(crate::i18n::accounts_token_mismatch(&headers.locale));
} }
} else { } else {
err!("No email change pending") err!(crate::i18n::accounts_no_email_change_pending(&headers.locale))
} }
user.verified_at = Some(Utc::now().naive_utc()); user.verified_at = Some(Utc::now().naive_utc());
} else { } else {
@ -1224,10 +1239,10 @@ async fn post_verify_email(headers: Headers) -> EmptyResult {
let user = headers.user; let user = headers.user;
if !CONFIG.mail_enabled() { 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:#?}"); error!("Error sending verify_email email: {e:#?}");
} }
@ -1246,14 +1261,14 @@ async fn post_verify_email_token(data: Json<VerifyEmailTokenData>, conn: DbConn)
let data: VerifyEmailTokenData = data.into_inner(); let data: VerifyEmailTokenData = data.into_inner();
let Some(mut user) = User::find_by_uuid(&data.user_id, &conn).await else { 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 { 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 { 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.verified_at = Some(Utc::now().naive_utc());
user.last_verifying_at = None; user.last_verifying_at = None;
@ -1279,7 +1294,7 @@ async fn post_delete_recover(data: Json<DeleteRecoverData>, ip: ClientIp, conn:
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
if let Some(user) = User::find_by_mail(&data.email, &conn).await 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:#?}"); error!("Error sending delete account email: {e:#?}");
} }
@ -1289,7 +1304,7 @@ async fn post_delete_recover(data: Json<DeleteRecoverData>, ip: ClientIp, conn:
// to delete accounts without at least logging in... And if the user // to delete accounts without at least logging in... And if the user
// cannot remember their password then they will need to contact // cannot remember their password then they will need to contact
// the administrator to delete it... // 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<DeleteRecoverTokenData>, conn: DbC
let data: DeleteRecoverTokenData = data.into_inner(); let data: DeleteRecoverTokenData = data.into_inner();
let Ok(claims) = decode_delete(&data.token) else { 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 { 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 { 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 // The devices are deleted together with the user, so check for push devices beforehand
@ -1375,7 +1390,7 @@ async fn password_hint(data: Json<PasswordHintData>, ip: ClientIp, conn: DbConn)
crate::ratelimit::check_limit_unauthenticated(&ip.ip)?; crate::ratelimit::check_limit_unauthenticated(&ip.ip)?;
if !CONFIG.password_hints_allowed() || (!CONFIG.mail_enabled() && !CONFIG.show_password_hint()) { 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(); let data: PasswordHintData = data.into_inner();
@ -1400,10 +1415,11 @@ async fn password_hint(data: Json<PasswordHintData>, ip: ClientIp, conn: DbConn)
Some(user) => { Some(user) => {
let hint: Option<String> = user.password_hint; let hint: Option<String> = user.password_hint;
if CONFIG.mail_enabled() { 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(()) Ok(())
} else if let Some(hint) = hint { } 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 { } else {
err!(NO_HINT); err!(NO_HINT);
} }
@ -1487,7 +1503,7 @@ async fn verify_password(data: Json<SecretVerificationRequest>, headers: Headers
let mut user = headers.user; let mut user = headers.user;
if !user.check_valid_password(&data.master_password_hash) { 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?; 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/<device_id>")] #[get("/devices/identifier/<device_id>")]
async fn get_device(device_id: DeviceId, headers: Headers, conn: DbConn) -> JsonResult { 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 { 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())) Ok(Json(device.to_json()))
} }
@ -1612,7 +1628,10 @@ async fn put_device_token(device_id: DeviceId, data: Json<PushToken>, headers: H
let token = data.push_token; let token = data.push_token;
let Some(mut device) = Device::find_by_uuid_and_user(&headers.device.uuid, &headers.user.uuid, &conn).await else { 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 // 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<PushToken>, headers: H
device.push_token = Some(token); device.push_token = Some(token);
if let Err(e) = device.save(true, &conn).await { 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?; register_push_device(&mut device, &conn).await?;
@ -1694,13 +1713,19 @@ async fn post_auth_request(
let data = data.into_inner(); let data = data.into_inner();
let Some(user) = User::find_by_mail(&data.email, &conn).await else { 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 // Validate device uuid and type
let device = match Device::find_by_uuid_and_user(&data.device_identifier, &user.uuid, &conn).await { 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, 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( 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 { 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 let Some(auth_request) = AuthRequest::find_by_uuid_and_user(&auth_request_id, &headers.user.uuid, &conn).await
else { 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)); 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 data = data.into_inner();
let Some(mut auth_request) = AuthRequest::find_by_uuid_and_user(&auth_request_id, &headers.user.uuid, &conn).await let Some(mut auth_request) = AuthRequest::find_by_uuid_and_user(&auth_request_id, &headers.user.uuid, &conn).await
else { 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 { 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() { 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(); 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)?; crate::ratelimit::check_limit_unauthenticated(&client_headers.ip.ip)?;
let Some(auth_request) = AuthRequest::find_by_uuid(&auth_request_id, &conn).await else { 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 if auth_request.device_type != client_headers.device_type
|| auth_request.request_ip != client_headers.ip.ip.to_string() || auth_request.request_ip != client_headers.ip.ip.to_string()
|| !auth_request.check_access_code(code) || !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)); let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date));

173
src/api/core/ciphers.rs

@ -234,11 +234,11 @@ async fn get_ciphers(headers: Headers, conn: DbConn) -> JsonResult {
#[get("/ciphers/<cipher_id>")] #[get("/ciphers/<cipher_id>")]
async fn get_cipher(cipher_id: CipherId, headers: Headers, conn: DbConn) -> JsonResult { async fn get_cipher(cipher_id: CipherId, headers: Headers, conn: DbConn) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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?)) 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 user_id = &headers.user.uuid;
let policy_type = OrgPolicyType::PersonalOwnership; let policy_type = OrgPolicyType::PersonalOwnership;
if OrgPolicy::is_applicable_to_user(user_id, policy_type, None, conn).await { 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(()) Ok(())
@ -460,20 +460,25 @@ pub async fn update_cipher_from_data(
// ISO 8601 format // ISO 8601 format
Err(err) => warn!("Error parsing LastKnownRevisionDate '{dt}': {err}"), Err(err) => warn!("Error parsing LastKnownRevisionDate '{dt}': {err}"),
Ok(dt) if cipher.updated_at.signed_duration_since(dt).num_seconds() > 1 => { 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(_) => (), Ok(_) => (),
} }
} }
if cipher.organization_uuid.is_some() && cipher.organization_uuid != data.organization_id { 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 { if let Some(note) = &data.notes {
let max_note_size = CONFIG._max_note_size(); let max_note_size = CONFIG._max_note_size();
if note.len() > 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 { if let Some(org_id) = data.organization_id {
match Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &org_id, conn).await { 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) => { Some(member) => {
// A non-empty list of collections implies the caller already validated the user's write // 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. // 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. // 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; cipher.user_uuid = None;
} else { } 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 if let Some(ref folder_id) = data.folder_id
&& Folder::find_by_uuid_and_user(folder_id, &headers.user.uuid, conn).await.is_none() && 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 // Modify attachments name and keys when rotating
@ -548,7 +553,7 @@ pub async fn update_cipher_from_data(
6 => data.bank_account, 6 => data.bank_account,
7 => data.drivers_license, 7 => data.drivers_license,
8 => data.passport, 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 { let type_data = if let Some(mut data) = type_data_opt {
@ -562,7 +567,7 @@ pub async fn update_cipher_from_data(
} }
data data
} else { } else {
err!("Data missing") err!(crate::i18n::cipher_data_missing(&headers.locale))
}; };
cipher.key = data.key; cipher.key = data.key;
@ -731,7 +736,7 @@ async fn put_cipher(
let data: CipherData = data.into_inner(); let data: CipherData = data.into_inner();
let Some(mut cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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. // 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. // Interestingly, upstream Bitwarden doesn't properly handle this either.
if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn).await { 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 // Moving a cipher into an organization is only possible through the share endpoints
if cipher.organization_uuid != data.organization_id { 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?; 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 data: PartialCipherData = data.into_inner();
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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 if let Some(ref folder_id) = data.folder_id
&& Folder::find_by_uuid_and_user(folder_id, &headers.user.uuid, &conn).await.is_none() && 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 // Move cipher
@ -851,15 +856,15 @@ async fn post_collections_update(
let data: CollectionsAdminData = data.into_inner(); let data: CollectionsAdminData = data.into_inner();
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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 { 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::<CollectionId>::from_iter(data.collection_ids); let posted_collections = HashSet::<CollectionId>::from_iter(data.collection_ids);
@ -868,7 +873,7 @@ async fn post_collections_update(
for collection in posted_collections.symmetric_difference(&current_collections) { for collection in posted_collections.symmetric_difference(&current_collections) {
match Collection::find_by_uuid_and_org(collection, org_uuid, &conn).await { 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) => { Some(collection) => {
if collection.is_writable_by_user(&headers.user.uuid, &conn).await { if collection.is_writable_by_user(&headers.user.uuid, &conn).await {
if posted_collections.contains(&collection.uuid) { if posted_collections.contains(&collection.uuid) {
@ -879,7 +884,7 @@ async fn post_collections_update(
CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?; CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?;
} }
} else { } 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 data: CollectionsAdminData = data.into_inner();
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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 { 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::<CollectionId>::from_iter(data.collection_ids); let posted_collections = HashSet::<CollectionId>::from_iter(data.collection_ids);
@ -948,7 +953,7 @@ async fn post_collections_admin(
for collection in posted_collections.symmetric_difference(&current_collections) { for collection in posted_collections.symmetric_difference(&current_collections) {
match Collection::find_by_uuid_and_org(collection, org_uuid, &conn).await { 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) => { Some(collection) => {
if collection.is_writable_by_user(&headers.user.uuid, &conn).await { if collection.is_writable_by_user(&headers.user.uuid, &conn).await {
if posted_collections.contains(&collection.uuid) { if posted_collections.contains(&collection.uuid) {
@ -959,7 +964,7 @@ async fn post_collections_admin(
CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?; CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn).await?;
} }
} else { } 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(); let data: ShareCipherData = data.into_inner();
if data.cipher.organization_id.is_none() { 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() { 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 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(); let data: ShareSelectedCipherData = data.into_inner();
if data.ciphers.is_empty() { 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() { 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 { for cipher in &data.ciphers {
if cipher.id.is_none() { 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() { 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())); responses.push(cipher_mini_from_json(response.into_inner()));
} }
} else { } 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 { if cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await {
cipher cipher
} else { } else {
err!("Cipher is not write accessible") err!(crate::i18n::cipher_not_write_accessible(&headers.locale))
} }
} else { } 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 // `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 // already linked. There are no transactions, so that would leave the cipher linked to a
// collection of another organization. // collection of another organization.
if cipher.organization_uuid.is_some() && cipher.organization_uuid != data.cipher.organization_id { 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![]; 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 { if let Some(organization_id) = &data.cipher.organization_id {
for col_id in &data.collection_ids { for col_id in &data.collection_ids {
match Collection::find_by_uuid_and_org(col_id, organization_id, conn).await { 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) => { Some(collection) => {
if collection.is_writable_by_user(&headers.user.uuid, conn).await { if collection.is_writable_by_user(&headers.user.uuid, conn).await {
CollectionCipher::save(&cipher.uuid, &collection.uuid, conn).await?; CollectionCipher::save(&cipher.uuid, &collection.uuid, conn).await?;
shared_to_collections.push(collection.uuid); shared_to_collections.push(collection.uuid);
} else { } 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, conn: DbConn,
) -> JsonResult { ) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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 { 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(attachment) if cipher_id == attachment.cipher_uuid => Ok(Json(attachment.to_json(&headers.host).await?)),
Some(_) => err!("Attachment doesn't belong to cipher"), Some(_) => err!(crate::i18n::cipher_attachment_not_belong_to_cipher(&headers.locale)),
None => err!("Attachment doesn't exist"), 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) (limit_kb, Attachment::size_by_org(org_id, conn).await)
} else { } 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 { if limit_kb == 0 {
err!("Attachments are disabled") err!(crate::i18n::cipher_attachments_disabled(&CONFIG.default_locale()))
} }
let Some(left) = let Some(left) =
limit_kb.checked_mul(1024).and_then(|l| l.checked_sub(already_used)).and_then(|l| l.checked_add(size_adjust)) limit_kb.checked_mul(1024).and_then(|l| l.checked_sub(already_used)).and_then(|l| l.checked_add(size_adjust))
else { else {
err!("Attachment size overflow"); err!(crate::i18n::cipher_attachment_size_overflow(&CONFIG.default_locale()));
}; };
if left <= 0 { 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)) Ok(Some(left))
@ -1283,28 +1288,28 @@ async fn post_attachment_v2(
nt: Notify<'_>, nt: Notify<'_>,
) -> JsonResult { ) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(&cipher_id, &conn).await else { 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 { 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 data: AttachmentRequestData = data.into_inner();
let file_size = data.file_size.into_i64()?; let file_size = data.file_size.into_i64()?;
if file_size < 0 { 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 // Matches the "file" upload limit in main.rs, nothing larger can be uploaded
if file_size > SIZE_525_MB { 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? if let Some(size_limit) = attachment_size_limit(&cipher, 0, &conn).await?
&& file_size > size_limit && 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(); let attachment_id = crypto::generate_attachment_id();
@ -1353,18 +1358,18 @@ async fn save_attachment(
let data = data.into_inner(); let data = data.into_inner();
let Some(size) = data.data.len().to_i64() else { 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 { 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 { 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 { 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, // 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? if let Some(size_limit) = attachment_size_limit(&cipher, size_adjust, &conn).await?
&& size > size_limit && 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 { 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. // size, but it's not clear when or why this is needed.
const LEEWAY: i64 = 1024 * 1024; // 1 MiB const LEEWAY: i64 = 1024 * 1024; // 1 MiB
let Some(max_size) = attachment.file_size.checked_add(LEEWAY) else { 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 { 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 { if min_size <= size && size <= max_size {
@ -1408,7 +1413,10 @@ async fn save_attachment(
} else { } else {
attachment.delete(&conn).await.ok(); 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 { } else {
// Legacy API // 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()); let encrypted_filename = data.data.raw_name().map(|s| s.dangerous_unsafe_unsanitized_raw().to_string());
if encrypted_filename.is_none() { if encrypted_filename.is_none() {
err!("No filename provided") err!(crate::i18n::cipher_no_filename_provided(&headers.locale))
} }
if data.key.is_none() { if data.key.is_none() {
err!("No attachment key provided") err!(crate::i18n::cipher_no_attachment_key_provided(&headers.locale))
} }
let attachment = let attachment =
Attachment::new(file_id.clone(), cipher_id.clone(), encrypted_filename.unwrap(), size, data.key); 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 { ) -> EmptyResult {
let attachment = match Attachment::find_by_id(&attachment_id, &conn).await { let attachment = match Attachment::find_by_id(&attachment_id, &conn).await {
Some(attachment) if cipher_id == attachment.cipher_uuid => Some(attachment), Some(attachment) if cipher_id == attachment.cipher_uuid => Some(attachment),
Some(_) => err!("Attachment doesn't belong to cipher"), Some(_) => err!(crate::i18n::cipher_attachment_not_belong_to_cipher(&headers.locale)),
None => err!("Attachment doesn't exist"), None => err!(crate::i18n::cipher_attachment_not_found(&headers.locale)),
}; };
save_attachment(attachment, cipher_id, data, &headers, conn, nt).await?; 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 if let Some(ref folder_id) = data.folder_id
&& Folder::find_by_uuid_and_user(folder_id, user_id, &conn).await.is_none() && 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(); let cipher_count = data.ids.len();
@ -1771,9 +1779,9 @@ async fn move_cipher_selected(
} }
if cipher_count != accessible_ciphers_count { if cipher_count != accessible_ciphers_count {
err!(format!( let msg =
"Not all ciphers are moved! {accessible_ciphers_count} of the selected {cipher_count} were moved." format!("Not all ciphers are moved! {accessible_ciphers_count} of the selected {cipher_count} were moved.");
)) err!(msg)
} }
Ok(()) Ok(())
@ -1807,8 +1815,9 @@ async fn purge_org_vault(
conn: DbConn, conn: DbConn,
nt: Notify<'_>, nt: Notify<'_>,
) -> EmptyResult { ) -> EmptyResult {
let locale = headers.user.locale.clone().unwrap_or_else(|| CONFIG.default_locale());
if organization.org_id != headers.org_id { 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(); let data: PasswordOrOtpData = data.into_inner();
@ -1834,7 +1843,7 @@ async fn purge_org_vault(
Ok(()) 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<'_>, nt: &Notify<'_>,
) -> EmptyResult { ) -> EmptyResult {
let Some(mut cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { 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 { 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 { if *delete_options == CipherDeleteOptions::SoftSingle || *delete_options == CipherDeleteOptions::SoftMulti {
@ -1997,11 +2006,11 @@ async fn restore_cipher_by_uuid(
nt: &Notify<'_>, nt: &Notify<'_>,
) -> JsonResult { ) -> JsonResult {
let Some(mut cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { 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 { 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; cipher.deleted_at = None;
@ -2069,19 +2078,19 @@ async fn delete_cipher_attachment_by_id(
nt: &Notify<'_>, nt: &Notify<'_>,
) -> JsonResult { ) -> JsonResult {
let Some(attachment) = Attachment::find_by_id(attachment_id, conn).await else { 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 { 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 { 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 { 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 // Delete attachment
@ -2120,11 +2129,11 @@ async fn archive_cipher(
nt: &Notify<'_>, nt: &Notify<'_>,
) -> JsonResult { ) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { 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 { 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?; cipher.set_archived_at(Utc::now().naive_utc(), &headers.user.uuid, conn).await?;
@ -2152,11 +2161,11 @@ async fn unarchive_cipher(
nt: &Notify<'_>, nt: &Notify<'_>,
) -> JsonResult { ) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else { 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 { 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?; cipher.unarchive(&headers.user.uuid, conn).await?;

157
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!"), emergency_access.to_json_grantee_details(&conn).await.expect("Grantee user should exist but does not!"),
)) ))
} else { } 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 data: EmergencyAccessUpdateData = data.into_inner();
let Some(new_type) = EmergencyAccessType::from_str(&data.r#type.into_string()) else { 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) { 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) = let Some(mut emergency_access) =
EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await
else { else {
err!("Emergency access not valid.") err!(crate::i18n::emergency_access_not_valid(&headers.locale))
}; };
emergency_access.atype = new_type as i32; 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}"); info!("Grantee deleted emergency access {emer_id}");
grantee_emer grantee_emer
} }
_ => err!("Emergency access not valid."), _ => err!(crate::i18n::emergency_access_not_valid(&headers.locale)),
}; };
emergency_access.delete(&conn).await?; emergency_access.delete(&conn).await?;
@ -213,28 +213,31 @@ async fn send_invite(data: Json<EmergencyAccessInviteData>, headers: Headers, co
let wait_time_days = data.wait_time_days; let wait_time_days = data.wait_time_days;
if !(EMERGENCY_ACCESS_TIMEOUT_RANGE).contains(&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 { 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; let grantor_user = headers.user;
// avoid setting yourself as emergency contact // avoid setting yourself as emergency contact
if email == grantor_user.email { 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 { let (grantee_user, new_user) = match User::find_by_mail(&email, &conn).await {
None => { None => {
if !CONFIG.invitations_allowed() { 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) { 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() { if !CONFIG.mail_enabled() {
@ -259,7 +262,7 @@ async fn send_invite(data: Json<EmergencyAccessInviteData>, headers: Headers, co
.await .await
.is_some() .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; let new_type = new_type as i32;
@ -269,12 +272,13 @@ async fn send_invite(data: Json<EmergencyAccessInviteData>, headers: Headers, co
new_emergency_access.save(&conn).await?; new_emergency_access.save(&conn).await?;
if CONFIG.mail_enabled() { 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"), &new_emergency_access.email.expect("Grantee email does not exists"),
grantee_user.uuid, grantee_user.uuid,
new_emergency_access.uuid, new_emergency_access.uuid,
&grantor_user.name, &grantor_user.name,
&grantor_user.email, &grantor_user.email,
grantee_user.locale.as_deref(),
) )
.await?; .await?;
} else if !new_user { } else if !new_user {
@ -292,30 +296,31 @@ async fn resend_invite(emer_id: EmergencyAccessId, headers: Headers, conn: DbCon
let Some(mut emergency_access) = let Some(mut emergency_access) =
EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await
else { else {
err!("Emergency access not valid.") err!(crate::i18n::emergency_access_not_valid(&headers.locale))
}; };
if emergency_access.status != EmergencyAccessStatus::Invited as i32 { 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 { 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 { 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; let grantor_user = headers.user;
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
mail::send_emergency_access_invite( mail::send_emergency_access_invite_for_locale(
&email, &email,
grantor_user.uuid, grantor_user.uuid,
emergency_access.uuid, emergency_access.uuid,
&grantor_user.name, &grantor_user.name,
&grantor_user.email, &grantor_user.email,
grantee_user.locale.as_deref(),
) )
.await?; .await?;
} else if !grantee_user.password_hash.is_empty() { } 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. // 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. // 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 { 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 { let grantee_user = if let Some(user) = User::find_by_mail(&claims.email, &conn).await {
Invitation::take(&claims.email, &conn).await; Invitation::take(&claims.email, &conn).await;
user user
} else { } 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. // 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) = let Some(mut emergency_access) =
EmergencyAccess::find_by_uuid_and_grantee_email(&emer_id, &headers.user.email, &conn).await EmergencyAccess::find_by_uuid_and_grantee_email(&emer_id, &headers.user.email, &conn).await
else { else {
err!("Emergency access not valid.") err!(crate::i18n::emergency_access_not_valid(&headers.locale))
}; };
// get grantor user to send Accepted email // get grantor user to send Accepted email
let Some(grantor_user) = User::find_by_uuid(&emergency_access.grantor_uuid, &conn).await else { 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 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?; emergency_access.accept_invite(&grantee_user.uuid, &grantee_user.email, &conn).await?;
if CONFIG.mail_enabled() { 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(()) Ok(())
} else { } 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) = let Some(mut emergency_access) =
EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &confirming_user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &confirming_user.uuid, &conn).await
else { else {
err!("Emergency access not valid.") err!(crate::i18n::emergency_access_not_valid(&headers.locale))
}; };
if emergency_access.status != EmergencyAccessStatus::Accepted as i32 if emergency_access.status != EmergencyAccessStatus::Accepted as i32
|| emergency_access.grantor_uuid != confirming_user.uuid || 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 { 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() { if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() {
let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { 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.status = EmergencyAccessStatus::Confirmed as i32;
@ -437,11 +447,16 @@ async fn confirm_emergency_access(
emergency_access.save(&conn).await?; emergency_access.save(&conn).await?;
if CONFIG.mail_enabled() { 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())) Ok(Json(emergency_access.to_json()))
} else { } 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 EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &initiating_user.uuid, &conn).await
else { else {
err!( 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) format!("Emergency access '{emer_id}', not found for user '{}'.", initiating_user.email)
) )
}; };
if emergency_access.status != EmergencyAccessStatus::Confirmed as i32 { if emergency_access.status != EmergencyAccessStatus::Confirmed as i32 {
err!( 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) format!("Emergency access '{emer_id}', not confirmed for user '{}'.", initiating_user.email)
) )
} }
if !EMERGENCY_ACCESS_TIMEOUT_RANGE.contains(&emergency_access.wait_time_days) { if !EMERGENCY_ACCESS_TIMEOUT_RANGE.contains(&emergency_access.wait_time_days) {
err!( 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) 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 { 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(); 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?; emergency_access.save(&conn).await?;
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
mail::send_emergency_access_recovery_initiated( mail::send_emergency_access_recovery_initiated_for_locale(
&grantor_user.email, &grantor_user.email,
&initiating_user.name, &initiating_user.name,
emergency_access.get_type_as_str(), emergency_access.get_type_as_str(),
&emergency_access.wait_time_days, &emergency_access.wait_time_days,
grantor_user.locale.as_deref(),
) )
.await?; .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 EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await
else { else {
err!( 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) format!("Emergency access '{emer_id}', not found for user '{}'.", headers.user.email)
) )
}; };
if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32 { if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32 {
err!( 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) 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 { 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() { if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() {
let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { 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.status = EmergencyAccessStatus::RecoveryApproved as i32;
emergency_access.save(&conn).await?; emergency_access.save(&conn).await?;
if CONFIG.mail_enabled() { 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())) Ok(Json(emergency_access.to_json()))
} else { } 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) = let Some(mut emergency_access) =
EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantor_uuid(&emer_id, &headers.user.uuid, &conn).await
else { else {
err!("Emergency access not valid.") err!(crate::i18n::emergency_access_not_valid(&headers.locale))
}; };
if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32 if emergency_access.status != EmergencyAccessStatus::RecoveryInitiated as i32
&& emergency_access.status != EmergencyAccessStatus::RecoveryApproved 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() { if let Some(grantee_uuid) = emergency_access.grantee_uuid.as_ref() {
let Some(grantee_user) = User::find_by_uuid(grantee_uuid, &conn).await else { 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.status = EmergencyAccessStatus::Confirmed as i32;
emergency_access.save(&conn).await?; emergency_access.save(&conn).await?;
if CONFIG.mail_enabled() { 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())) Ok(Json(emergency_access.to_json()))
} else { } 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) = let Some(emergency_access) =
EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &headers.user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &headers.user.uuid, &conn).await
else { 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) { 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; 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) = let Some(emergency_access) =
EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await
else { 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) { 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 { 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!({ let result = json!({
@ -675,15 +701,15 @@ async fn password_emergency_access(
let Some(emergency_access) = let Some(emergency_access) =
EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await
else { 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) { 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 { 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) = let (new_master_password_hash, new_key) =
@ -691,14 +717,14 @@ async fn password_emergency_access(
authentication_data.check(&grantor_user, &unlock_data)?; authentication_data.check(&grantor_user, &unlock_data)?;
if !authentication_data.kdf.matches_user(&grantor_user) { 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) (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) { } else if let (Some(new_master_password_hash), Some(new_key)) = (data.new_master_password_hash, data.key) {
(new_master_password_hash, new_key) (new_master_password_hash, new_key)
} else { } else {
err!("Invalid request!") err!(crate::i18n::emergency_access_invalid_request(&headers.locale))
}; };
// change grantor_user password // change grantor_user password
@ -725,15 +751,15 @@ async fn policies_emergency_access(emer_id: EmergencyAccessId, headers: Headers,
let Some(emergency_access) = let Some(emergency_access) =
EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await EmergencyAccess::find_by_uuid_and_grantee_uuid(&emer_id, &requesting_user.uuid, &conn).await
else { 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) { 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 { 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); 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 { fn check_emergency_access_enabled() -> EmptyResult {
if !CONFIG.emergency_access_allowed() { if !CONFIG.emergency_access_allowed() {
err!("Emergency access is not enabled.") err!(crate::i18n::emergency_access_not_enabled(&CONFIG.default_locale()))
} }
Ok(()) Ok(())
} }
@ -820,17 +846,23 @@ pub async fn emergency_request_timeout_job(pool: DbPool) {
} }
if CONFIG.mail_enabled() { 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, &grantor_user.email,
&grantee_user.name, &grantee_user.name,
emer.get_type_as_str(), emer.get_type_as_str(),
grantor_user.locale.as_deref(),
) )
.await .await
{ {
error!("Failed to send emergency access recovery time-out email for '{}': {e}", emer.uuid); 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); 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() 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, &grantor_user.email,
&grantee_user.name, &grantee_user.name,
emer.get_type_as_str(), emer.get_type_as_str(),
"1", // This notification is only triggered one day before the activation "1", // This notification is only triggered one day before the activation
grantor_user.locale.as_deref(),
) )
.await .await
{ {

23
src/api/core/events.rs

@ -31,9 +31,10 @@ struct EventRange {
} }
impl EventRange { impl EventRange {
fn date_range(&self) -> ApiResult<(NaiveDateTime, NaiveDateTime)> { fn date_range(&self, locale: &str) -> ApiResult<(NaiveDateTime, NaiveDateTime)> {
let start_date = parse_date(&self.start).map_res("Invalid start date")?; 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("Invalid end date")?; 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)) 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 // Upstream: https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Controllers/EventsController.cs#L87
#[get("/organizations/<org_id>/events?<data..>")] #[get("/organizations/<org_id>/events?<data..>")]
async fn get_org_events(org_id: OrganizationId, data: EventRange, headers: AdminHeaders, conn: DbConn) -> JsonResult { 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 { 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. // Return an empty vec when we org events are disabled.
// This prevents client errors // This prevents client errors
let events_json: Vec<Value> = if CONFIG.org_events_enabled() { let events_json: Vec<Value> = 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) Event::find_by_organization_uuid(&org_id, &start_date, &end_date, &conn)
.await .await
@ -73,7 +76,7 @@ async fn get_cipher_events(cipher_id: CipherId, data: EventRange, headers: Heade
let events_json: Vec<Value> = if CONFIG.org_events_enabled() let events_json: Vec<Value> = if CONFIG.org_events_enabled()
&& Membership::user_has_ge_admin_access_to_cipher(&headers.user.uuid, &cipher_id, &conn).await && 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() Event::find_by_cipher_uuid(&cipher_id, &start_date, &end_date, &conn).await.iter().map(Event::to_json).collect()
} else { } else {
@ -95,13 +98,15 @@ async fn get_user_events(
headers: AdminHeaders, headers: AdminHeaders,
conn: DbConn, conn: DbConn,
) -> JsonResult { ) -> 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 { 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. // Return an empty vec when we org events are disabled.
// This prevents client errors // This prevents client errors
let events_json: Vec<Value> = if CONFIG.org_events_enabled() { let events_json: Vec<Value> = 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) Event::find_by_org_and_member(&org_id, &member_id, &start_date, &end_date, &conn)
.await .await
@ -162,7 +167,7 @@ async fn post_events_collect(data: Json<Vec<EventCollection>>, headers: Headers,
} }
for event in data.iter() { 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. // Only the event types upstream accepts from clients, the rest are written server-side.
match event.r#type { match event.r#type {
t if t == EventType::UserClientExportedVault as i32 => { t if t == EventType::UserClientExportedVault as i32 => {

6
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 { if let Some(folder) = Folder::find_by_uuid_and_user(&folder_id, &headers.user.uuid, &conn).await {
Ok(Json(folder.to_json())) Ok(Json(folder.to_json()))
} else { } 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 data: FolderData = data.into_inner();
let Some(mut folder) = Folder::find_by_uuid_and_user(&folder_id, &headers.user.uuid, &conn).await else { 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; folder.name = data.name;
@ -97,7 +97,7 @@ async fn delete_folder_post(folder_id: FolderId, headers: Headers, conn: DbConn,
#[delete("/folders/<folder_id>")] #[delete("/folders/<folder_id>")]
async fn delete_folder(folder_id: FolderId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { 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 { 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 // Delete the actual folder entry

18
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; pub use sends::purge_sends;
use reqwest::Method; 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::{ use crate::{
CONFIG, CONFIG,
@ -268,12 +268,14 @@ pub fn catchers() -> Vec<Catcher> {
} }
#[catch(404)] #[catch(404)]
fn api_not_found() -> Json<Value> { fn api_not_found(request: &Request<'_>) -> Json<Value> {
let locale =
crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale());
Json(json!({ Json(json!({
"error": { "error": {
"code": 404, "code": 404,
"reason": "Not Found", "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<String>, reset_password_key: Option<String>,
conn: &DbConn, conn: &DbConn,
) -> EmptyResult { ) -> 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 { 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; member.status = MembershipStatus::Accepted as i32;
@ -298,10 +302,12 @@ async fn accept_org_invite(
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
let Some(org) = Organization::find_by_uuid(&member.org_uuid, conn).await else { 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 // 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?; .await?;
} }

540
src/api/core/organizations.rs

File diff suppressed because it is too large

4
src/api/core/public.rs

@ -108,7 +108,7 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
let (org_name, org_email) = if let Some(org) = Organization::find_by_uuid(&org_id, &conn).await { let (org_name, org_email) = if let Some(org) = Organization::find_by_uuid(&org_id, &conn).await {
(org.name, org.billing_email) (org.name, org.billing_email)
} else { } 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())); 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<OrgImportData>, token: PublicToken, conn: DbConn
new_member.delete(&conn).await?; new_member.delete(&conn).await?;
} }
err!(format!("Error sending invite: {e:?} ")); err!(crate::i18n::org_error_sending_invite(&CONFIG.default_locale()), format!("{e:?}"));
} }
} }
} }

85
src/api/core/sends.rs

@ -103,7 +103,7 @@ async fn enforce_disable_send_policy(headers: &Headers, conn: &DbConn) -> EmptyR
if !CONFIG.sends_allowed() if !CONFIG.sends_allowed()
|| OrgPolicy::is_applicable_to_user(user_id, OrgPolicyType::DisableSend, None, conn).await || 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(()) Ok(())
} }
@ -118,10 +118,7 @@ async fn enforce_disable_hide_email_policy(data: &SendData, headers: &Headers, c
let user_id = &headers.user.uuid; let user_id = &headers.user.uuid;
let hide_email = data.hide_email.unwrap_or(false); let hide_email = data.hide_email.unwrap_or(false);
if hide_email && OrgPolicy::is_hide_email_disabled(user_id, conn).await { if hide_email && OrgPolicy::is_hide_email_disabled(user_id, conn).await {
err!( err!(crate::i18n::send_hide_email_policy_forbidden(&headers.locale))
"Due to an Enterprise Policy, you are not allowed to hide your email address \
from recipients when creating or editing a Send."
)
} }
Ok(()) Ok(())
} }
@ -132,24 +129,22 @@ fn create_send(data: SendData, user_id: UserId) -> ApiResult<Send> {
} else if data.r#type == SendType::File as i32 { } else if data.r#type == SendType::File as i32 {
data.file data.file
} else { } else {
err!("Invalid Send type") err!(crate::i18n::send_invalid_type(&CONFIG.default_locale()))
}; };
let data_str = if let Some(mut d) = data_val { let data_str = if let Some(mut d) = data_val {
d.as_object_mut().and_then(|o| o.remove("response")); d.as_object_mut().and_then(|o| o.remove("response"));
serde_json::to_string(&d)? serde_json::to_string(&d)?
} else { } 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() { if data.deletion_date > Utc::now() + TimeDelta::try_days(31).unwrap() {
err!( err!(crate::i18n::send_deletion_date_too_far(&CONFIG.default_locale()));
"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."
);
} }
if data.emails.is_some() { 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()); 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 { if let Some(send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await {
Ok(Json(send.to_json())) Ok(Json(send.to_json()))
} else { } 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<SendData>, headers: Headers, conn: DbConn, nt: Not
enforce_disable_hide_email_policy(&data, &headers, &conn).await?; enforce_disable_hide_email_policy(&data, &headers, &conn).await?;
if data.r#type == SendType::File as i32 { 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)?; let mut send = create_send(data, headers.user.uuid)?;
@ -228,7 +223,7 @@ async fn post_send_file_v2(data: Json<SendData>, headers: Headers, conn: DbConn)
let data = data.into_inner(); let data = data.into_inner();
if data.r#type != SendType::File as i32 { 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?; enforce_disable_hide_email_policy(&data, &headers, &conn).await?;
@ -236,23 +231,23 @@ async fn post_send_file_v2(data: Json<SendData>, headers: Headers, conn: DbConn)
let file_length = if let Some(m) = &data.file_length { let file_length = if let Some(m) = &data.file_length {
m.into_i64()? m.into_i64()?
} else { } else {
err!("Invalid send length") err!(crate::i18n::send_invalid_length(&headers.locale))
}; };
if file_length < 0 { 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() { 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) => { Some(limit_kb) => {
let Some(already_used) = Send::size_by_user(&headers.user.uuid, &conn).await else { 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 { 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 { 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) i64::clamp(left, 0, SIZE_525_MB)
} }
@ -260,7 +255,7 @@ async fn post_send_file_v2(data: Json<SendData>, headers: Headers, conn: DbConn)
}; };
if file_length > size_limit { 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)?; 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 data = data.into_inner();
let Some(send) = Send::find_by_uuid_and_user(&send_id, &headers.user.uuid, &conn).await else { 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 { 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::<SendFileData>(&send.data) else { let Ok(send_data) = serde_json::from_str::<SendFileData>(&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() { 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()) || (headers.device.is_cli() && send_data.fileName.ends_with(raw_file_name.dangerous_unsafe_unsanitized_raw().as_str())
) => {} ) => {}
Some(raw_file_name) => err!( Some(raw_file_name) => err!(
"Send file name does not match.", crate::i18n::send_file_name_mismatch(&headers.locale),
format!( format!(
"Expected file name '{}' got '{}'", "Expected file name '{}' got '{}'",
send_data.fileName.escape_debug(), send_data.fileName.escape_debug(),
raw_file_name.dangerous_unsafe_unsanitized_raw().as_str().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 { 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 { 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 { 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}"); 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 { fn check_send_file_id(send: &Send, file_id: &SendFileId) -> EmptyResult {
if send.atype != SendType::File as i32 { 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::<SendFileData>(&send.data) { match serde_json::from_str::<SendFileData>(&send.data) {
Ok(data) if &data.id == file_id => Ok(()), Ok(data) if &data.id == file_id => Ok(()),
@ -470,11 +474,14 @@ async fn put_send(send_id: SendId, data: Json<SendData>, headers: Headers, conn:
enforce_disable_hide_email_policy(&data, &headers, &conn).await?; 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 { 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() { 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?; 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, ut: UpdateType,
) -> EmptyResult { ) -> EmptyResult {
if send.user_uuid.as_ref() != Some(&headers.user.uuid) { 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 { 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() { if data.deletion_date > Utc::now() + TimeDelta::try_days(31).unwrap() {
err!( err!(crate::i18n::send_deletion_date_too_far(&headers.locale));
"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."
);
} }
// When updating a file Send, we receive nulls in the File field, as it's immutable, // 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")); d.as_object_mut().and_then(|d| d.remove("response"));
serde_json::to_string(&d)? serde_json::to_string(&d)?
} else { } else {
err!("Send data not provided"); err!(crate::i18n::send_data_not_provided(&headers.locale));
}; };
send.data = data_str; send.data = data_str;
} }
@ -543,7 +548,7 @@ async fn update_send_from_data(
#[delete("/sends/<send_id>")] #[delete("/sends/<send_id>")]
async fn delete_send(send_id: SendId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { 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 { 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?; 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?; 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 { 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); send.set_password(None);

10
src/api/core/two_factor/authenticator.rs

@ -62,11 +62,11 @@ async fn activate_authenticator(data: Json<EnableAuthenticatorData>, headers: He
let decoded_key: Vec<u8> = if let Ok(decoded) = BASE32.decode(key.as_bytes()) { let decoded_key: Vec<u8> = if let Ok(decoded) = BASE32.decode(key.as_bytes()) {
decoded decoded
} else { } else {
err!("Invalid totp secret") err!(crate::i18n::two_factor_invalid_totp_secret(&headers.locale))
}; };
if decoded_key.len() != 20 { 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 // Validate the token provided with the key, and save new twofactor
@ -97,7 +97,7 @@ pub async fn validate_totp_code_str(
conn: &DbConn, conn: &DbConn,
) -> EmptyResult { ) -> EmptyResult {
if !totp_code.chars().all(char::is_numeric) { 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 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}; use totp_lite::{Sha1, totp_custom};
let Ok(decoded_secret) = BASE32.decode(secret.as_bytes()) else { 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 { 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<DisableAuthenticatorData>, headers: He
twofactor.delete(&conn).await?; twofactor.delete(&conn).await?;
log_user_event(EventType::UserDisabled2fa, &user.uuid, headers.device.atype, &headers.ip.ip, &conn).await; log_user_event(EventType::UserDisabled2fa, &user.uuid, headers.device.atype, &headers.ip.ip, &conn).await;
} else { } 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());
} }
} }

7
src/api/core/two_factor/duo.rs

@ -2,6 +2,7 @@ use chrono::Utc;
use rocket::{Route, serde::json::Json}; use rocket::{Route, serde::json::Json};
use crate::{ use crate::{
CONFIG,
api::{ api::{
ApiResult, EmptyResult, JsonResult, PasswordOrOtpData, ApiResult, EmptyResult, JsonResult, PasswordOrOtpData,
core::log_user_event, core::log_user_event,
@ -114,7 +115,9 @@ async fn activate_duo(data: Json<EnableDuoData>, headers: Headers, conn: DbConn)
let (data, data_str) = if check_duo_fields_custom(&data) { let (data, data_str) = if check_duo_fields_custom(&data) {
let data_req: DuoData = data.into(); let data_req: DuoData = data.into();
let data_str = serde_json::to_string(&data_req)?; 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) (data_req.obscure(), data_str)
} else { } else {
(DuoData::secret(), String::new()) (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(), Some(u) => get_user_duo_data(&u.uuid, conn).await.data(),
_ => DuoData::global(), _ => 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)) Ok((data.ik, data.sk, data.host))
} }

54
src/api/core/two_factor/duo_oidc.rs

@ -140,7 +140,7 @@ impl DuoClient {
&EncodingKey::from_secret(self.client_secret.as_bytes()), &EncodingKey::from_secret(self.client_secret.as_bytes()),
) { ) {
Ok(token) => Ok(token), 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 .await
{ {
Ok(r) => r, 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::<HealthCheckResponse>().await { let response: HealthCheckResponse = match res.json::<HealthCheckResponse>().await {
Ok(r) => r, 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 { let health_stat: String = match response {
@ -183,11 +188,14 @@ impl DuoClient {
HealthCheckResponse::HealthFail { HealthCheckResponse::HealthFail {
message, message,
message_detail, 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" { 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(()) Ok(())
@ -217,7 +225,10 @@ impl DuoClient {
let authz_endpoint = format!("https://{}/oauth/v1/authorize", self.api_host); let authz_endpoint = format!("https://{}/oauth/v1/authorize", self.api_host);
let mut auth_url = match Url::parse(authz_endpoint.as_str()) { let mut auth_url = match Url::parse(authz_endpoint.as_str()) {
Ok(url) => url, 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, nonce: &str,
) -> Result<(), Error> { ) -> Result<(), Error> {
if duo_code.is_empty() { 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); let token_url = format!("https://{}/oauth/v1/token", self.api_host);
@ -271,17 +282,22 @@ impl DuoClient {
.await .await
{ {
Ok(r) => r, 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(); let status_code = res.status();
if status_code != StatusCode::OK { 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::<IdTokenResponse>().await { let response: IdTokenResponse = match res.json::<IdTokenResponse>().await {
Ok(r) => r, 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); let mut validation = Validation::new(DUO_RESP_SIGNATURE_ALG);
@ -295,14 +311,14 @@ impl DuoClient {
&validation, &validation,
) { ) {
Ok(c) => c, 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_nonces = crypto::ct_eq(nonce, &token_data.claims.nonce);
let matching_usernames = crypto::ct_eq(duo_username, &token_data.claims.preferred_username); let matching_usernames = crypto::ct_eq(duo_username, &token_data.claims.preferred_username);
if !(matching_nonces && matching_usernames) { 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(()) Ok(())
@ -357,13 +373,19 @@ fn make_callback_url(client_name: &str) -> Result<String, Error> {
// Get the location of this application as defined in the config. // Get the location of this application as defined in the config.
let base = match Url::parse(&format!("{}/", CONFIG.domain())) { let base = match Url::parse(&format!("{}/", CONFIG.domain())) {
Ok(url) => url, 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 // Add the client redirect bridge location
let mut callback = match base.join(DUO_REDIRECT_LOCATION) { let mut callback = match base.join(DUO_REDIRECT_LOCATION) {
Ok(url) => url, 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 // 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 { match TwoFactorDuoContext::save(state.as_str(), email, nonce.as_str(), CTX_VALIDITY_SECS, conn).await {
Ok(()) => client.make_authz_req_url(email, state, hash), 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:?}"))
}
} }
} }

63
src/api/core/two_factor/email.rs

@ -47,7 +47,7 @@ async fn send_email_login(data: Json<SendEmailLoginData>, client_headers: Client
let data: SendEmailLoginData = data.into_inner(); let data: SendEmailLoginData = data.into_inner();
if !CONFIG._enable_email_2fa() { if !CONFIG._enable_email_2fa() {
err!("Email 2FA is disabled") err!(crate::i18n::two_factor_email_disabled(&client_headers.locale))
} }
// Ratelimit the login // Ratelimit the login
@ -85,17 +85,23 @@ async fn send_email_login(data: Json<SendEmailLoginData>, client_headers: Client
} }
} else if let Some(auth_request_id) = auth_request_id { } else if let Some(auth_request_id) = auth_request_id {
let Some(auth_request) = AuthRequest::find_by_uuid(auth_request_id, &conn).await else { 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 { 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 if auth_request.device_type != client_headers.device_type
|| auth_request.request_ip != client_headers.ip.ip.to_string() || auth_request.request_ip != client_headers.ip.ip.to_string()
|| !auth_request.check_access_code(code) || !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 { } else if let Some(device_identifier) = &data.device_identifier {
// iOS/Android SSO logins send the email and device id but no password hash, // 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<SendEmailLoginData>, client_headers: Client
device_identifier.to_string().escape_debug() device_identifier.to_string().escape_debug()
); );
} else { } else {
err!("No password hash has been submitted.") err!(crate::i18n::two_factor_no_password_hash_submitted(&client_headers.locale))
} }
user user
} else { } else {
let Some(device_identifier) = &data.device_identifier 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 // 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 { 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<SendEmailLoginData>, client_headers: Client
user 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 /// 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 { pub async fn send_token(user_id: &UserId, conn: &DbConn, locale: Option<&str>) -> EmptyResult {
let mut twofactor = let default_locale = CONFIG.default_locale();
TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn).await.map_res("Two factor not found")?; 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()); 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.data = twofactor_data.to_json();
twofactor.save(conn).await?; 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(()) Ok(())
} }
@ -193,7 +207,7 @@ async fn send_email(data: Json<SendEmailData>, headers: Headers, conn: DbConn) -
two_factor::validate_email(&data.user_verification_token, &user.uuid, data.email.clone(), false)?; two_factor::validate_email(&data.user_verification_token, &user.uuid, data.email.clone(), false)?;
if !CONFIG._enable_email_2fa() { 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 { 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<SendEmailData>, headers: Headers, conn: DbConn) -
TwoFactor::new(user.uuid.clone(), TwoFactorType::EmailVerificationChallenge, twofactor_data.to_json()); TwoFactor::new(user.uuid.clone(), TwoFactorType::EmailVerificationChallenge, twofactor_data.to_json());
twofactor.save(&conn).await?; 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!({}))) Ok(Json(json!({})))
} }
@ -231,16 +250,16 @@ async fn email(data: Json<EmailData>, headers: Headers, conn: DbConn) -> JsonRes
let mut twofactor = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::EmailVerificationChallenge, &conn) let mut twofactor = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::EmailVerificationChallenge, &conn)
.await .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 mut email_data = EmailTokenData::from_json(&twofactor.data)?;
let Some(issued_token) = &email_data.last_token else { 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) { 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(); email_data.reset_token();
@ -281,8 +300,10 @@ pub async fn validate_email_code_str(
conn: &DbConn, conn: &DbConn,
) -> EmptyResult { ) -> EmptyResult {
let mut email_data = EmailTokenData::from_json(data)?; let mut email_data = EmailTokenData::from_json(data)?;
let mut twofactor = let locale = CONFIG.default_locale();
TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Email, conn).await.map_res("Two factor not found")?; 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 { let Some(issued_token) = &email_data.last_token else {
err!( err!(
format!("No token available! IP: {ip}"), format!("No token available! IP: {ip}"),
@ -373,14 +394,14 @@ impl EmailTokenData {
if let Ok(x) = res { if let Ok(x) = res {
Ok(x) Ok(x)
} else { } 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 { pub async fn activate_email_2fa(user: &User, conn: &DbConn) -> EmptyResult {
if user.verified_at.is_none() { 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 // The token is set when the first code is sent
let twofactor_data = EmailTokenData::new(user.email.clone(), None); 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 { if let Some(user) = User::find_by_uuid(user_id, conn).await {
activate_email_2fa(&user, conn).await activate_email_2fa(&user, conn).await
} else { } else {
err!("User not found!"); err!(crate::i18n::two_factor_user_not_found_exclam(&CONFIG.default_locale()));
} }
} }

7
src/api/core/two_factor/mod.rs

@ -144,7 +144,7 @@ pub async fn enforce_2fa_policy(
if member.atype < MembershipType::Admin { if member.atype < MembershipType::Admin {
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
let org = Organization::find_by_uuid(&member.org_uuid, conn).await.unwrap(); 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; let mut member = member;
member.revoke(); 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 member.atype < MembershipType::Admin && TwoFactor::find_by_user(&member.user_uuid, conn).await.is_empty() {
if CONFIG.mail_enabled() { if CONFIG.mail_enabled() {
let user = User::find_by_uuid(&member.user_uuid, conn).await.unwrap(); 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; let mut member = member;
member.revoke(); 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 {} did not complete a 2FA login within the configured time limit. IP: {}",
user.email, login.ip_address user.email, login.ip_address
); );
match mail::send_incomplete_2fa_login( match mail::send_incomplete_2fa_login_for_locale(
&user.email, &user.email,
&login.ip_address, &login.ip_address,
&login.login_time, &login.login_time,
&login.device_name, &login.device_name,
&DeviceType::from_i32(login.device_type).to_string(), &DeviceType::from_i32(login.device_type).to_string(),
user.locale.as_deref(),
) )
.await .await
{ {

18
src/api/core/two_factor/protected_actions.rs

@ -48,7 +48,7 @@ impl ProtectedActionData {
if let Ok(x) = res { if let Ok(x) = res {
Ok(x) Ok(x)
} else { } 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 elapsed = pa_data.time_since_sent().num_seconds();
let delay = 30; let delay = 30;
if elapsed < delay { 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?; 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()); let twofactor = TwoFactor::new(user.uuid, TwoFactorType::ProtectedActions, pa_data.to_json());
twofactor.save(&conn).await?; 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(()) Ok(())
} }
@ -124,22 +127,23 @@ pub async fn validate_protected_action_otp(
delete_if_valid: bool, delete_if_valid: bool,
conn: &DbConn, conn: &DbConn,
) -> EmptyResult { ) -> EmptyResult {
let locale = CONFIG.default_locale();
let mut pa = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::ProtectedActions, conn) let mut pa = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::ProtectedActions, conn)
.await .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)?; let mut pa_data = ProtectedActionData::from_json(&pa.data)?;
// Fail after x attempts if the token has been used too many times. // 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. // Don't delete it, as we use it to keep track of attempts.
if pa_data.attempts >= u64::from(CONFIG.email_attempts_limit()) { 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) // Check if the token has expired (Using the email 2fa expiration time)
let max_time = i64::from(CONFIG.email_expiration_time()); let max_time = i64::from(CONFIG.email_expiration_time());
if pa_data.time_since_sent().num_seconds() > max_time { if pa_data.time_since_sent().num_seconds() > max_time {
pa.delete(conn).await?; 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) { 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.data = pa_data.to_json();
pa.save(conn).await?; pa.save(conn).await?;
err!("Token is invalid") err!(crate::i18n::two_factor_token_invalid(&CONFIG.default_locale()))
} }
if delete_if_valid { if delete_if_valid {

12
src/api/core/two_factor/webauthn.rs

@ -119,7 +119,7 @@ impl WebauthnRegistration {
#[post("/two-factor/get-webauthn", data = "<data>")] #[post("/two-factor/get-webauthn", data = "<data>")]
async fn get_webauthn(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult { async fn get_webauthn(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult {
if !CONFIG.is_webauthn_2fa_supported() { 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(); let data: PasswordOrOtpData = data.into_inner();
@ -282,7 +282,7 @@ async fn activate_webauthn(data: Json<EnableWebauthnData>, headers: Headers, con
tf.delete(&conn).await?; tf.delete(&conn).await?;
state state
} else { } else {
err!("Can't recover challenge") err!(crate::i18n::two_factor_cannot_recover_challenge(&headers.locale))
}; };
// Verify the credentials with the saved state // Verify the credentials with the saved state
@ -344,7 +344,7 @@ async fn inner_delete_webauthns(
let user = headers.user; let user = headers.user;
let Some(mut tf) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Webauthn, conn).await else { 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<WebauthnRegistration> = serde_json::from_str(&tf.data)?; let mut keys: Vec<WebauthnRegistration> = serde_json::from_str(&tf.data)?;
@ -365,7 +365,7 @@ async fn inner_delete_webauthns(
}); });
if removed.is_empty() { if removed.is_empty() {
err!("Webauthn entry not found") err!(crate::i18n::two_factor_webauthn_entry_not_found(&headers.locale))
} }
if keys.is_empty() { 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 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 { 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::<Vec<U2FRegistration>>(&u2f.data) else { let Ok(mut data) = serde_json::from_str::<Vec<U2FRegistration>>(&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)); 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(); get_webauthn_registrations(user_id, conn).await?.1.into_iter().map(|r| r.credential).collect();
if creds.is_empty() { 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 // Generate a challenge based on the credentials

23
src/api/core/two_factor/yubikey.rs

@ -92,17 +92,18 @@ fn jsonify_yubikeys(yubikeys: Vec<String>) -> Value {
fn get_yubico_credentials() -> Result<(String, String), Error> { fn get_yubico_credentials() -> Result<(String, String), Error> {
if !CONFIG._enable_yubico() { 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()) { if let (Some(id), Some(secret)) = (CONFIG.yubico_client_id(), CONFIG.yubico_secret_key()) {
Ok((id, secret)) Ok((id, secret))
} else { } 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 { async fn verify_yubikey_otp(otp: String) -> EmptyResult {
let locale = CONFIG.default_locale();
let (yubico_id, yubico_secret) = get_yubico_credentials()?; let (yubico_id, yubico_secret) = get_yubico_credentials()?;
let mut config = Config::default().set_client_id(yubico_id).set_key(yubico_secret)?; 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 client = HttpClientTransport::new()?;
let verifier = Verifier::with_client(config, client)?; 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 = "<data>")] #[post("/two-factor/get-yubikey", data = "<data>")]
@ -154,7 +155,7 @@ async fn activate_yubikey(data: Json<EnableYubikeyData>, headers: Headers, conn:
if yubikeys.is_empty() { if yubikeys.is_empty() {
// Return an error to prevent saving empty keys which would cause users not being able to login anymore. // 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 // 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 // Check if we already have some data
@ -174,7 +175,9 @@ async fn activate_yubikey(data: Json<EnableYubikeyData>, headers: Headers, conn:
continue; 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<String> = yubikeys.into_iter().filter_map(|x| x.get(..12).map(str::to_owned)).collect(); let yubikey_ids: Vec<String> = yubikeys.into_iter().filter_map(|x| x.get(..12).map(str::to_owned)).collect();
@ -221,18 +224,20 @@ async fn delete_yubikeys(data: Json<VerificationTokenData>, headers: Headers, co
pub async fn validate_yubikey_login(response: &str, twofactor_data: &str) -> EmptyResult { pub async fn validate_yubikey_login(response: &str, twofactor_data: &str) -> EmptyResult {
if response.len() != 44 { 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 yubikey_metadata: YubikeyMetadata = serde_json::from_str(twofactor_data).expect("Can't parse Yubikey Metadata");
let Some(response_id) = response.get(..12) else { 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()) { 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(()) Ok(())
} }

187
src/api/identity.rs

@ -24,7 +24,7 @@ use crate::{
push::register_push_device, push::register_push_device,
}, },
auth, 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, crypto,
db::{ db::{
DbConn, DbConn,
@ -66,7 +66,9 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
check_is_some(data.refresh_token.as_ref(), "refresh_token cannot be blank")?; check_is_some(data.refresh_token.as_ref(), "refresh_token cannot be blank")?;
refresh_login(data, &conn, &client_header.ip).await 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" => { "password" => {
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?;
check_is_some(data.password.as_ref(), "password cannot be blank")?; check_is_some(data.password.as_ref(), "password cannot be blank")?;
@ -77,14 +79,14 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?; 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")?; 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" => { "client_credentials" => {
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; 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.client_secret.as_ref(), "client_secret cannot be blank")?;
check_is_some(data.scope.as_ref(), "scope 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() => { "authorization_code" if CONFIG.sso_enabled() => {
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?;
@ -97,7 +99,7 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
sso_login(data, &mut user_id, &conn, &client_header.ip).await 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" => { "send_access" => {
crate::ratelimit::check_limit_unauthenticated(&client_header.ip.ip)?; crate::ratelimit::check_limit_unauthenticated(&client_header.ip.ip)?;
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?; check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?;
@ -112,7 +114,7 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
.await?; .await?;
Ok(Json(tokens.to_json())) 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 { 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 // https://github.com/bitwarden/clients/blob/2ee158e720a5e7dbe3641caf80b569e97a1dd91b/libs/common/src/services/api.service.ts#L1786-L1797
let Some(refresh_token) = data.refresh_token else { 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<UserId>, conn: &DbCon
if user.email != user_infos.email { if user.email != user_infos.email {
if CONFIG.mail_enabled() { 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); 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<UserId>, conn: &DbCon
authenticated_response(&user, &mut device, auth_tokens, twofactor_token, conn, ip).await authenticated_response(&user, &mut device, auth_tokens, twofactor_token, conn, ip).await
} }
async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &DbConn, ip: &ClientIp) -> JsonResult { async fn password_login(
data: ConnectData,
user_id: &mut Option<UserId>,
conn: &DbConn,
ip: &ClientIp,
locale: &str,
) -> JsonResult {
// Validate scope // Validate scope
AuthMethod::Password.check_scope(data.scope.as_ref())?; AuthMethod::Password.check_scope(data.scope.as_ref())?;
@ -379,7 +387,10 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
let username = data.username.as_ref().unwrap().trim(); let username = data.username.as_ref().unwrap().trim();
let log_username = username.escape_debug(); let log_username = username.escape_debug();
let Some(mut user) = User::find_by_mail(username, conn).await else { 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. // 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<UserId>, conn: &
|| !auth_request.check_access_code(password) || !auth_request.check_access_code(password)
{ {
err!( 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), format!("IP: {}. Username: {log_username}.", ip.ip),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn, event: EventType::UserFailedLogIn,
@ -419,7 +430,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
} }
} else if !user.check_valid_password(password) { } else if !user.check_valid_password(password) {
err!( err!(
"Username or password is incorrect. Try again", crate::i18n::auth_invalid_username_or_password(locale),
format!("IP: {}. Username: {log_username}.", ip.ip), format!("IP: {}. Username: {log_username}.", ip.ip),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn, event: EventType::UserFailedLogIn,
@ -430,7 +441,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
// Check if the user is disabled // Check if the user is disabled
if !user.enabled { if !user.enabled {
err!( err!(
"This user has been disabled", crate::i18n::auth_user_disabled(locale),
format!("IP: {}. Username: {log_username}.", ip.ip), format!("IP: {}. Username: {log_username}.", ip.ip),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn event: EventType::UserFailedLogIn
@ -461,7 +472,10 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
error!("Error updating user: {e:#?}"); 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:#?}"); error!("Error auto-sending email verification email: {e:#?}");
} }
} }
@ -469,7 +483,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
// We still want the login to fail until they actually verified the email address // We still want the login to fail until they actually verified the email address
err!( err!(
"Please verify your email before trying again.", crate::i18n::auth_verify_email_before_login(locale),
format!("IP: {}. Username: {log_username}.", ip.ip), format!("IP: {}. Username: {log_username}.", ip.ip),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn event: EventType::UserFailedLogIn
@ -486,7 +500,7 @@ async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &
&& !AuthRequest::set_authentication_date(auth_request_id, conn).await? && !AuthRequest::set_authentication_date(auth_request_id, conn).await?
{ {
err!( 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), format!("IP: {}. Username: {log_username}.", ip.ip),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn, event: EventType::UserFailedLogIn,
@ -509,7 +523,15 @@ async fn authenticated_response(
) -> JsonResult { ) -> JsonResult {
if CONFIG.mail_enabled() && device.is_new() { if CONFIG.mail_enabled() && device.is_new() {
let now = Utc::now().naive_utc(); 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:#?}"); error!("Error sending new device email: {e:#?}");
if CONFIG.require_device_email() { if CONFIG.require_device_email() {
@ -598,7 +620,13 @@ async fn authenticated_response(
Ok(Json(result)) Ok(Json(result))
} }
async fn api_key_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &DbConn, ip: &ClientIp) -> JsonResult { async fn api_key_login(
data: ConnectData,
user_id: &mut Option<UserId>,
conn: &DbConn,
ip: &ClientIp,
locale: &str,
) -> JsonResult {
// Ratelimit the login // Ratelimit the login
crate::ratelimit::check_limit_login(&ip.ip)?; crate::ratelimit::check_limit_login(&ip.ip)?;
@ -610,10 +638,12 @@ async fn api_key_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &D
check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?; 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")?; 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, Some(scope) if scope == &AuthMethod::OrgApiKey.scope() => {
_ => err!("Scope not supported"), 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<UserId>, user_id: &mut Option<UserId>,
conn: &DbConn, conn: &DbConn,
ip: &ClientIp, ip: &ClientIp,
locale: &str,
) -> JsonResult { ) -> JsonResult {
// Get the user via the client_id // Get the user via the client_id
let client_id = data.client_id.as_ref().unwrap(); let client_id = data.client_id.as_ref().unwrap();
let Some(client_user_id) = client_id.strip_prefix("user.") else { 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 client_user_id: UserId = client_user_id.into();
let Some(user) = User::find_by_uuid(&client_user_id, conn).await else { let Some(mut user) = User::find_by_uuid(&client_user_id, conn).await else {
err!("Invalid client_id", format!("IP: {}.", ip.ip)) 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. // 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(); let client_secret = data.client_secret.as_ref().unwrap();
if !user.check_valid_api_key(client_secret) { if !user.check_valid_api_key(client_secret) {
err!( err!(
"Incorrect client_secret", crate::i18n::auth_incorrect_client_secret(locale),
format!("IP: {}. Username: {}.", ip.ip, user.email), format!("IP: {}. Username: {}.", ip.ip, user.email),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn 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?; let mut device = get_device(&data, conn, &user).await?;
if CONFIG.mail_enabled() && device.is_new() { if CONFIG.mail_enabled() && device.is_new() {
let now = Utc::now().naive_utc(); 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:#?}"); error!("Error sending new device email: {e:#?}");
if CONFIG.require_device_email() { if CONFIG.require_device_email() {
@ -748,21 +795,24 @@ async fn user_api_key_login(
Ok(Json(result)) 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 // Get the org via the client_id
let client_id = data.client_id.as_ref().unwrap(); let client_id = data.client_id.as_ref().unwrap();
let Some(org_id) = client_id.strip_prefix("organization.") else { 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 org_id: OrganizationId = org_id.to_owned().into();
let Some(org_api_key) = OrganizationApiKey::find_by_org_uuid(&org_id, conn).await else { 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. // Check API key.
let client_secret = data.client_secret.as_ref().unwrap(); let client_secret = data.client_secret.as_ref().unwrap();
if !org_api_key.check_valid_api_key(client_secret) { 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); 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) (tf.enabled && is_twofactor_provider_usable(&provider_type, Some(&tf.data))).then_some(tf.atype)
}) })
.collect(); .collect();
let default_locale = CONFIG.default_locale();
let locale = user.locale.as_deref().unwrap_or(default_locale.as_str());
if twofactor_ids.is_empty() { 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 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) if ![TwoFactorType::Remember as i32, TwoFactorType::RecoveryCode as i32].contains(&selected_id)
&& !twofactor_ids.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 // 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 { 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_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) { match TwoFactorType::from_i32(selected_id) {
Some(TwoFactorType::Authenticator) => { Some(TwoFactorType::Authenticator) => {
@ -887,7 +945,7 @@ async fn twofactor_auth(
let recovery_code = twofactor_code.replace(' ', "").trim().to_lowercase(); let recovery_code = twofactor_code.replace(' ', "").trim().to_lowercase();
if !user.check_valid_recovery_code(&recovery_code) { if !user.check_valid_recovery_code(&recovery_code) {
err!( err!(
"Two-step token is invalid. Try again.", crate::i18n::auth_two_step_token_invalid(locale),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn2fa event: EventType::UserFailedLogIn2fa
} }
@ -907,8 +965,13 @@ async fn twofactor_auth(
log_user_event(EventType::UserRecovered2fa, &user.uuid, device.atype, &ip.ip, conn).await; log_user_event(EventType::UserRecovered2fa, &user.uuid, device.atype, &ip.ip, conn).await;
if CONFIG.mail_enabled() if CONFIG.mail_enabled()
&& let Err(e) = && let Err(e) = mail::send_recover_twofactor_for_locale(
mail::send_recover_twofactor(&user.email, &ip.ip.to_string(), &Utc::now().naive_utc()).await &user.email,
&ip.ip.to_string(),
&Utc::now().naive_utc(),
user.locale.as_deref(),
)
.await
{ {
error!("Error sending two-step login recovered email: {e:#?}"); error!("Error sending two-step login recovered email: {e:#?}");
} }
@ -918,7 +981,7 @@ async fn twofactor_auth(
user.save(conn).await?; user.save(conn).await?;
} }
_ => err!( _ => err!(
"Invalid two factor provider", crate::i18n::auth_invalid_twofactor_provider(locale),
ErrorEvent { ErrorEvent {
event: EventType::UserFailedLogIn2fa event: EventType::UserFailedLogIn2fa
} }
@ -936,8 +999,8 @@ async fn twofactor_auth(
Ok(two_factor) Ok(two_factor)
} }
fn selected_data(tf: Option<TwoFactor>) -> ApiResult<String> { fn selected_data(tf: Option<TwoFactor>, locale: &str) -> ApiResult<String> {
tf.map(|t| t.data).map_res("Two factor doesn't exist") 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<Value> { async fn json_err_twofactor(providers: &[i32], user: &User, data: &ConnectData, conn: &DbConn) -> ApiResult<Value> {
@ -975,7 +1038,9 @@ async fn json_err_twofactor(providers: &[i32], user: &User, data: &ConnectData,
Some(tf_type @ TwoFactorType::YubiKey) => { Some(tf_type @ TwoFactorType::YubiKey) => {
let Some(twofactor) = TwoFactor::find_by_user_and_type(user_id, tf_type, conn).await else { 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)?; 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) => { Some(tf_type @ TwoFactorType::Email) => {
let Some(twofactor) = TwoFactor::find_by_user_and_type(user_id, tf_type, conn).await else { 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)?; 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( async fn register_verification_email(
data: Json<RegisterVerificationData>, data: Json<RegisterVerificationData>,
accept: Option<&Accept>, accept: Option<&Accept>,
locale: RequestLocale,
ip: ClientIp, ip: ClientIp,
conn: DbConn, conn: DbConn,
) -> ApiResult<RegisterVerificationResponse> { ) -> ApiResult<RegisterVerificationResponse> {
@ -1070,7 +1138,7 @@ async fn register_verification_email(
if !(CONFIG.is_signup_allowed(&data.email) if !(CONFIG.is_signup_allowed(&data.email)
|| (!CONFIG.mail_enabled() && Invitation::find_by_mail(&data.email, &conn).await.is_some())) || (!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(); 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); let sleep_ms: u64 = rng.random_range(900..=1100);
tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await; tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await;
} else { } 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(())) Ok(RegisterVerificationResponse::NoContent(()))
@ -1124,9 +1192,9 @@ async fn register_verification_email_clicked(
} }
#[post("/accounts/register/finish", data = "<data>")] #[post("/accounts/register/finish", data = "<data>")]
async fn register_finish(data: Json<RegisterData>, ip: ClientIp, conn: DbConn) -> JsonResult { async fn register_finish(data: Json<RegisterData>, locale: RequestLocale, ip: ClientIp, conn: DbConn) -> JsonResult {
crate::ratelimit::check_limit_unauthenticated(&ip.ip)?; 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 // https://github.com/bitwarden/jslib/blob/master/common/src/models/request/tokenRequest.ts
@ -1201,14 +1269,15 @@ fn check_is_some<T>(value: Option<&T>, msg: &str) -> EmptyResult {
} }
#[get("/sso/prevalidate")] #[get("/sso/prevalidate")]
fn prevalidate() -> JsonResult { #[allow(clippy::needless_pass_by_value)]
fn prevalidate(locale: RequestLocale) -> JsonResult {
if CONFIG.sso_enabled() { if CONFIG.sso_enabled() {
let sso_token = sso::encode_ssotoken_claims(); let sso_token = sso::encode_ssotoken_claims();
Ok(Json(json!({ Ok(Json(json!({
"token": sso_token, "token": sso_token,
}))) })))
} else { } 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 state = sso::decode_state(&base64_state)?;
let Some(mut sso_auth) = SsoAuth::find(&state, conn).await else { 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 // 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())); 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()) { match (sso_auth.binding_hash.as_deref(), provided_hash.as_deref()) {
(Some(expected), Some(actual)) if crypto::ct_eq(expected, actual) => {} (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 cookies
.remove(Cookie::build(SSO_BINDING_COOKIE).path(format!("{}/identity/connect/", CONFIG.domain_path())).build()); .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) { let mut url = match url::Url::parse(&sso_auth.redirect_uri) {
Ok(url) => url, 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() url.query_pairs_mut()
@ -1317,7 +1392,13 @@ struct AuthorizeData {
// The `redirect_uri` will change depending of the client (web, android, ios ..) // The `redirect_uri` will change depending of the client (web, android, ios ..)
#[get("/connect/authorize?<data..>")] #[get("/connect/authorize?<data..>")]
async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure, conn: DbConn) -> ApiResult<Redirect> { async fn authorize(
data: AuthorizeData,
cookies: &CookieJar<'_>,
secure: Secure,
locale: RequestLocale,
conn: DbConn,
) -> ApiResult<Redirect> {
let AuthorizeData { let AuthorizeData {
client_id, client_id,
redirect_uri, redirect_uri,
@ -1328,7 +1409,7 @@ async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure,
} = data; } = data;
if code_challenge_method != "S256" { 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. // Generate browser-binding token. Stored hashed in DB; raw value handed to the browser as a cookie.

4
src/api/mod.rs

@ -64,13 +64,13 @@ impl PasswordOrOtpData {
match (self.master_password_hash.as_deref(), self.otp.as_deref()) { match (self.master_password_hash.as_deref(), self.otp.as_deref()) {
(Some(pw_hash), None) => { (Some(pw_hash), None) => {
if !user.check_valid_password(pw_hash) { if !user.check_valid_password(pw_hash) {
err!("Invalid password"); err!(crate::i18n::auth_invalid_password(&CONFIG.default_locale()));
} }
} }
(None, Some(otp)) => { (None, Some(otp)) => {
validate_protected_action_otp(otp, &user.uuid, delete_if_valid, conn).await?; 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(()) Ok(())
} }

11
src/api/push.rs

@ -65,12 +65,12 @@ async fn get_auth_api_token() -> ApiResult<String> {
.await .await
{ {
Ok(r) => r, 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::<AuthPushToken>().await { let json_pushtoken = match res.json::<AuthPushToken>().await {
Ok(r) => r, 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; 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? .await?
.error_for_status() .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 { 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(()) Ok(())
@ -155,9 +155,8 @@ pub async fn unregister_push_device(push_id: Option<&PushId>) -> EmptyResult {
.await? .await?
.error_for_status() .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(()) Ok(())
} }

91
src/api/web.rs

@ -4,10 +4,12 @@ use std::{
sync::{Arc, LazyLock, RwLock}, sync::{Arc, LazyLock, RwLock},
}; };
use include_dir::{Dir, include_dir};
use rocket::{ use rocket::{
Catcher, Route, Catcher, Route,
fs::NamedFile, fs::NamedFile,
http::ContentType, http::ContentType,
request::Request,
response::{Redirect, content::RawHtml as Html}, response::{Redirect, content::RawHtml as Html},
serde::json::Json, serde::json::Json,
}; };
@ -29,7 +31,7 @@ use crate::{
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
// If adding more routes here, consider also adding them to // If adding more routes here, consider also adding them to
// crate::utils::LOGGED_ROUTES to make sure they appear in the log // 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() { if CONFIG.web_vault_enabled() {
routes.append(&mut routes![ routes.append(&mut routes![
web_index, web_index,
@ -44,7 +46,7 @@ pub fn routes() -> Vec<Route> {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
if CONFIG.reload_templates() { if CONFIG.reload_templates() {
routes.append(&mut routes![static_files_dev]); routes.append(&mut routes![static_files_dev, static_locale_files_dev]);
} }
routes routes
@ -58,13 +60,28 @@ pub fn catchers() -> Vec<Catcher> {
} }
} }
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)] #[catch(404)]
fn not_found() -> ApiResult<Html<String>> { fn not_found(request: &Request<'_>) -> ApiResult<Html<String>> {
let locale =
crate::i18n::resolve_locale(None, request.headers().get_one("Accept-Language"), &CONFIG.default_locale());
// Return the page // Return the page
let json = json!({ 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)) Ok(Html(text))
} }
@ -277,12 +294,29 @@ pub async fn static_files_dev(filename: PathBuf) -> Option<NamedFile> {
None None
} }
#[cfg(debug_assertions)]
#[get("/vw_static/locales/<locale>/<filename>", rank = 1)]
pub async fn static_locale_files_dev(locale: &str, filename: PathBuf) -> Option<NamedFile> {
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 struct StaticFile {
pub content_type: ContentType, pub content_type: ContentType,
pub bytes: &'static [u8], pub bytes: &'static [u8],
pub etag: String, pub etag: String,
} }
static BUILTIN_LOCALES_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/static/locales");
pub static STATIC_FILES: LazyLock<HashMap<&'static str, StaticFile>> = LazyLock::new(|| { pub static STATIC_FILES: LazyLock<HashMap<&'static str, StaticFile>> = LazyLock::new(|| {
[ [
("404.png", ContentType::PNG, &include_bytes!("../static/images/404.png")[..]), ("404.png", ContentType::PNG, &include_bytes!("../static/images/404.png")[..]),
@ -295,6 +329,11 @@ pub static STATIC_FILES: LazyLock<HashMap<&'static str, StaticFile>> = LazyLock:
("404.css", ContentType::CSS, &include_bytes!("../static/scripts/404.css")[..]), ("404.css", ContentType::CSS, &include_bytes!("../static/scripts/404.css")[..]),
("admin.css", ContentType::CSS, &include_bytes!("../static/scripts/admin.css")[..]), ("admin.css", ContentType::CSS, &include_bytes!("../static/scripts/admin.css")[..]),
("admin.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin.js")[..]), ("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_settings.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin_settings.js")[..]),
("admin_users.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin_users.js")[..]), ("admin_users.js", ContentType::JavaScript, &include_bytes!("../static/scripts/admin_users.js")[..]),
( (
@ -327,11 +366,51 @@ pub static STATIC_FILES: LazyLock<HashMap<&'static str, StaticFile>> = LazyLock:
.collect() .collect()
}); });
pub static STATIC_LOCALE_FILES: LazyLock<HashMap<String, StaticFile>> = LazyLock::new(|| {
let mut files = HashMap::new();
let mut locale_dirs = BUILTIN_LOCALES_DIR.dirs().collect::<Vec<_>>();
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/<filename>", rank = 2)] #[get("/vw_static/<filename>", rank = 2)]
pub fn static_files(filename: &str) -> Result<EtagCached<&'static [u8]>, Error> { pub fn static_files(filename: &str) -> Result<EtagCached<&'static [u8]>, Error> {
if let Some(file) = STATIC_FILES.get(filename) { if let Some(file) = STATIC_FILES.get(filename) {
Ok(EtagCached::new(file.bytes, file.content_type.clone(), &file.etag)) Ok(EtagCached::new(file.bytes, file.content_type.clone(), &file.etag))
} else { } else {
err!(format!("Static file not found: {filename}")) err!(crate::i18n::api_static_file_not_found(&CONFIG.default_locale()), filename)
}
}
#[get("/vw_static/locales/<locale>/<filename>", rank = 2)]
pub fn static_locale_files(locale: &str, filename: &str) -> Result<EtagCached<&'static [u8]>, 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)
} }
} }

89
src/auth.rs

@ -99,16 +99,16 @@ pub async fn initialize_keys() -> Result<(), Error> {
let enc = EncodingKey::from_rsa_pem(&priv_key_buffer)?; let enc = EncodingKey::from_rsa_pem(&priv_key_buffer)?;
let dec: DecodingKey = DecodingKey::from_rsa_pem(&pub_key_buffer)?; let dec: DecodingKey = DecodingKey::from_rsa_pem(&pub_key_buffer)?;
if PRIVATE_RSA_KEY.set(enc).is_err() { 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() { 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 // 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"); 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() { 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(()) Ok(())
} }
@ -138,10 +138,10 @@ pub fn decode_jwt<T: DeserializeOwned>(token: &str, issuer: String) -> Result<T,
match jsonwebtoken::decode(&token, PUBLIC_RSA_KEY.wait(), &validation) { match jsonwebtoken::decode(&token, PUBLIC_RSA_KEY.wait(), &validation) {
Ok(d) => Ok(d.claims), Ok(d) => Ok(d.claims),
Err(err) => match *err.kind() { Err(err) => match *err.kind() {
ErrorKind::InvalidToken => err!("Token is invalid"), ErrorKind::InvalidToken => err!(crate::i18n::auth_token_invalid(&CONFIG.default_locale())),
ErrorKind::InvalidIssuer => err!("Issuer is invalid"), ErrorKind::InvalidIssuer => err!(crate::i18n::auth_issuer_invalid(&CONFIG.default_locale())),
ErrorKind::ExpiredSignature => err!("Token has expired"), ErrorKind::ExpiredSignature => err!(crate::i18n::auth_token_expired(&CONFIG.default_locale())),
_ => err!(format!("Error decoding JWT: {:?}", err)), _ => 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<Utc>) -> Result<DateTime<Utc>, Error> { fn calculate_invite_expire_hours(now: &DateTime<Utc>) -> Result<DateTime<Utc>, Error> {
let expire_hours = i64::from(CONFIG.invitation_expiration_hours()); let expire_hours = i64::from(CONFIG.invitation_expiration_hours());
let Some(hours_delta) = TimeDelta::try_hours(expire_hours) else { 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 { 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) Ok(exp)
} }
@ -562,10 +562,10 @@ pub fn generate_admin_claims() -> Result<BasicJwtClaims, Error> {
let time_now = Utc::now(); let time_now = Utc::now();
let lifetime_minutes = i64::from(CONFIG.admin_session_lifetime()); let lifetime_minutes = i64::from(CONFIG.admin_session_lifetime());
let Some(minutes_delta) = TimeDelta::try_minutes(lifetime_minutes) else { 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 { 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 { Ok(BasicJwtClaims {
nbf: time_now.timestamp(), nbf: time_now.timestamp(),
@ -632,6 +632,26 @@ impl<'r> FromRequest<'r> for Host {
pub struct ClientHeaders { pub struct ClientHeaders {
pub device_type: i32, pub device_type: i32,
pub ip: ClientIp, 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<Self, Self::Error> {
Outcome::Success(RequestLocale {
locale: crate::i18n::resolve_locale(
None,
request.headers().get_one("Accept-Language"),
&CONFIG.default_locale(),
),
})
}
} }
#[rocket::async_trait] #[rocket::async_trait]
@ -648,10 +668,13 @@ impl<'r> FromRequest<'r> for ClientHeaders {
.get_one("device-type") .get_one("device-type")
.and_then(|d| d.parse().ok()) .and_then(|d| d.parse().ok())
.unwrap_or(DeviceType::UnknownBrowser as i32); .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 { Outcome::Success(ClientHeaders {
device_type, device_type,
ip, ip,
locale,
}) })
} }
} }
@ -661,6 +684,7 @@ pub struct Headers {
pub device: Device, pub device: Device,
pub user: User, pub user: User,
pub ip: ClientIp, pub ip: ClientIp,
pub locale: String,
} }
#[rocket::async_trait] #[rocket::async_trait]
@ -706,6 +730,9 @@ impl<'r> FromRequest<'r> for Headers {
err_handler!("Device has no user associated") 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 user.security_stamp != claims.sstamp {
if let Some(stamp_exception) = if let Some(stamp_exception) =
user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok()) user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok())
@ -741,6 +768,7 @@ impl<'r> FromRequest<'r> for Headers {
device, device,
user, user,
ip, ip,
locale,
}) })
} }
} }
@ -953,11 +981,13 @@ impl<'r> FromRequest<'r> for ManagerHeaders {
impl From<ManagerHeaders> for Headers { impl From<ManagerHeaders> for Headers {
fn from(h: ManagerHeaders) -> Headers { fn from(h: ManagerHeaders) -> Headers {
let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale());
Headers { Headers {
host: h.host, host: h.host,
device: h.device, device: h.device,
user: h.user, user: h.user,
ip: h.ip, ip: h.ip,
locale,
} }
} }
} }
@ -994,11 +1024,13 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose {
impl From<ManagerHeadersLoose> for Headers { impl From<ManagerHeadersLoose> for Headers {
fn from(h: ManagerHeadersLoose) -> Headers { fn from(h: ManagerHeadersLoose) -> Headers {
let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale());
Headers { Headers {
host: h.host, host: h.host,
device: h.device, device: h.device,
user: h.user, user: h.user,
ip: h.ip, ip: h.ip,
locale,
} }
} }
} }
@ -1011,10 +1043,19 @@ impl ManagerHeaders {
) -> Result<ManagerHeaders, Error> { ) -> Result<ManagerHeaders, Error> {
for col_id in collections { for col_id in collections {
if uuid::Uuid::parse_str(col_id.as_ref()).is_err() { 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 { 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<OrgMemberHeaders> for Headers { impl From<OrgMemberHeaders> for Headers {
fn from(h: OrgMemberHeaders) -> Headers { fn from(h: OrgMemberHeaders) -> Headers {
let locale = crate::i18n::resolve_locale(h.user.locale.as_deref(), None, &CONFIG.default_locale());
Headers { Headers {
host: h.host, host: h.host,
device: h.device, device: h.device,
user: h.user, user: h.user,
ip: h.ip, ip: h.ip,
locale,
} }
} }
} }
@ -1281,9 +1324,11 @@ impl AuthMethod {
pub fn check_scope(&self, scope: Option<&String>) -> ApiResult<String> { pub fn check_scope(&self, scope: Option<&String>) -> ApiResult<String> {
let method_scope = self.scope(); let method_scope = self.scope();
match 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) 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) { let refresh_claims = match decode_refresh(refresh_token) {
Err(err) => { Err(err) => {
error!("Failed to decode refresh_token from {}: {err:?}", ip.ip); 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, Ok(claims) => claims,
}; };
// Get device by refresh token // Get device by refresh token
let Some(mut device) = Device::find_by_refresh_token(&refresh_claims.device_token, conn).await else { 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`. // Save to update `updated_at`.
device.save(true, conn).await?; device.save(true, conn).await?;
let Some(user) = User::find_by_uuid(&device.user_uuid, conn).await else { 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 { let auth_tokens = match refresh_claims.sub {
@ -1394,10 +1439,12 @@ pub async fn refresh_tokens(
AuthMethod::Sso if CONFIG.sso_enabled() => { AuthMethod::Sso if CONFIG.sso_enabled() => {
sso::exchange_refresh_token(&device, &user, client_id, refresh_claims).await? 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::Sso => err!(crate::i18n::auth_sso_now_disabled_login_password(&CONFIG.default_locale())),
AuthMethod::Password if CONFIG.sso_enabled() && CONFIG.sso_only() => err!("SSO is now required, Login again"), 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), 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)) Ok((device, auth_tokens))

18
src/auth/two_factor.rs

@ -126,14 +126,16 @@ fn validate<T: DeserializeOwned>(token: &str, user_id: &UserId, enabled: bool) -
match decode_jwt::<TwoFactorClaims<T>>(token, JWT_2FA_AUTH_ISSUER.to_string()) { match decode_jwt::<TwoFactorClaims<T>>(token, JWT_2FA_AUTH_ISSUER.to_string()) {
Ok(claims) => { Ok(claims) => {
if claims.sub != *user_id { 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 { 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) 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 { pub fn validate_authenticator(token: &str, user_id: &UserId, key: &str, enabled: bool) -> EmptyResult {
let claims = validate::<AuthenticatorClaims>(token, user_id, enabled)?; let claims = validate::<AuthenticatorClaims>(token, user_id, enabled)?;
if claims.key != key { if claims.key != key {
err!("Invalid verification token: Invalid key"); err!(crate::i18n::two_factor_invalid_verification_token_invalid_key(&CONFIG.default_locale()));
} }
Ok(()) Ok(())
} }
@ -169,7 +171,7 @@ pub fn duo_token(user_id: UserId, data: Option<DuoData>, enabled: bool) -> Strin
pub fn validate_duo(token: &str, user_id: &UserId, data: Option<&DuoData>, enabled: bool) -> EmptyResult { pub fn validate_duo(token: &str, user_id: &UserId, data: Option<&DuoData>, enabled: bool) -> EmptyResult {
let claims = validate::<DuoClaims>(token, user_id, enabled)?; let claims = validate::<DuoClaims>(token, user_id, enabled)?;
if enabled && claims.data.as_ref() != data { 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(()) Ok(())
} }
@ -188,7 +190,7 @@ pub fn email_token(user_id: UserId, email: Option<String>, enabled: bool) -> Str
pub fn validate_email(token: &str, user_id: &UserId, email: String, enabled: bool) -> EmptyResult { pub fn validate_email(token: &str, user_id: &UserId, email: String, enabled: bool) -> EmptyResult {
let claims = validate::<EmailClaims>(token, user_id, enabled)?; let claims = validate::<EmailClaims>(token, user_id, enabled)?;
if enabled && claims.email != Some(email) { 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(()) Ok(())
} }
@ -206,7 +208,7 @@ pub fn webauthn_token(user_id: UserId, keys: Vec<i32>, enabled: bool) -> String
pub fn validate_webauthn(token: &str, user_id: &UserId, keys: &[i32], enabled: bool) -> EmptyResult { pub fn validate_webauthn(token: &str, user_id: &UserId, keys: &[i32], enabled: bool) -> EmptyResult {
let claims = validate::<WebauthnClaims>(token, user_id, enabled)?; let claims = validate::<WebauthnClaims>(token, user_id, enabled)?;
if keys != claims.keys { if keys != claims.keys {
err!("Invalid verification token: Invalid keys"); err!(crate::i18n::two_factor_invalid_verification_token_invalid_keys(&CONFIG.default_locale()));
} }
Ok(()) Ok(())
} }
@ -224,7 +226,7 @@ pub fn yubikey_token(user_id: UserId, keys: Vec<String>, enabled: bool) -> Strin
pub fn validate_yubikey(token: &str, user_id: &UserId, keys: &Vec<String>, enabled: bool) -> EmptyResult { pub fn validate_yubikey(token: &str, user_id: &UserId, keys: &Vec<String>, enabled: bool) -> EmptyResult {
let claims = validate::<YubikeyClaims>(token, user_id, enabled)?; let claims = validate::<YubikeyClaims>(token, user_id, enabled)?;
if *keys != claims.keys { if *keys != claims.keys {
err!("Invalid verification token: Invalid keys"); err!(crate::i18n::two_factor_invalid_verification_token_invalid_keys(&CONFIG.default_locale()));
} }
Ok(()) Ok(())
} }

196
src/config.rs

@ -396,7 +396,7 @@ macro_rules! make_config {
GroupData { GroupData {
group: stringify!($group), group: stringify!($group),
grouptoggle: stringify!($($group_enabled)?), grouptoggle: stringify!($($group_enabled)?),
groupdoc: (make_config! { @show $($groupdoc)? }), groupdoc: (make_config! { @show $($groupdoc)? }).trim(),
elements: vec![ elements: vec![
$( // This repetition is for each element within a group $( // 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]://' /// 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 /// 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(); 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 |> Indicates if the domain is set by the admin. Otherwise the default will be used.
domain_set: bool, false, def, false; domain_set: bool, false, def, false;
/// Domain origin |> Domain URL origin (in https://example.com:8443/path, https://example.com:8443 is the origin) /// 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> { 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 // Validate connection URL is valid and DB feature is enabled
#[cfg(sqlite)] #[cfg(sqlite)]
{ {
@ -969,10 +973,7 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
if let Some(parent) = path.parent() if let Some(parent) = path.parent()
&& !parent.is_dir() && !parent.is_dir()
{ {
err!(format!( err!(crate::i18n::config_sqlite_database_directory_invalid(locale), parent.display().to_string());
"SQLite database directory `{}` does not exist or is not a directory",
parent.display()
));
} }
} }
} }
@ -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") { 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()) { for entry in trusted_proxies.split(',').filter(|e| !e.trim().is_empty()) {
if crate::auth::parse_trusted_proxy(entry).is_none() { if crate::auth::parse_trusted_proxy(entry).is_none() {
err!(format!( err!(crate::i18n::config_ip_header_trusted_proxies_invalid_entry(locale), entry.trim());
"Invalid IP_HEADER_TRUSTED_PROXIES entry `{}`, expected an IP or CIDR range",
entry.trim()
));
} }
} }
} }
if cfg.password_iterations < 100_000 { 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; let limit = 256;
if cfg.database_max_conns < 1 || cfg.database_max_conns > limit { 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 { 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 { 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 { 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 { 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 if let Some(log_file) = &cfg.log_file
&& std::fs::OpenOptions::new().append(true).create(true).open(log_file).is_err() && 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(); 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; let whitelist = &cfg.signups_domains_whitelist;
if !whitelist.is_empty() && whitelist.split(',').any(|d| d.trim().is_empty()) { 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(); 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") if !(org_creation_users.is_empty() || org_creation_users == "all" || org_creation_users == "none")
&& org_creation_users.split(',').any(|u| !u.contains('@')) && 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 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 { if cfg.push_enabled {
let push_relay_uri = cfg.push_relay_uri.to_lowercase(); let push_relay_uri = cfg.push_relay_uri.to_lowercase();
if !push_relay_uri.starts_with("https://") { 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() { 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(); let push_identity_uri = cfg.push_identity_uri.to_lowercase();
if !push_identity_uri.starts_with("https://") { 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() { 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 if let Some(limit) = cfg.user_attachment_limit
&& !(0i64..=MAX_FILESIZE_KB).contains(&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 if let Some(limit) = cfg.org_attachment_limit
&& !(0i64..=MAX_FILESIZE_KB).contains(&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 if let Some(limit) = cfg.user_send_limit
&& !(0i64..=MAX_FILESIZE_KB).contains(&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 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())
&& !(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_enabled {
if cfg.sso_client_id.is_empty() || cfg.sso_client_secret.is_empty() || cfg.sso_authority.is_empty() { 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_issuer_url(&cfg.sso_authority, locale)?;
validate_internal_sso_redirect_url(&cfg.sso_callback_path)?; validate_internal_sso_redirect_url(&cfg.sso_callback_path, locale)?;
validate_sso_master_password_policy(cfg.sso_master_password_policy.as_ref())?; validate_sso_master_password_policy(cfg.sso_master_password_policy.as_ref(), locale)?;
} }
if cfg._enable_yubico { if cfg._enable_yubico {
if cfg.yubico_client_id.is_some() != cfg.yubico_secret_key.is_some() { 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 { 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 // Check if we can find the sendmail command to execute when no absolute path is given
if !path.is_absolute() { if !path.is_absolute() {
let Ok(which_path) = which::which(&command) else { 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; path = which_path;
} }
match path.metadata() { match path.metadata() {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => { 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(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) => { Ok(metadata) => {
if metadata.is_dir() { 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)] #[cfg(unix)]
if nix::unistd::access(&path, nix::unistd::AccessFlags::X_OK).is_err() { 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 { } else {
if cfg.smtp_host.is_some() == cfg.smtp_from.is_empty() { 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() { 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) { 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 { 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) { 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 { 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 { 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 // 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); let validate_regex = regex::Regex::new(r);
match validate_regex { match validate_regex {
Ok(_) => (), 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" => (), "internal" | "bitwarden" | "duckduckgo" | "google" => (),
_ => { _ => {
if !icon_service.starts_with("http") { 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() { match icon_service.matches("{}").count() {
1 => (), // nominal 1 => (), // nominal
0 => err!(format!("Icon service URL `{icon_service}` has no placeholder \"{{}}\"")), 0 => err!(crate::i18n::config_icon_service_url_missing_placeholder(locale), icon_service),
_ => err!(format!("Icon service URL `{icon_service}` has more than one placeholder \"{{}}\"")), _ => 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 // Check if the icon redirect code is valid
match cfg.icon_redirect_code { match cfg.icon_redirect_code {
301 | 302 | 307 | 308 => (), 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 { 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) { 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 // Validate schedule crontab format
if !cfg.send_purge_schedule.is_empty() && cfg.send_purge_schedule.parse::<Schedule>().is_err() { if !cfg.send_purge_schedule.is_empty() && cfg.send_purge_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.trash_purge_schedule.is_empty() && cfg.trash_purge_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.incomplete_2fa_schedule.is_empty() && cfg.incomplete_2fa_schedule.parse::<Schedule>().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() if !cfg.emergency_notification_reminder_schedule.is_empty()
&& cfg.emergency_notification_reminder_schedule.parse::<Schedule>().is_err() && cfg.emergency_notification_reminder_schedule.parse::<Schedule>().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() if !cfg.emergency_request_timeout_schedule.is_empty()
&& cfg.emergency_request_timeout_schedule.parse::<Schedule>().is_err() && cfg.emergency_request_timeout_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.event_cleanup_schedule.is_empty() && cfg.event_cleanup_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.auth_request_purge_schedule.is_empty() && cfg.auth_request_purge_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.duo_context_purge_schedule.is_empty() && cfg.duo_context_purge_schedule.parse::<Schedule>().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::<Schedule>().is_err() { if !cfg.purge_incomplete_sso_auth.is_empty() && cfg.purge_incomplete_sso_auth.parse::<Schedule>().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 { 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 { 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 { 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 { 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 { 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 { 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 { if !cfg.disable_admin_token {
match cfg.admin_token.as_ref() { match cfg.admin_token.as_ref() {
Some(t) if t.starts_with("$argon2") => { Some(t) if t.starts_with("$argon2") => {
if let Err(e) = argon2::password_hash::phc::PasswordHash::new(t) { 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(_) => { Some(_) => {
@ -1371,31 +1372,37 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
Ok(()) Ok(())
} }
fn validate_internal_sso_issuer_url(sso_authority: &String) -> Result<openidconnect::IssuerUrl, Error> { fn validate_internal_sso_issuer_url(sso_authority: &String, locale: &str) -> Result<openidconnect::IssuerUrl, Error> {
match openidconnect::IssuerUrl::new(sso_authority.clone()) { 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), Ok(issuer_url) => Ok(issuer_url),
} }
} }
fn validate_internal_sso_redirect_url(sso_callback_path: &String) -> Result<openidconnect::RedirectUrl, Error> { fn validate_internal_sso_redirect_url(
sso_callback_path: &String,
locale: &str,
) -> Result<openidconnect::RedirectUrl, Error> {
match openidconnect::RedirectUrl::new(sso_callback_path.clone()) { 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), Ok(redirect_url) => Ok(redirect_url),
} }
} }
fn validate_sso_master_password_policy( fn validate_sso_master_password_policy(
sso_master_password_policy: Option<&String>, sso_master_password_policy: Option<&String>,
locale: &str,
) -> Result<Option<serde_json::Value>, Error> { ) -> Result<Option<serde_json::Value>, Error> {
let policy = sso_master_password_policy.as_ref().map(|mpp| serde_json::from_str::<serde_json::Value>(mpp)); let policy = sso_master_password_policy.as_ref().map(|mpp| serde_json::from_str::<serde_json::Value>(mpp));
match policy { match policy {
None => Ok(None), None => Ok(None),
Some(Ok(jsobject @ serde_json::Value::Object(_))) => Ok(Some(jsobject)), 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)) => { 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<T: serde::ser::Serialize>(&self, name: &str, data: &T) -> Result<String, Error> { pub fn render_fallback_template<T: serde::ser::Serialize>(&self, name: &str, data: &T) -> Result<String, Error> {
let hb = &self.inner.read().unwrap().templates; let hb = &self.inner.read().unwrap().templates;
hb.render(&format!("fallback_{name}"), data).map_err(Into::into) hb.render(&format!("fallback_{name}"), data).map_err(Into::into)
@ -1759,15 +1776,18 @@ impl Config {
} }
pub fn sso_issuer_url(&self) -> Result<openidconnect::IssuerUrl, Error> { pub fn sso_issuer_url(&self) -> Result<openidconnect::IssuerUrl, Error> {
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<openidconnect::RedirectUrl, Error> { pub fn sso_redirect_url(&self) -> Result<openidconnect::RedirectUrl, Error> {
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<serde_json::Value> { pub fn sso_master_password_policy_value(&self) -> Option<serde_json::Value> {
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<String> { pub fn sso_scopes_vec(&self) -> Vec<String> {
@ -1793,6 +1813,7 @@ where
hb.set_strict_mode(true); hb.set_strict_mode(true);
// Register helpers // Register helpers
hb.register_helper("case", Box::new(case_helper)); 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("to_json", Box::new(to_json));
hb.register_helper("webver", Box::new(webver)); hb.register_helper("webver", Box::new(webver));
hb.register_helper("vwver", Box::new(vwver)); 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>( fn to_json<'reg, 'rc>(
h: &Helper<'rc>, h: &Helper<'rc>,
_r: &'reg Handlebars<'_>, _r: &'reg Handlebars<'_>,

24
src/db/mod.rs

@ -218,7 +218,7 @@ impl DbPool {
init_stmts: conn_type.get_init_stmts(), init_stmts: conn_type.get_init_stmts(),
})) }))
.build(manager) .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 // Set a global to determine the database more easily throughout the rest of the code
if ACTIVE_DB_TYPE.set(conn_type).is_err() { 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 { let permit = match timeout(duration, Arc::clone(&self.semaphore).acquire_owned()).await {
Ok(p) => p.expect("Semaphore should be open"), Ok(p) => p.expect("Semaphore should be open"),
Err(_) => { 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 p = self.pool.as_ref().expect("DbPool.pool should always be Some()");
let pool = p.clone(); let pool = p.clone();
let c = let c = run_blocking(move || pool.get_timeout(duration))
run_blocking(move || pool.get_timeout(duration)).await.map_res("Error retrieving connection from pool")?; .await
.map_res(crate::i18n::db_error_retrieving_connection_from_pool(&CONFIG.default_locale()))?;
Ok(DbConn { Ok(DbConn {
conn: Arc::new(Mutex::new(Some(c))), conn: Arc::new(Mutex::new(Some(c))),
permit: Some(permit), permit: Some(permit),
@ -260,7 +261,7 @@ impl DbConnType {
return Ok(DbConnType::Mysql); return Ok(DbConnType::Mysql);
#[cfg(not(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 // Postgresql
} else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") { } else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") {
@ -268,7 +269,7 @@ impl DbConnType {
return Ok(DbConnType::Postgresql); return Ok(DbConnType::Postgresql);
#[cfg(not(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) // Sqlite (explicit)
} else if url.len() > 7 && &url[..7] == "sqlite:" { } else if url.len() > 7 && &url[..7] == "sqlite:" {
@ -276,7 +277,7 @@ impl DbConnType {
return Ok(DbConnType::Sqlite); return Ok(DbConnType::Sqlite);
#[cfg(not(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. // 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() { if std::path::Path::new(url).exists() {
return Ok(DbConnType::Sqlite); return Ok(DbConnType::Sqlite);
} }
err!(format!( let msg = format!(
"`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \ "`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \
and no existing SQLite database was found at '{url}'. \ and no existing SQLite database was found at '{url}'. \
If you intend to use SQLite, use an explicit `sqlite://` scheme in your `DATABASE_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." Otherwise, check your DATABASE_URL for typos or quoting issues."
)) );
err!(msg)
} }
#[cfg(not(sqlite))] #[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 { pub fn get_init_stmts(&self) -> String {
@ -421,7 +423,7 @@ pub fn backup_sqlite() -> Result<String, Error> {
.bind::<diesel::sql_types::Text, _>(&backup_file) .bind::<diesel::sql_types::Text, _>(&backup_file)
.execute(&mut conn) .execute(&mut conn)
.map(|_| ()) .map(|_| ())
.map_res("VACUUM INTO failed")?; .map_res(crate::i18n::db_vacuum_into_failed(&CONFIG.default_locale()))?;
Ok(backup_file) Ok(backup_file)
} else { } else {

7
src/db/models/archive.rs

@ -2,6 +2,7 @@ use chrono::NaiveDateTime;
use diesel::prelude::*; use diesel::prelude::*;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{DbConn, schema::archives}, db::{DbConn, schema::archives},
error::MapResult, error::MapResult,
@ -52,7 +53,7 @@ impl Archive {
.do_update() .do_update()
.set(archives::archived_at.eq(archived_at)) .set(archives::archived_at.eq(archived_at))
.execute(conn) .execute(conn)
.map_res("Error saving archive") .map_res(crate::i18n::db_error_saving_archive(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(archives::table) diesel::insert_into(archives::table)
@ -65,7 +66,7 @@ impl Archive {
.do_update() .do_update()
.set(archives::archived_at.eq(archived_at)) .set(archives::archived_at.eq(archived_at))
.execute(conn) .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)), archives::table.filter(archives::user_uuid.eq(user_uuid)).filter(archives::cipher_uuid.eq(cipher_uuid)),
) )
.execute(conn) .execute(conn)
.map_res("Error deleting archive") .map_res(crate::i18n::db_error_deleting_archive(&CONFIG.default_locale()))
}) })
.await .await
} }

6
src/db/models/attachment.rs

@ -89,7 +89,7 @@ impl Attachment {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving attachment") .map_res(crate::i18n::db_error_saving_attachment(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(attachments::table) diesel::insert_into(attachments::table)
@ -98,7 +98,7 @@ impl Attachment {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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, 10,
) )
.map(|_| ()) .map(|_| ())
.map_res("Error deleting attachment") .map_res(crate::i18n::db_error_deleting_attachment(&CONFIG.default_locale()))
}) })
.await?; .await?;

11
src/db/models/auth_request.rs

@ -4,6 +4,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::{ApiResult, EmptyResult}, api::{ApiResult, EmptyResult},
crypto::ct_eq, crypto::ct_eq,
db::{DbConn, schema::auth_requests}, db::{DbConn, schema::auth_requests},
@ -91,7 +92,7 @@ impl AuthRequest {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving auth_request") .map_res(crate::i18n::db_error_saving_auth_request(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(auth_requests::table) diesel::insert_into(auth_requests::table)
@ -100,7 +101,7 @@ impl AuthRequest {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(auth_requests::table.filter(auth_requests::uuid.eq(&self.uuid))) diesel::delete(auth_requests::table.filter(auth_requests::uuid.eq(&self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting auth request") .map_res(crate::i18n::db_error_deleting_auth_request(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -170,7 +171,7 @@ impl AuthRequest {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(auth_requests::table.filter(auth_requests::user_uuid.eq(user_uuid))) diesel::delete(auth_requests::table.filter(auth_requests::user_uuid.eq(user_uuid)))
.execute(conn) .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 .await
} }
@ -185,7 +186,7 @@ impl AuthRequest {
.set(auth_requests::authentication_date.eq(now)) .set(auth_requests::authentication_date.eq(now))
.execute(conn) .execute(conn)
.map(|updated| updated == 1) .map(|updated| updated == 1)
.map_res("Error updating auth request") .map_res(crate::i18n::db_error_updating_auth_request(&CONFIG.default_locale()))
}) })
.await .await
} }

26
src/db/models/cipher.rs

@ -97,10 +97,11 @@ impl Cipher {
} }
pub fn validate_cipher_data(cipher_data: &[CipherData]) -> EmptyResult { pub fn validate_cipher_data(cipher_data: &[CipherData]) -> EmptyResult {
let locale = CONFIG.default_locale();
let mut validation_errors = serde_json::Map::new(); let mut validation_errors = serde_json::Map::new();
let max_note_size = CONFIG._max_note_size(); let max_note_size = CONFIG._max_note_size();
let max_note_size_msg = 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() { for (index, cipher) in cipher_data.iter().enumerate() {
// Validate the note size and if it is exceeded return a warning // Validate the note size and if it is exceeded return a warning
if let Some(note) = &cipher.notes if let Some(note) = &cipher.notes
@ -118,10 +119,8 @@ impl Cipher {
{ {
validation_errors.insert( validation_errors.insert(
format!("Ciphers[{index}].Notes"), format!("Ciphers[{index}].Notes"),
serde_json::to_value([ serde_json::to_value([crate::i18n::cipher_password_history_null_only_strings(&locale)])
"The password history contains a `null` value. Only strings are allowed.", .unwrap(),
])
.unwrap(),
); );
break; break;
} }
@ -131,11 +130,11 @@ impl Cipher {
if !validation_errors.is_empty() { if !validation_errors.is_empty() {
let err_json = json!({ let err_json = json!({
"message": "The model state is invalid.", "message": crate::i18n::cipher_model_state_invalid(&locale),
"validationErrors" : validation_errors, "validationErrors" : validation_errors,
"object": "error" "object": "error"
}); });
err_json!(err_json, "Import validation errors") err_json!(err_json, crate::i18n::cipher_import_validation_errors(&locale))
} }
Ok(()) Ok(())
@ -400,7 +399,10 @@ impl Cipher {
6 => "bankAccount", 6 => "bankAccount",
7 => "driversLicense", 7 => "driversLicense",
8 => "passport", 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; json_object[key] = type_data_json;
@ -447,7 +449,7 @@ impl Cipher {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving cipher") .map_res(crate::i18n::db_error_saving_cipher(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(ciphers::table) diesel::insert_into(ciphers::table)
@ -456,7 +458,7 @@ impl Cipher {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(ciphers::table.filter(ciphers::uuid.eq(&self.uuid))) diesel::delete(ciphers::table.filter(ciphers::uuid.eq(&self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting cipher") .map_res(crate::i18n::db_error_deleting_cipher(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -543,7 +545,7 @@ impl Cipher {
if let Some(old_folder) = FolderCipher::find_by_folder_and_cipher(&old_folder, &self.uuid, conn).await { if let Some(old_folder) = FolderCipher::find_by_folder_and_cipher(&old_folder, &self.uuid, conn).await {
old_folder.delete(conn).await old_folder.delete(conn).await
} else { } else {
err!("Couldn't move from previous folder") err!(crate::i18n::cipher_couldnt_move_from_previous_folder(&CONFIG.default_locale()))
} }
} }

26
src/db/models/collection.rs

@ -175,7 +175,7 @@ impl Collection {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving collection") .map_res(crate::i18n::db_error_saving_collection(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(collections::table) diesel::insert_into(collections::table)
@ -184,7 +184,7 @@ impl Collection {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(collections::table.filter(collections::uuid.eq(self.uuid))) diesel::delete(collections::table.filter(collections::uuid.eq(self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting collection") .map_res(crate::i18n::db_error_deleting_collection(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -743,7 +743,7 @@ impl CollectionUser {
.do_update() .do_update()
.set(values) .set(values)
.execute(conn) .execute(conn)
.map_res("Error adding user to collection") .map_res(crate::i18n::db_error_adding_user_to_collection(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(users_collections::table) diesel::insert_into(users_collections::table)
@ -752,7 +752,7 @@ impl CollectionUser {
.do_update() .do_update()
.set(values) .set(values)
.execute(conn) .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)), .filter(users_collections::collection_uuid.eq(&self.collection_uuid)),
) )
.execute(conn) .execute(conn)
.map_res("Error removing user from collection") .map_res(crate::i18n::db_error_removing_user_from_collection(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -853,7 +853,7 @@ impl CollectionUser {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(users_collections::table.filter(users_collections::collection_uuid.eq(collection_uuid))) diesel::delete(users_collections::table.filter(users_collections::collection_uuid.eq(collection_uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting users from collection") .map_res(crate::i18n::db_error_deleting_users_from_collection(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -875,7 +875,7 @@ impl CollectionUser {
), ),
) )
.execute(conn) .execute(conn)
.map_res("Error removing user from collections")?; .map_res(crate::i18n::db_error_removing_user_from_collections(&CONFIG.default_locale()))?;
} }
Ok(()) Ok(())
}) })
@ -902,7 +902,7 @@ impl CollectionCipher {
.on_conflict(diesel::dsl::DuplicatedKeys) .on_conflict(diesel::dsl::DuplicatedKeys)
.do_nothing() .do_nothing()
.execute(conn) .execute(conn)
.map_res("Error adding cipher to collection") .map_res(crate::i18n::db_error_adding_cipher_to_collection(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(ciphers_collections::table) diesel::insert_into(ciphers_collections::table)
@ -913,7 +913,7 @@ impl CollectionCipher {
.on_conflict((ciphers_collections::cipher_uuid, ciphers_collections::collection_uuid)) .on_conflict((ciphers_collections::cipher_uuid, ciphers_collections::collection_uuid))
.do_nothing() .do_nothing()
.execute(conn) .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)), .filter(ciphers_collections::collection_uuid.eq(collection_uuid)),
) )
.execute(conn) .execute(conn)
.map_res("Error deleting cipher from collection") .map_res(crate::i18n::db_error_deleting_cipher_from_collection(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -937,7 +937,7 @@ impl CollectionCipher {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(ciphers_collections::table.filter(ciphers_collections::cipher_uuid.eq(cipher_uuid))) diesel::delete(ciphers_collections::table.filter(ciphers_collections::cipher_uuid.eq(cipher_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing cipher from collections") .map_res(crate::i18n::db_error_removing_cipher_from_collections(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -946,7 +946,7 @@ impl CollectionCipher {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(ciphers_collections::table.filter(ciphers_collections::collection_uuid.eq(collection_uuid))) diesel::delete(ciphers_collections::table.filter(ciphers_collections::collection_uuid.eq(collection_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing ciphers from collection") .map_res(crate::i18n::db_error_removing_ciphers_from_collection(&CONFIG.default_locale()))
}) })
.await .await
} }

11
src/db/models/device.rs

@ -5,6 +5,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
crypto, crypto,
db::{DbConn, schema::devices}, db::{DbConn, schema::devices},
@ -155,7 +156,7 @@ impl Device {
.set(&*self) .set(&*self)
.execute(conn), .execute(conn),
10, 10,
).map_res("Error saving device") ).map_res(crate::i18n::db_error_saving_device(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
crate::util::retry(|| crate::util::retry(||
@ -166,7 +167,7 @@ impl Device {
.set(&*self) .set(&*self)
.execute(conn), .execute(conn),
10, 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| { conn.run(move |conn| {
diesel::delete(devices::table.filter(devices::user_uuid.eq(user_uuid))) diesel::delete(devices::table.filter(devices::user_uuid.eq(user_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing devices for user") .map_res(crate::i18n::db_error_removing_devices_for_user(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -218,7 +219,7 @@ impl Device {
.filter(devices::uuid.eq(uuid)) .filter(devices::uuid.eq(uuid))
.set(devices::push_token.eq::<Option<String>>(None)) .set(devices::push_token.eq::<Option<String>>(None))
.execute(conn) .execute(conn)
.map_res("Error removing push token") .map_res(crate::i18n::db_error_removing_push_token(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -281,7 +282,7 @@ impl Device {
.filter(devices::user_uuid.eq(user_uuid)) .filter(devices::user_uuid.eq(user_uuid))
.set(devices::twofactor_remember.eq::<Option<String>>(None)) .set(devices::twofactor_remember.eq::<Option<String>>(None))
.execute(conn) .execute(conn)
.map_res("Error removing two factor remember tokens") .map_res(crate::i18n::db_error_removing_twofactor_remember_tokens(&CONFIG.default_locale()))
}) })
.await .await
} }

27
src/db/models/emergency_access.rs

@ -4,6 +4,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{DbConn, schema::emergency_access}, db::{DbConn, schema::emergency_access},
error::MapResult, error::MapResult,
@ -115,14 +116,16 @@ impl EmergencyAccess {
pub fn deadline_at(&self) -> Result<NaiveDateTime, crate::Error> { pub fn deadline_at(&self) -> Result<NaiveDateTime, crate::Error> {
if !(EMERGENCY_ACCESS_TIMEOUT_RANGE).contains(&self.wait_time_days) { 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)) TimeDelta::try_days(i64::from(self.wait_time_days))
.and_then(|w| initiated_at.checked_add_signed(w)) .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<bool, crate::Error> { pub fn is_recovery_allowed(&self, now: &NaiveDateTime) -> Result<bool, crate::Error> {
@ -171,7 +174,7 @@ impl EmergencyAccess {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving emergency access") .map_res(crate::i18n::db_error_saving_emergency_access(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(emergency_access::table) diesel::insert_into(emergency_access::table)
@ -180,7 +183,7 @@ impl EmergencyAccess {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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 { match res {
Ok(1) => {} // One record updated, which is valid Ok(1) => {} // One record updated, which is valid
Ok(_) => err!("Emergency access status was changed already"), Ok(_) => err!(crate::i18n::emergency_access_status_changed_already(&CONFIG.default_locale())),
Err(e) => err!("Error updating emergency access status", format!("{e}")), Err(e) => {
err!(crate::i18n::emergency_access_error_updating_status(&CONFIG.default_locale()), format!("{e}"))
}
} }
self.status = to_status; self.status = to_status;
@ -238,7 +243,7 @@ impl EmergencyAccess {
}, },
10, 10,
) )
.map_res("Error updating emergency access status") .map_res(crate::i18n::db_error_updating_emergency_access_status(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -266,7 +271,7 @@ impl EmergencyAccess {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(emergency_access::table.filter(emergency_access::uuid.eq(self.uuid))) diesel::delete(emergency_access::table.filter(emergency_access::uuid.eq(self.uuid)))
.execute(conn) .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 .await
} }
@ -398,11 +403,11 @@ impl EmergencyAccess {
pub async fn accept_invite(&mut self, grantee_uuid: &UserId, grantee_email: &str, conn: &DbConn) -> EmptyResult { 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 { 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 { 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; self.status = EmergencyAccessStatus::Accepted as i32;

14
src/db/models/event.rs

@ -215,7 +215,7 @@ impl Event {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving event") .map_res(crate::i18n::db_error_saving_event(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(event::table) diesel::insert_into(event::table)
@ -224,7 +224,7 @@ impl Event {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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 { pub async fn delete(self, conn: &DbConn) -> EmptyResult {
conn.run(move |conn| { 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 .await
} }
@ -352,16 +354,16 @@ impl Event {
}; };
let Some(days_to_retain) = TimeDelta::try_days(i64::from(days_to_retain)) else { 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 { 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| { conn.run(move |conn| {
diesel::delete(event::table.filter(event::event_date.lt(dt))) diesel::delete(event::table.filter(event::event_date.lt(dt)))
.execute(conn) .execute(conn)
.map_res("Error cleaning old events") .map_res(crate::i18n::db_error_cleaning_old_events(&CONFIG.default_locale()))
}) })
.await .await
} }

9
src/db/models/favorite.rs

@ -1,6 +1,7 @@
use diesel::prelude::*; use diesel::prelude::*;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{DbConn, schema::favorites}, db::{DbConn, schema::favorites},
error::MapResult, error::MapResult,
@ -45,7 +46,7 @@ impl Favorite {
diesel::insert_into(favorites::table) diesel::insert_into(favorites::table)
.values((favorites::user_uuid.eq(user_uuid), favorites::cipher_uuid.eq(cipher_uuid))) .values((favorites::user_uuid.eq(user_uuid), favorites::cipher_uuid.eq(cipher_uuid)))
.execute(conn) .execute(conn)
.map_res("Error adding favorite") .map_res(crate::i18n::db_error_adding_favorite(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -58,7 +59,7 @@ impl Favorite {
.filter(favorites::cipher_uuid.eq(cipher_uuid)), .filter(favorites::cipher_uuid.eq(cipher_uuid)),
) )
.execute(conn) .execute(conn)
.map_res("Error removing favorite") .map_res(crate::i18n::db_error_removing_favorite(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -72,7 +73,7 @@ impl Favorite {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(favorites::table.filter(favorites::cipher_uuid.eq(cipher_uuid))) diesel::delete(favorites::table.filter(favorites::cipher_uuid.eq(cipher_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing favorites by cipher") .map_res(crate::i18n::db_error_removing_favorites_by_cipher(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -82,7 +83,7 @@ impl Favorite {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(favorites::table.filter(favorites::user_uuid.eq(user_uuid))) diesel::delete(favorites::table.filter(favorites::user_uuid.eq(user_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing favorites by user") .map_res(crate::i18n::db_error_removing_favorites_by_user(&CONFIG.default_locale()))
}) })
.await .await
} }

17
src/db/models/folder.rs

@ -4,6 +4,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{ db::{
DbConn, DbConn,
@ -84,7 +85,7 @@ impl Folder {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving folder") .map_res(crate::i18n::db_error_saving_folder(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(folders::table) diesel::insert_into(folders::table)
@ -93,7 +94,7 @@ impl Folder {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(folders::table.filter(folders::uuid.eq(&self.uuid))) diesel::delete(folders::table.filter(folders::uuid.eq(&self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting folder") .map_res(crate::i18n::db_error_deleting_folder(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -145,7 +146,7 @@ impl FolderCipher {
.on_conflict(diesel::dsl::DuplicatedKeys) .on_conflict(diesel::dsl::DuplicatedKeys)
.do_nothing() .do_nothing()
.execute(conn) .execute(conn)
.map_res("Error adding cipher to folder") .map_res(crate::i18n::db_error_adding_cipher_to_folder(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(folders_ciphers::table) diesel::insert_into(folders_ciphers::table)
@ -153,7 +154,7 @@ impl FolderCipher {
.on_conflict((folders_ciphers::cipher_uuid, folders_ciphers::folder_uuid)) .on_conflict((folders_ciphers::cipher_uuid, folders_ciphers::folder_uuid))
.do_nothing() .do_nothing()
.execute(conn) .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)), .filter(folders_ciphers::folder_uuid.eq(self.folder_uuid)),
) )
.execute(conn) .execute(conn)
.map_res("Error removing cipher from folder") .map_res(crate::i18n::db_error_removing_cipher_from_folder(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -175,7 +176,7 @@ impl FolderCipher {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(folders_ciphers::table.filter(folders_ciphers::cipher_uuid.eq(cipher_uuid))) diesel::delete(folders_ciphers::table.filter(folders_ciphers::cipher_uuid.eq(cipher_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing cipher from folders") .map_res(crate::i18n::db_error_removing_cipher_from_folders(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -184,7 +185,7 @@ impl FolderCipher {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(folders_ciphers::table.filter(folders_ciphers::folder_uuid.eq(folder_uuid))) diesel::delete(folders_ciphers::table.filter(folders_ciphers::folder_uuid.eq(folder_uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing ciphers from folder") .map_res(crate::i18n::db_error_removing_ciphers_from_folder(&CONFIG.default_locale()))
}) })
.await .await
} }

27
src/db/models/group.rs

@ -4,6 +4,7 @@ use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{ db::{
DbConn, DbConn,
@ -172,7 +173,7 @@ impl Group {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving group") .map_res(crate::i18n::db_error_saving_group(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(groups::table) diesel::insert_into(groups::table)
@ -181,7 +182,7 @@ impl Group {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(groups::table.filter(groups::uuid.eq(&self.uuid))) diesel::delete(groups::table.filter(groups::uuid.eq(&self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting group") .map_res(crate::i18n::db_error_deleting_group(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -308,7 +309,7 @@ impl Group {
}, },
10, 10,
) )
.map_res("Error updating group revision") .map_res(crate::i18n::db_error_updating_group_revision(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -337,7 +338,7 @@ impl CollectionGroup {
.do_update() .do_update()
.set(values) .set(values)
.execute(conn) .execute(conn)
.map_res("Error adding group to collection") .map_res(crate::i18n::db_error_adding_group_to_collection(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(collections_groups::table) diesel::insert_into(collections_groups::table)
@ -346,7 +347,7 @@ impl CollectionGroup {
.do_update() .do_update()
.set(values) .set(values)
.execute(conn) .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::collections_uuid.eq(&self.collections_uuid))
.filter(collections_groups::groups_uuid.eq(&self.groups_uuid)) .filter(collections_groups::groups_uuid.eq(&self.groups_uuid))
.execute(conn) .execute(conn)
.map_res("Error deleting collection group") .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -438,7 +439,7 @@ impl CollectionGroup {
diesel::delete(collections_groups::table) diesel::delete(collections_groups::table)
.filter(collections_groups::groups_uuid.eq(group_uuid)) .filter(collections_groups::groups_uuid.eq(group_uuid))
.execute(conn) .execute(conn)
.map_res("Error deleting collection group") .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -460,7 +461,7 @@ impl CollectionGroup {
diesel::delete(collections_groups::table) diesel::delete(collections_groups::table)
.filter(collections_groups::collections_uuid.eq(collection_uuid)) .filter(collections_groups::collections_uuid.eq(collection_uuid))
.execute(conn) .execute(conn)
.map_res("Error deleting collection group") .map_res(crate::i18n::db_error_deleting_collection_group(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -482,7 +483,7 @@ impl GroupUser {
.on_conflict(diesel::dsl::DuplicatedKeys) .on_conflict(diesel::dsl::DuplicatedKeys)
.do_nothing() .do_nothing()
.execute(conn) .execute(conn)
.map_res("Error adding user to group") .map_res(crate::i18n::db_error_adding_user_to_group(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(groups_users::table) diesel::insert_into(groups_users::table)
@ -490,7 +491,7 @@ impl GroupUser {
.on_conflict((groups_users::users_organizations_uuid, groups_users::groups_uuid)) .on_conflict((groups_users::users_organizations_uuid, groups_users::groups_uuid))
.do_nothing() .do_nothing()
.execute(conn) .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) diesel::delete(groups_users::table)
.filter(groups_users::groups_uuid.eq(group_uuid)) .filter(groups_users::groups_uuid.eq(group_uuid))
.execute(conn) .execute(conn)
.map_res("Error deleting group users") .map_res(crate::i18n::db_error_deleting_group_users(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -598,7 +599,7 @@ impl GroupUser {
diesel::delete(groups_users::table) diesel::delete(groups_users::table)
.filter(groups_users::users_organizations_uuid.eq(member_uuid)) .filter(groups_users::users_organizations_uuid.eq(member_uuid))
.execute(conn) .execute(conn)
.map_res("Error deleting user groups") .map_res(crate::i18n::db_error_deleting_user_groups(&CONFIG.default_locale()))
}) })
.await .await
} }

30
src/db/models/org_policy.rs

@ -140,10 +140,10 @@ impl OrgPolicy {
.filter(org_policies::uuid.eq(&self.uuid)) .filter(org_policies::uuid.eq(&self.uuid))
.set(&*self) .set(&*self)
.execute(conn) .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()), Err(e) => Err(e.into()),
}.map_res("Error saving org_policy") }.map_res(crate::i18n::db_error_saving_org_policy(&CONFIG.default_locale()))
} }
postgresql { postgresql {
// We need to make sure we're not going to violate the unique constraint on org_uuid and atype. // 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)), .filter(org_policies::atype.eq(&self.atype)),
) )
.execute(conn) .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) diesel::insert_into(org_policies::table)
.values(&*self) .values(&*self)
@ -163,7 +163,7 @@ impl OrgPolicy {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(org_policies::table.filter(org_policies::uuid.eq(self.uuid))) diesel::delete(org_policies::table.filter(org_policies::uuid.eq(self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting org_policy") .map_res(crate::i18n::db_error_deleting_org_policy(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -242,7 +242,7 @@ impl OrgPolicy {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(org_policies::table.filter(org_policies::org_uuid.eq(org_uuid))) diesel::delete(org_policies::table.filter(org_policies::org_uuid.eq(org_uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting org_policy") .map_res(crate::i18n::db_error_deleting_org_policy(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -328,26 +328,30 @@ impl OrgPolicy {
if CONFIG.email_2fa_auto_fallback() { if CONFIG.email_2fa_auto_fallback() {
two_factor::email::find_and_activate_email_2fa(&m.user_uuid, conn).await?; two_factor::email::find_and_activate_email_2fa(&m.user_uuid, conn).await?;
} else { } 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 // 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 { if Self::is_applicable_to_user(&m.user_uuid, OrgPolicyType::SingleOrg, Some(&m.org_uuid), conn).await {
err!(format!( err!(
"Cannot {} because another organization policy forbids it (membership {})", crate::i18n::org_policy_cannot_because_other_org_policy_forbids(&CONFIG.default_locale()),
action, m.uuid format!("{}, {}", action, m.uuid)
)); );
} }
if let Some(p) = Self::find_by_org_and_type(&m.org_uuid, OrgPolicyType::SingleOrg, conn).await if let Some(p) = Self::find_by_org_and_type(&m.org_uuid, OrgPolicyType::SingleOrg, conn).await
&& p.enabled && p.enabled
&& Membership::count_accepted_and_confirmed_by_user(&m.user_uuid, &m.org_uuid, conn).await > 0 && 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 {})", "Cannot {} because the organization policy forbids being part of other organization (membership {})",
action, m.uuid action, m.uuid
)); );
err!(msg);
} }
} }

27
src/db/models/organization.rs

@ -342,7 +342,10 @@ impl OrganizationApiKey {
impl Organization { impl Organization {
pub async fn save(&self, conn: &DbConn) -> EmptyResult { pub async fn save(&self, conn: &DbConn) -> EmptyResult {
if !crate::util::is_valid_email(&self.billing_email) { 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 { for member in &Membership::find_by_org(&self.uuid, conn).await {
@ -357,7 +360,7 @@ impl Organization {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving organization") .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(organizations::table) diesel::insert_into(organizations::table)
@ -366,7 +369,7 @@ impl Organization {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(organizations::table.filter(organizations::uuid.eq(self.uuid))) diesel::delete(organizations::table.filter(organizations::uuid.eq(self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error saving organization") .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -722,7 +725,7 @@ impl Membership {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error adding user to organization") .map_res(crate::i18n::db_error_adding_user_to_organization(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(users_organizations::table) diesel::insert_into(users_organizations::table)
@ -731,7 +734,7 @@ impl Membership {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(users_organizations::table.filter(users_organizations::uuid.eq(self.uuid))) diesel::delete(users_organizations::table.filter(users_organizations::uuid.eq(self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error removing user from organization") .map_res(crate::i18n::db_error_removing_user_from_organization(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -850,7 +853,7 @@ impl Membership {
.filter(users_organizations::status.eq(MembershipStatus::Invited as i32)) .filter(users_organizations::status.eq(MembershipStatus::Invited as i32))
.set(users_organizations::status.eq(MembershipStatus::Accepted as i32)) .set(users_organizations::status.eq(MembershipStatus::Accepted as i32))
.execute(conn) .execute(conn)
.map_res("Error confirming invitations") .map_res(crate::i18n::db_error_confirming_invitations(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -1154,7 +1157,7 @@ impl OrganizationApiKey {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving organization") .map_res(crate::i18n::db_error_saving_organization(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(organization_api_key::table) diesel::insert_into(organization_api_key::table)
@ -1163,7 +1166,7 @@ impl OrganizationApiKey {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(organization_api_key::table.filter(organization_api_key::org_uuid.eq(org_uuid))) diesel::delete(organization_api_key::table.filter(organization_api_key::org_uuid.eq(org_uuid)))
.execute(conn) .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 .await
} }

8
src/db/models/send.rs

@ -213,7 +213,7 @@ impl Send {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving send") .map_res(crate::i18n::db_error_saving_send(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(sends::table) diesel::insert_into(sends::table)
@ -222,7 +222,7 @@ impl Send {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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| { 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 .await
} }

11
src/db/models/sso_auth.rs

@ -10,6 +10,7 @@ use diesel::{
}; };
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{DbConn, DbPool, schema::sso_auth}, db::{DbConn, DbPool, schema::sso_auth},
error::MapResult, error::MapResult,
@ -93,7 +94,7 @@ impl SsoAuth {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving SSO auth") .map_res(crate::i18n::db_error_saving_sso_auth(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(sso_auth::table) diesel::insert_into(sso_auth::table)
@ -102,7 +103,7 @@ impl SsoAuth {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(sso_auth::table.filter(sso_auth::state.eq(self.state))) diesel::delete(sso_auth::table.filter(sso_auth::state.eq(self.state)))
.execute(conn) .execute(conn)
.map_res("Error deleting sso_auth") .map_res(crate::i18n::db_error_deleting_sso_auth(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -146,11 +147,11 @@ impl SsoAuth {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(sso_auth::table.filter(sso_auth::created_at.lt(oldest))) diesel::delete(sso_auth::table.filter(sso_auth::created_at.lt(oldest)))
.execute(conn) .execute(conn)
.map_res("Error deleting expired SSO nonce") .map_res(crate::i18n::db_error_deleting_expired_sso_nonce(&CONFIG.default_locale()))
}) })
.await .await
} else { } 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()))
} }
} }
} }

13
src/db/models/two_factor.rs

@ -5,6 +5,7 @@ use webauthn_rs_core::proto::CredentialV3;
use webauthn_rs_proto::{AttestationFormat, RegisteredExtensions}; use webauthn_rs_proto::{AttestationFormat, RegisteredExtensions};
use crate::{ use crate::{
CONFIG,
api::{EmptyResult, core::two_factor::webauthn::WebauthnRegistration}, api::{EmptyResult, core::two_factor::webauthn::WebauthnRegistration},
db::{DbConn, schema::twofactor}, db::{DbConn, schema::twofactor},
error::MapResult, error::MapResult,
@ -93,10 +94,10 @@ impl TwoFactor {
.filter(twofactor::uuid.eq(&self.uuid)) .filter(twofactor::uuid.eq(&self.uuid))
.set(self) .set(self)
.execute(conn) .execute(conn)
.map_res("Error saving twofactor") .map_res(crate::i18n::db_error_saving_twofactor(&CONFIG.default_locale()))
} }
Err(e) => Err(e.into()), Err(e) => Err(e.into()),
}.map_res("Error saving twofactor") }.map_res(crate::i18n::db_error_saving_twofactor(&CONFIG.default_locale()))
} }
postgresql { postgresql {
// We need to make sure we're not going to violate the unique constraint on user_uuid and atype. // 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. // 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))) let _: () = diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(&self.user_uuid)).filter(twofactor::atype.eq(&self.atype)))
.execute(conn) .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) diesel::insert_into(twofactor::table)
.values(self) .values(self)
@ -112,7 +113,7 @@ impl TwoFactor {
.do_update() .do_update()
.set(self) .set(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(twofactor::table.filter(twofactor::uuid.eq(self.uuid))) diesel::delete(twofactor::table.filter(twofactor::uuid.eq(self.uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting twofactor") .map_res(crate::i18n::db_error_deleting_twofactor(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -152,7 +153,7 @@ impl TwoFactor {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(user_uuid))) diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(user_uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting twofactors") .map_res(crate::i18n::db_error_deleting_twofactors(&CONFIG.default_locale()))
}) })
.await .await
} }

5
src/db/models/two_factor_duo_context.rs

@ -2,6 +2,7 @@ use chrono::Utc;
use diesel::prelude::*; use diesel::prelude::*;
use crate::{ use crate::{
CONFIG,
api::EmptyResult, api::EmptyResult,
db::{DbConn, schema::twofactor_duo_ctx}, db::{DbConn, schema::twofactor_duo_ctx},
error::MapResult, error::MapResult,
@ -43,7 +44,7 @@ impl TwoFactorDuoContext {
twofactor_duo_ctx::exp.eq(exp), twofactor_duo_ctx::exp.eq(exp),
)) ))
.execute(conn) .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 .await
} }
@ -63,7 +64,7 @@ impl TwoFactorDuoContext {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(twofactor_duo_ctx::table.filter(twofactor_duo_ctx::state.eq(&self.state))) diesel::delete(twofactor_duo_ctx::table.filter(twofactor_duo_ctx::state.eq(&self.state)))
.execute(conn) .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 .await
} }

6
src/db/models/two_factor_incomplete.rs

@ -60,7 +60,7 @@ impl TwoFactorIncomplete {
twofactor_incomplete::ip_address.eq(ip.ip.to_string()), twofactor_incomplete::ip_address.eq(ip.ip.to_string()),
)) ))
.execute(conn) .execute(conn)
.map_res("Error adding twofactor_incomplete record") .map_res(crate::i18n::db_error_adding_twofactor_incomplete_record(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -106,7 +106,7 @@ impl TwoFactorIncomplete {
.filter(twofactor_incomplete::device_uuid.eq(device_uuid)), .filter(twofactor_incomplete::device_uuid.eq(device_uuid)),
) )
.execute(conn) .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 .await
} }
@ -115,7 +115,7 @@ impl TwoFactorIncomplete {
conn.run(move |conn| { conn.run(move |conn| {
diesel::delete(twofactor_incomplete::table.filter(twofactor_incomplete::user_uuid.eq(user_uuid))) diesel::delete(twofactor_incomplete::table.filter(twofactor_incomplete::user_uuid.eq(user_uuid)))
.execute(conn) .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 .await
} }

40
src/db/models/user.rs

@ -70,6 +70,7 @@ pub struct User {
pub avatar_color: Option<String>, pub avatar_color: Option<String>,
pub external_id: Option<String>, // Todo: Needs to be removed in the future, this is not used anymore. pub external_id: Option<String>, // Todo: Needs to be removed in the future, this is not used anymore.
pub locale: Option<String>,
pub key_id: Option<KeyId>, pub key_id: Option<KeyId>,
} }
@ -157,6 +158,7 @@ impl User {
avatar_color: None, avatar_color: None,
external_id: None, // Todo: Needs to be removed in the future, this is not used anymore. external_id: None, // Todo: Needs to be removed in the future, this is not used anymore.
locale: None,
key_id: None, key_id: None,
} }
@ -316,7 +318,10 @@ impl User {
"emailVerified": self.verified(), "emailVerified": self.verified(),
"premium": true, "premium": true,
"premiumFromOrganization": false, "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, "twoFactorEnabled": twofactor_enabled,
"key": self.akey, "key": self.akey,
"privateKey": self.private_key, "privateKey": self.private_key,
@ -335,7 +340,7 @@ impl User {
pub async fn save(&mut self, conn: &DbConn) -> EmptyResult { pub async fn save(&mut self, conn: &DbConn) -> EmptyResult {
if !crate::util::is_valid_email(&self.email) { 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(); self.updated_at = Utc::now().naive_utc();
@ -348,7 +353,7 @@ impl User {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .execute(conn)
.map_res("Error saving user") .map_res(crate::i18n::db_error_saving_user(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(users::table) // Insert or update diesel::insert_into(users::table) // Insert or update
@ -357,7 +362,7 @@ impl User {
.do_update() .do_update()
.set(&*self) .set(&*self)
.execute(conn) .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 if member.atype == MembershipType::Owner
&& Membership::count_confirmed_by_org_and_type(&member.org_uuid, MembershipType::Owner, conn).await <= 1 && 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 Invitation::take(&self.email, conn).await; // Delete invitation if any
conn.run(move |conn| { 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 .await
} }
@ -401,7 +408,7 @@ impl User {
conn.run(move |conn| { conn.run(move |conn| {
retry(|| diesel::update(users::table).set(users::updated_at.eq(updated_at)).execute(conn), 10) 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 .await
} }
@ -422,7 +429,7 @@ impl User {
}, },
10, 10,
) )
.map_res("Error updating user revision") .map_res(crate::i18n::db_error_updating_user_revision(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -484,7 +491,10 @@ impl Invitation {
pub async fn save(&self, conn: &DbConn) -> EmptyResult { pub async fn save(&self, conn: &DbConn) -> EmptyResult {
if !crate::util::is_valid_email(&self.email) { 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: db_run! { conn:
@ -496,7 +506,7 @@ impl Invitation {
.on_conflict(diesel::dsl::DuplicatedKeys) .on_conflict(diesel::dsl::DuplicatedKeys)
.do_nothing() .do_nothing()
.execute(conn) .execute(conn)
.map_res("Error saving invitation") .map_res(crate::i18n::db_error_saving_invitation(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(invitations::table) diesel::insert_into(invitations::table)
@ -504,7 +514,7 @@ impl Invitation {
.on_conflict(invitations::email) .on_conflict(invitations::email)
.do_nothing() .do_nothing()
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(invitations::table.filter(invitations::email.eq(self.email))) diesel::delete(invitations::table.filter(invitations::email.eq(self.email)))
.execute(conn) .execute(conn)
.map_res("Error deleting invitation") .map_res(crate::i18n::db_error_deleting_invitation(&CONFIG.default_locale()))
}) })
.await .await
} }
@ -579,13 +589,13 @@ impl SsoUser {
diesel::insert_into(sso_users::table) diesel::insert_into(sso_users::table)
.values(self) .values(self)
.execute(conn) .execute(conn)
.map_res("Error saving SSO user") .map_res(crate::i18n::db_error_saving_sso_user(&CONFIG.default_locale()))
} }
postgresql, sqlite { postgresql, sqlite {
diesel::insert_into(sso_users::table) diesel::insert_into(sso_users::table)
.values(self) .values(self)
.execute(conn) .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| { conn.run(move |conn| {
diesel::delete(sso_users::table.filter(sso_users::user_uuid.eq(user_uuid))) diesel::delete(sso_users::table.filter(sso_users::user_uuid.eq(user_uuid)))
.execute(conn) .execute(conn)
.map_res("Error deleting sso user") .map_res(crate::i18n::db_error_deleting_sso_user(&CONFIG.default_locale()))
}) })
.await .await
} }

1
src/db/schema.rs

@ -218,6 +218,7 @@ table! {
api_key -> Nullable<Text>, api_key -> Nullable<Text>,
avatar_color -> Nullable<Text>, avatar_color -> Nullable<Text>,
external_id -> Nullable<Text>, external_id -> Nullable<Text>,
locale -> Nullable<Text>,
key_id -> Nullable<Text>, key_id -> Nullable<Text>,
} }
} }

4
src/http_client.rs

@ -24,10 +24,10 @@ pub fn make_http_request(method: reqwest::Method, url: &str) -> Result<reqwest::
LazyLock::new(|| get_reqwest_client_builder(true).build().expect("Failed to build client")); LazyLock::new(|| get_reqwest_client_builder(true).build().expect("Failed to build client"));
let Ok(url) = url::Url::parse(url) else { let Ok(url) = url::Url::parse(url) else {
err!("Invalid URL"); err!(crate::i18n::api_invalid_url(&CONFIG.default_locale()));
}; };
let Some(host) = url.host() else { let Some(host) = url.host() else {
err!("Invalid host"); err!(crate::i18n::api_invalid_host(&CONFIG.default_locale()));
}; };
should_block_host(&host)?; should_block_host(&host)?;

3129
src/i18n.rs

File diff suppressed because it is too large

406
src/mail.rs

@ -19,6 +19,7 @@ use crate::{
}, },
db::models::{Device, DeviceType, EmergencyAccessId, MembershipId, OrganizationId, User, UserId}, db::models::{Device, DeviceType, EmergencyAccessId, MembershipId, OrganizationId, User, UserId},
error::Error, error::Error,
i18n,
util::upcase_first, 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> { 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; let mut data = data;
sanitize_data(&mut 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)) Ok((subject_html, body_html, body_text))
} }
fn get_template(template_name: &str, data: &serde_json::Value) -> Result<(String, String), Error> { fn get_template(
let text = CONFIG.render_template(template_name, data)?; 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 mut text_split = text.split("<!---------------->");
let subject = if let Some(s) = text_split.next() { let subject = if let Some(s) = text_split.next() {
s.trim().to_owned() s.trim().to_owned()
} else { } 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() { let body = if let Some(s) = text_split.next() {
s.trim().to_owned() s.trim().to_owned()
} else { } else {
err!("Template doesn't contain body") err!(i18n::api_template_missing_body(&CONFIG.default_locale()))
}; };
if text_split.next().is_some() { 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)) 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<String>) -> EmptyResult { pub async fn send_password_hint(address: &str, hint: Option<String>) -> EmptyResult {
send_password_hint_for_locale(address, hint, None).await
}
pub async fn send_password_hint_for_locale(address: &str, hint: Option<String>, locale: Option<&str>) -> EmptyResult {
let template_name = if hint.is_some() { let template_name = if hint.is_some() {
"email/pw_hint_some" "email/pw_hint_some"
} else { } else {
"email/pw_hint_none" "email/pw_hint_none"
}; };
let (subject, body_html, body_text) = get_text( let (subject, body_html, body_text) = get_text_for_locale(
template_name, template_name,
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"hint": hint, "hint": hint,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_delete_account(address: &str, user_id: &UserId) -> EmptyResult { 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 claims = generate_delete_claims(user_id.to_string())?;
let delete_token = encode_jwt(&claims); 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", "email/delete_account",
json!({ json!({
"url": CONFIG.domain(), "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(), "email": percent_encode(address.as_bytes(), NON_ALPHANUMERIC).to_string(),
"token": delete_token, "token": delete_token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_verify_email(address: &str, user_id: &UserId) -> EmptyResult { 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 claims = generate_verify_email_claims(user_id)?;
let verify_email_token = encode_jwt(&claims); 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", "email/verify_email",
json!({ json!({
"url": CONFIG.domain(), "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(), "email": percent_encode(address.as_bytes(), NON_ALPHANUMERIC).to_string(),
"token": verify_email_token, "token": verify_email_token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_register_verify_email(email: &str, token: &str) -> EmptyResult { 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(); 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"); query.query_pairs_mut().append_pair("email", email).append_pair("token", token).append_pair("fromEmail", "true");
let Some(query_string) = query.query() else { 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", "email/register_verify_email",
json!({ json!({
// `url.Url` would place the anchor `#` after the query parameters // `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(), "img_src": CONFIG._smtp_img_src(),
"email": email, "email": email,
}), }),
locale,
)?; )?;
send_email(email, &subject, body_html, body_text).await send_email(email, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_welcome(address: &str) -> EmptyResult { 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", "email/welcome",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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 claims = generate_verify_email_claims(user_id)?;
let verify_email_token = encode_jwt(&claims); 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", "email/welcome_must_verify",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -248,32 +324,49 @@ pub async fn send_welcome_must_verify(address: &str, user_id: &UserId) -> EmptyR
"user_id": user_id, "user_id": user_id,
"token": verify_email_token, "token": verify_email_token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/send_2fa_removed_from_org",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"org_name": org_name, "org_name": org_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/send_single_org_removed_from_org",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"org_name": org_name, "org_name": org_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/send_org_invite",
json!({ json!({
// `url.Url` would place the anchor `#` after the query parameters // `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(), "img_src": CONFIG._smtp_img_src(),
"org_name": org_name, "org_name": org_name,
}), }),
user.locale.as_deref(),
)?; )?;
send_email(&user.email, &subject, body_html, body_text).await send_email(&user.email, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_emergency_access_invite( pub async fn send_emergency_access_invite(
address: &str, address: &str,
user_id: UserId, user_id: UserId,
emer_id: EmergencyAccessId, emer_id: EmergencyAccessId,
grantor_name: &str, grantor_name: &str,
grantor_email: &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 { ) -> EmptyResult {
let claims = generate_emergency_access_invite_claims( let claims = generate_emergency_access_invite_claims(
user_id, user_id,
@ -365,10 +471,10 @@ pub async fn send_emergency_access_invite(
} }
let Some(query_string) = query.query() else { 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", "email/send_emergency_access_invite",
json!({ json!({
// `url.Url` would place the anchor `#` after the query parameters // `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(), "img_src": CONFIG._smtp_img_src(),
"grantor_name": grantor_name, "grantor_name": grantor_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/emergency_access_invite_accepted",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"grantee_email": grantee_email, "grantee_email": grantee_email,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/emergency_access_invite_confirmed",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"grantor_name": grantor_name, "grantor_name": grantor_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/emergency_access_recovery_approved",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"grantor_name": grantor_name, "grantor_name": grantor_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_emergency_access_recovery_initiated( pub async fn send_emergency_access_recovery_initiated(
address: &str, address: &str,
grantee_name: &str, grantee_name: &str,
atype: &str, atype: &str,
wait_time_days: &i32, wait_time_days: &i32,
) -> EmptyResult { ) -> 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", "email/emergency_access_recovery_initiated",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -435,18 +583,30 @@ pub async fn send_emergency_access_recovery_initiated(
"atype": atype, "atype": atype,
"wait_time_days": wait_time_days, "wait_time_days": wait_time_days,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_emergency_access_recovery_reminder( pub async fn send_emergency_access_recovery_reminder(
address: &str, address: &str,
grantee_name: &str, grantee_name: &str,
atype: &str, atype: &str,
days_left: &str, days_left: &str,
) -> EmptyResult { ) -> 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", "email/emergency_access_recovery_reminder",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -455,26 +615,47 @@ pub async fn send_emergency_access_recovery_reminder(
"atype": atype, "atype": atype,
"days_left": days_left, "days_left": days_left,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/emergency_access_recovery_rejected",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"grantor_name": grantor_name, "grantor_name": grantor_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/emergency_access_recovery_timed_out",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -482,13 +663,24 @@ pub async fn send_emergency_access_recovery_timed_out(address: &str, grantee_nam
"grantee_name": grantee_name, "grantee_name": grantee_name,
"atype": atype, "atype": atype,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/invite_accepted",
json!({ json!({
"url": CONFIG.domain(), "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, "email": new_user_email,
"org_name": org_name, "org_name": org_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_invite_confirmed(address: &str, org_name: &str) -> EmptyResult { 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", "email/invite_confirmed",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"org_name": org_name, "org_name": org_name,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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 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", "email/new_device_logged_in",
json!({ json!({
"url": CONFIG.domain(), "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(), "device_type": DeviceType::from_i32(device.atype).to_string(),
"datetime": crate::util::format_naive_datetime_local(dt, fmt), "datetime": crate::util::format_naive_datetime_local(dt, fmt),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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 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", "email/recover_twofactor",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -541,20 +762,33 @@ pub async fn send_recover_twofactor(address: &str, ip: &str, dt: &NaiveDateTime)
"ip": ip, "ip": ip,
"datetime": crate::util::format_naive_datetime_local(dt, fmt), "datetime": crate::util::format_naive_datetime_local(dt, fmt),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_incomplete_2fa_login( pub async fn send_incomplete_2fa_login(
address: &str, address: &str,
ip: &str, ip: &str,
dt: &NaiveDateTime, dt: &NaiveDateTime,
device_name: &str, device_name: &str,
device_type: &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 { ) -> EmptyResult {
let fmt = "%A, %B %_d, %Y at %r %Z"; 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", "email/incomplete_2fa_login",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -565,39 +799,61 @@ pub async fn send_incomplete_2fa_login(
"datetime": crate::util::format_naive_datetime_local(dt, fmt), "datetime": crate::util::format_naive_datetime_local(dt, fmt),
"time_limit": CONFIG.incomplete_2fa_time_limit(), "time_limit": CONFIG.incomplete_2fa_time_limit(),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_token(address: &str, token: &str) -> EmptyResult { 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", "email/twofactor_email",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"token": token, "token": token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_change_email(address: &str, token: &str) -> EmptyResult { 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", "email/change_email",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"token": token, "token": token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/change_email_existing",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -605,13 +861,23 @@ pub async fn send_change_email_existing(address: &str, acting_address: &str) ->
"existing_address": address, "existing_address": address,
"acting_address": acting_address, "acting_address": acting_address,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await 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 { 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", "email/change_email_invited",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -619,35 +885,49 @@ pub async fn send_change_email_invited(address: &str, acting_address: &str) -> E
"existing_address": address, "existing_address": address,
"acting_address": acting_address, "acting_address": acting_address,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_sso_change_email(address: &str) -> EmptyResult { 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", "email/sso_change_email",
json!({ json!({
"url": format!("{}/#/settings/account", CONFIG.domain()), "url": format!("{}/#/settings/account", CONFIG.domain()),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_test(address: &str) -> EmptyResult { 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", "email/smtp_test",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_admin_account_recovery( pub async fn send_admin_account_recovery(
address: &str, address: &str,
user_name: &str, user_name: &str,
@ -656,7 +936,28 @@ pub async fn send_admin_account_recovery(
reset_2fa: bool, reset_2fa: bool,
fallback_2fa_email: bool, fallback_2fa_email: bool,
) -> EmptyResult { ) -> 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", "email/admin_account_recovery",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
@ -667,18 +968,25 @@ pub async fn send_admin_account_recovery(
"reset_2fa": reset_2fa, "reset_2fa": reset_2fa,
"fallback_2fa_email": fallback_2fa_email, "fallback_2fa_email": fallback_2fa_email,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
} }
#[allow(dead_code)]
pub async fn send_protected_action_token(address: &str, token: &str) -> EmptyResult { 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", "email/protected_action",
json!({ json!({
"url": CONFIG.domain(), "url": CONFIG.domain(),
"img_src": CONFIG._smtp_img_src(), "img_src": CONFIG._smtp_img_src(),
"token": token, "token": token,
}), }),
locale,
)?; )?;
send_email(address, &subject, body_html, body_text).await send_email(address, &subject, body_html, body_text).await
@ -692,13 +1000,13 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult {
Err(e) => { Err(e) => {
if e.is_client() { if e.is_client() {
debug!("Sendmail client error: {e:?}"); 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() { } else if e.is_response() {
debug!("Sendmail response error: {e:?}"); 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:?}"); debug!("Sendmail error: {e:?}");
err!(format!("Sendmail error: {e}")); err!(i18n::mail_sendmail_error(&CONFIG.default_locale()), e.to_string());
} }
} }
} else { } else {
@ -708,10 +1016,10 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult {
Err(e) => { Err(e) => {
if e.is_client() { if e.is_client() {
debug!("SMTP client error: {e:#?}"); 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() { } else if e.is_transient() {
debug!("SMTP 4xx error: {e:#?}"); 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() { } else if e.is_permanent() {
debug!("SMTP 5xx error: {e:#?}"); debug!("SMTP 5xx error: {e:#?}");
let mut msg = e.to_string(); let mut msg = e.to_string();
@ -719,16 +1027,16 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult {
if msg.contains("(535)") { if msg.contains("(535)") {
msg = format!("{msg} - Authentication credentials invalid"); 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() { } else if e.is_timeout() {
debug!("SMTP timeout error: {e:#?}"); 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() { } else if e.is_tls() {
debug!("SMTP encryption error: {e:#?}"); 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:#?}"); debug!("SMTP error: {e:#?}");
err!(format!("SMTP error: {e}")); err!(i18n::mail_smtp_error(&CONFIG.default_locale()), e.to_string());
} }
} }
} }

5
src/main.rs

@ -56,6 +56,7 @@ mod crypto;
#[macro_use] #[macro_use]
mod db; mod db;
mod http_client; mod http_client;
mod i18n;
mod mail; mod mail;
mod ratelimit; mod ratelimit;
mod sso; mod sso;
@ -262,7 +263,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
(level, levels_override) (level, levels_override)
} else { } 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. // Depending on the main log level we either want to disable or enable logging for hickory.
@ -386,7 +387,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
} }
if let Err(err) = logger.apply() { 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 // Catch panics and log them instead of default output to StdErr

29
src/sso.rs

@ -174,10 +174,16 @@ pub fn decode_state(base64_state: &str) -> ApiResult<OIDCState> {
if let Ok(valid) = String::from_utf8(vec) { if let Ok(valid) = String::from_utf8(vec) {
OIDCState(valid) OIDCState(valid)
} else { } 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 { } 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) Ok(state)
@ -202,11 +208,14 @@ pub async fn authorize_url(
"mobile" => "bitwarden://sso-callback".to_owned(), "mobile" => "bitwarden://sso-callback".to_owned(),
"cli" => { "cli" => {
let Some(uri) = localhost_redirect_uri else { 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 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?; 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; use openidconnect::OAuth2TokenResponse;
let Some(mut sso_auth) = SsoAuth::find_by_code(code, conn).await else { 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() { if let Some(authenticated_user) = sso_auth.auth_response.clone() {
@ -274,7 +283,7 @@ pub async fn exchange_code(
} }
(None, _) => { (None, _) => {
sso_auth.delete(conn).await?; 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 user_info = client.user_info(token_response.access_token().to_owned()).await?;
let email = match id_claims.email().or(user_info.email()) { 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(), 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) { match (decode_token_claims("access_token", &auth_user.access_token), auth_user.expires_in) {
(Ok(ap), _) => (ap.nbf(), ap.exp), (Ok(ap), _) => (ap.nbf(), ap.exp),
(Err(_), Some(exp)) => (now.timestamp(), (now + exp).timestamp()), (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 = 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) { let (ap_nbf, ap_exp) = match (decode_token_claims("access_token", &access_token), expires_in) {
(Ok(ap), _) => (ap.nbf(), ap.exp), (Ok(ap), _) => (ap.nbf(), ap.exp),
(Err(_), Some(exp)) => (now.timestamp(), (now + exp).timestamp()), (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 = let access_claims =
@ -474,6 +483,6 @@ pub async fn exchange_refresh_token(
create_auth_tokens_impl(device, None, access_claims, access_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())),
} }
} }

29
src/sso_client.rs

@ -112,12 +112,14 @@ impl Client {
let issuer_url = CONFIG.sso_issuer_url()?; let issuer_url = CONFIG.sso_issuer_url()?;
let http_client = match OidcHttpClient::new() { 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, Ok(client) => client,
}; };
let provider_metadata = match CoreProviderMetadata::discover_async(issuer_url, &http_client).await { 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, Ok(metadata) => metadata,
}; };
@ -133,20 +135,20 @@ impl Client {
} else if am.contains(&CoreClientAuthMethod::ClientSecretPost) { } else if am.contains(&CoreClientAuthMethod::ClientSecretPost) {
base_client = base_client.set_auth_type(AuthType::RequestBody); base_client = base_client.set_auth_type(AuthType::RequestBody);
} else { } 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() { let token_uri = if let Some(uri) = base_client.token_uri() {
uri.clone() uri.clone()
} else { } 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() { let user_info_url = if let Some(url) = base_client.user_info_url() {
url.clone() url.clone()
} else { } 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 let core_client = base_client
@ -217,7 +219,7 @@ impl Client {
let verifier = PkceCodeVerifier::new(client_verifier.to_string()); let verifier = PkceCodeVerifier::new(client_verifier.to_string());
let challenge = PkceCodeChallenge::from_code_verifier_sha256(&verifier); let challenge = PkceCodeChallenge::from_code_verifier_sha256(&verifier);
if challenge.as_str() != &*sso_auth.client_challenge { 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(()) Ok(())
} }
@ -251,12 +253,14 @@ impl Client {
} }
match exchange.request_async(&self.http_client).await { 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) => { Ok(token_response) => {
let oidc_nonce = Nonce::new(sso_auth.nonce.clone()); let oidc_nonce = Nonce::new(sso_auth.nonce.clone());
let Some(id_token) = token_response.extra_fields().id_token() else { 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() { if CONFIG.sso_debug_tokens() {
@ -270,7 +274,10 @@ impl Client {
Ok(claims) => claims.clone(), Ok(claims) => claims.clone(),
Err(err) => { Err(err) => {
Self::invalidate(); 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<CoreUserInfoClaims> { pub async fn user_info(&self, access_token: AccessToken) -> ApiResult<CoreUserInfoClaims> {
match self.core_client.user_info(access_token, None).request_async(&self.http_client).await { 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), Ok(user_info) => Ok(user_info),
} }
} }

6
src/static/scripts/admin.js

@ -1,6 +1,8 @@
"use strict"; "use strict";
/* exported BASE_URL, _post, _delete */ /* exported BASE_URL, _post, _delete */
const tAdmin = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key;
function getBaseUrl() { function getBaseUrl() {
// If the base URL is `https://vaultwarden.example.com/base/path/admin/`, // If the base URL is `https://vaultwarden.example.com/base/path/admin/`,
// `window.location.href` should have one of the following forms: // `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) { if (respJson.errorModel && respJson.errorModel.message) {
return respJson.errorModel.message; return respJson.errorModel.message;
} else { } 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) { } 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 => { }).then(apiMsg => {
msg(`${errMsg}\n${apiMsg}`, reload_page); msg(`${errMsg}\n${apiMsg}`, reload_page);

94
src/static/scripts/admin_diagnostics.js

@ -1,6 +1,8 @@
"use strict"; "use strict";
/* global BASE_URL:readable, bootstrap:readable */ /* global BASE_URL:readable, bootstrap:readable */
const tDiag = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key;
var dnsCheck = false; var dnsCheck = false;
var timeCheck = false; var timeCheck = false;
var ntpTimeCheck = false; var ntpTimeCheck = false;
@ -80,83 +82,83 @@ async function generateSupportString(event, dj) {
event.stopPropagation(); event.stopPropagation();
// Health check Markdown emoji, if something is a failure or not // 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 // 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})` : ""; const template_overrides = dj.template_overrides !== "" ? ` (${dj.template_overrides})` : "";
let supportString = "### Your environment (Generated via diagnostics page)\n\n"; let supportString = `${tDiag("support_title")}\n\n`;
supportString += `* Vaultwarden version: v${dj.current_release}\n`; supportString += `${tDiag("vw_version")}: v${dj.current_release}\n`;
supportString += `* Web-vault version: v${dj.active_web_release}\n`; supportString += `${tDiag("web_vault_version")}: v${dj.active_web_release}\n`;
supportString += `* OS/Arch: ${dj.host_os}/${dj.host_arch}\n`; supportString += `${tDiag("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 += `${tDiag("running_container")}: ${yn(dj.running_within_container)} (Base: ${dj.container_base_image})\n`;
supportString += `* Database type: ${dj.db_type}\n`; supportString += `${tDiag("db_type")}: ${dj.db_type}\n`;
supportString += `* Database version: ${dj.db_version}\n`; supportString += `${tDiag("db_version")}: ${dj.db_version}\n`;
supportString += `* Uses config.json: ${yn(dj.config_file_status !== "NotFound")}`; 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 += 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 += `${tDiag("env_valid")}: ${chk(dj.invalid_env_vars == "")}\n`;
supportString += `* Uses custom templates: ${yn(dj.template_overrides !== "")}${template_overrides}\n`; supportString += `${tDiag("uses_custom_templates")}: ${yn(dj.template_overrides !== "")}${template_overrides}\n`;
supportString += `* Uses a reverse proxy: ${yn(dj.ip_header_exists)}\n`; supportString += `${tDiag("uses_reverse_proxy")}: ${yn(dj.ip_header_exists)}\n`;
if (dj.ip_header_exists) { 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 += `${tDiag("internet_access")}: ${chk(dj.has_http_access)}\n`;
supportString += `* Internet access via a proxy: ${yn(dj.uses_proxy)}\n`; supportString += `${tDiag("internet_access_proxy")}: ${yn(dj.uses_proxy)}\n`;
supportString += `* DNS Check: ${chk(dnsCheck)}\n`; supportString += `${tDiag("dns_check")}: ${chk(dnsCheck)}\n`;
if (dj.tz_env !== "") { 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 += `${tDiag("browser_server_time_check")}: ${chk(timeCheck)}\n`;
supportString += `* Server/NTP Time Check: ${chk(ntpTimeCheck)}\n`; supportString += `${tDiag("server_ntp_time_check")}: ${chk(ntpTimeCheck)}\n`;
supportString += `* Domain Configuration Check: ${chk(domainCheck)}\n`; supportString += `${tDiag("domain_check")}: ${chk(domainCheck)}\n`;
supportString += `* HTTPS Check: ${chk(httpsCheck)}\n`; supportString += `${tDiag("https_check")}: ${chk(httpsCheck)}\n`;
if (dj.enable_websocket) { if (dj.enable_websocket) {
supportString += `* Websocket Check: ${chk(websocketCheck)}\n`; supportString += `${tDiag("websocket_check")}: ${chk(websocketCheck)}\n`;
} else { } 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 != "") { 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`, { const jsonResponse = await fetch(`${BASE_URL}/admin/diagnostics/config`, {
"headers": { "Accept": "application/json" } "headers": { "Accept": "application/json" }
}); });
if (!jsonResponse.ok) { if (!jsonResponse.ok) {
alert("Generation failed: " + jsonResponse.statusText); alert(`${tDiag("generation_failed_prefix")} ${jsonResponse.statusText}`);
throw new Error(jsonResponse); throw new Error(jsonResponse);
} }
const configJson = await jsonResponse.json(); const configJson = await jsonResponse.json();
// Start Config and Details section within a details block which is collapsed by default // 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 += `\n${tDiag("support_details_title")}\n\n`;
supportString += "<details><summary>Show Config & Details</summary>\n"; supportString += `${tDiag("support_details_summary")}\n`;
// Show invalid environment variables if they exists // Show invalid environment variables if they exists
if (dj.invalid_env_vars != "") { 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 // Add overrides if they exists
if (dj.overrides != "") { 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 != "") { 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 // Add http response check messages if they exists
if (httpResponseCheck === false) { if (httpResponseCheck === false) {
supportString += "\n**Failed HTTP Checks:**\n"; supportString += `\n${tDiag("failed_http_checks")}\n`;
// We use `innerText` here since that will convert <br> into new-lines // We use `innerText` here since that will convert <br> into new-lines
supportString += "\n```yaml\n" + document.getElementById("http-response-errors").innerText.trim() + "\n```\n"; supportString += "\n```yaml\n" + document.getElementById("http-response-errors").innerText.trim() + "\n```\n";
} }
// Add the current config in json form // 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```json\n" + JSON.stringify(configJson, undefined, 2) + "\n```\n";
supportString += "\n</details>\n"; supportString += "\n</details>\n";
@ -314,9 +316,9 @@ async function checkHttpResponse() {
// Check and validate the default API header responses // Check and validate the default API header responses
let apiErrors = checkSecurityHeaders(apiConfig.headers); let apiErrors = checkSecurityHeaders(apiConfig.headers);
if (apiErrors.length >= 1) { if (apiErrors.length >= 1) {
respErrorElm.innerHTML += "<b>API calls:</b><br>"; respErrorElm.innerHTML += `<b>${tDiag("api_calls")}:</b><br>`;
apiErrors.forEach((errMsg) => { apiErrors.forEach((errMsg) => {
respErrorElm.innerHTML += `<b>Header:</b> ${errMsg}<br>`; respErrorElm.innerHTML += `<b>${tDiag("header_prefix")}:</b> ${errMsg}<br>`;
}); });
} }
@ -329,38 +331,38 @@ async function checkHttpResponse() {
} }
}); });
if (connectorErrors.length >= 1) { if (connectorErrors.length >= 1) {
respErrorElm.innerHTML += "<b>2FA Connector calls:</b><br>"; respErrorElm.innerHTML += `<b>${tDiag("connector_calls")}:</b><br>`;
connectorErrors.forEach((errMsg) => { connectorErrors.forEach((errMsg) => {
respErrorElm.innerHTML += `<b>Header:</b> ${errMsg}<br>`; respErrorElm.innerHTML += `<b>${tDiag("header_prefix")}:</b> ${errMsg}<br>`;
}); });
} }
// Check specific error code responses if they are not re-written by a reverse proxy // Check specific error code responses if they are not re-written by a reverse proxy
let responseErrors = []; let responseErrors = [];
if (notFound.status !== 404 || notFound.text.indexOf("return to the web-vault") === -1) { 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) { 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) { 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) { 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) { 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) { if (responseErrors.length >= 1) {
respErrorElm.innerHTML += "<b>HTTP error responses:</b><br>"; respErrorElm.innerHTML += `<b>${tDiag("http_error_responses")}:</b><br>`;
responseErrors.forEach((errMsg) => { responseErrors.forEach((errMsg) => {
respErrorElm.innerHTML += `<b>Response to:</b> ${errMsg}<br>`; respErrorElm.innerHTML += `<b>${tDiag("response_to_prefix")}:</b> ${errMsg}<br>`;
}); });
} }

54
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.
}
}
})();
})();

43
src/static/scripts/admin_organizations.js

@ -1,6 +1,8 @@
"use strict"; "use strict";
/* global DataTable, _post:readable, BASE_URL:readable, reload:readable, jdenticon:readable */ /* 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) { function deleteOrganization(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
@ -8,22 +10,22 @@ function deleteOrganization(event) {
const org_name = event.target.dataset.vwOrgName; const org_name = event.target.dataset.vwOrgName;
const billing_email = event.target.dataset.vwBillingEmail; const billing_email = event.target.dataset.vwBillingEmail;
if (!org_uuid) { if (!org_uuid) {
alert("Required parameters not found!"); alert(tOrgs("required_params_not_found"));
return false; return false;
} }
// First make sure the user wants to delete this organization // 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) { 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 != null) {
if (input_org_uuid == org_uuid) { if (input_org_uuid == org_uuid) {
_post(`${BASE_URL}/admin/organizations/${org_uuid}/delete`, _post(`${BASE_URL}/admin/organizations/${org_uuid}/delete`,
"Organization deleted correctly", tOrgs("org_delete_ok"),
"Error deleting organization" tOrgs("org_delete_error")
); );
} else { } else {
alert("Wrong organization uuid, please try again"); alert(tOrgs("wrong_org_uuid_retry"));
} }
} }
} }
@ -40,17 +42,42 @@ function initActions() {
} }
// onLoad events // 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; const columnCount = document.getElementById("orgs-table").querySelectorAll("thead th").length;
new DataTable("#orgs-table", { new DataTable("#orgs-table", {
"drawCallback": function () { "drawCallback": function () {
initActions(); 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, "stateSave": true,
"responsive": true, "responsive": true,
"lengthMenu": [ "lengthMenu": [
[-1, 5, 10, 25, 50], [-1, 5, 10, 25, 50],
["All", 5, 10, 25, 50] [tOrgs("datatable_all"), 5, 10, 25, 50]
], ],
"pageLength": -1, // Default show all "pageLength": -1, // Default show all
"columnDefs": [{ "columnDefs": [{

28
src/static/scripts/admin_settings.js

@ -1,11 +1,13 @@
"use strict"; "use strict";
/* global _post:readable, BASE_URL:readable */ /* global _post:readable, BASE_URL:readable */
const tSettings = key => (window.VW_ADMIN_I18N && window.VW_ADMIN_I18N[key]) || key;
function smtpTest(event) { function smtpTest(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (formHasChanges(config_form)) { 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; return false;
} }
@ -19,8 +21,8 @@ function smtpTest(event) {
const data = JSON.stringify({ "email": test_email.value }); const data = JSON.stringify({ "email": test_email.value });
_post(`${BASE_URL}/admin/test/smtp`, _post(`${BASE_URL}/admin/test/smtp`,
"SMTP Test email sent correctly", tSettings("smtp_test_ok"),
"Error sending SMTP test email", tSettings("smtp_test_error"),
data, false data, false
); );
} }
@ -45,8 +47,8 @@ function getFormData() {
function saveConfig(event) { function saveConfig(event) {
const data = JSON.stringify(getFormData()); const data = JSON.stringify(getFormData());
_post(`${BASE_URL}/admin/config`, _post(`${BASE_URL}/admin/config`,
"Config saved correctly", tSettings("config_save_ok"),
"Error saving config", tSettings("config_save_error"),
data data
); );
event.preventDefault(); event.preventDefault();
@ -56,16 +58,15 @@ function deleteConf(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const input = prompt( const input = prompt(
"This will remove all user configurations, and restore the defaults and the " + tSettings("delete_config_prompt")
"values set by the environment. This operation could be dangerous. Type 'DELETE' to proceed:"
); );
if (input === "DELETE") { if (input === "DELETE") {
_post(`${BASE_URL}/admin/config/delete`, _post(`${BASE_URL}/admin/config/delete`,
"Config deleted correctly", tSettings("config_delete_ok"),
"Error deleting config" tSettings("config_delete_error")
); );
} else { } else {
alert("Wrong input, please try again"); alert(tSettings("wrong_input_retry"));
} }
} }
@ -73,8 +74,8 @@ function backupDatabase(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
_post(`${BASE_URL}/admin/config/backup_db`, _post(`${BASE_URL}/admin/config/backup_db`,
"Backup created successfully", tSettings("backup_create_ok"),
"Error creating backup", null, false tSettings("backup_create_error"), null, false
); );
} }
@ -121,7 +122,8 @@ function submitTestEmailOnEnter() {
function colorRiskSettings() { function colorRiskSettings() {
const risk_items = document.getElementsByClassName("col-form-label"); const risk_items = document.getElementsByClassName("col-form-label");
Array.from(risk_items).forEach((el) => { 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"; el.parentElement.className += " alert-danger";
} }
}); });

111
src/static/scripts/admin_users.js

@ -1,24 +1,26 @@
"use strict"; "use strict";
/* global DataTable, _post:readable, _delete:readable, BASE_URL:readable, reload:readable, jdenticon:readable */ /* 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) { function deleteUser(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const id = event.target.parentNode.dataset.vwUserUuid; const id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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 != null) {
if (input_email == email) { if (input_email == email) {
_post(`${BASE_URL}/admin/users/${id}/delete`, _post(`${BASE_URL}/admin/users/${id}/delete`,
"User deleted correctly", tUsers("user_deleted_ok"),
"Error deleting user" tUsers("user_deleted_error")
); );
} else { } 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 id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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 != null) {
if (input_email == email) { if (input_email == email) {
_delete(`${BASE_URL}/admin/users/${id}/sso`, _delete(`${BASE_URL}/admin/users/${id}/sso`,
"User SSO association deleted correctly", tUsers("user_sso_deleted_ok"),
"Error deleting user SSO association" tUsers("user_sso_deleted_error")
); );
} else { } 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 id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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) { if (confirmed) {
_post(`${BASE_URL}/admin/users/${id}/remove-2fa`, _post(`${BASE_URL}/admin/users/${id}/remove-2fa`,
"2FA removed correctly", tUsers("remove_2fa_ok"),
"Error removing 2FA" tUsers("remove_2fa_error")
); );
} }
} }
@ -69,14 +71,14 @@ function deauthUser(event) {
const id = event.target.parentNode.dataset.vwUserUuid; const id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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) { if (confirmed) {
_post(`${BASE_URL}/admin/users/${id}/deauth`, _post(`${BASE_URL}/admin/users/${id}/deauth`,
"Sessions deauthorized correctly", tUsers("deauth_ok"),
"Error deauthorizing sessions" tUsers("deauth_error")
); );
} }
} }
@ -87,14 +89,14 @@ function disableUser(event) {
const id = event.target.parentNode.dataset.vwUserUuid; const id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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) { if (confirmed) {
_post(`${BASE_URL}/admin/users/${id}/disable`, _post(`${BASE_URL}/admin/users/${id}/disable`,
"User disabled successfully", tUsers("user_disable_ok"),
"Error disabling user" tUsers("user_disable_error")
); );
} }
} }
@ -105,14 +107,14 @@ function enableUser(event) {
const id = event.target.parentNode.dataset.vwUserUuid; const id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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) { if (confirmed) {
_post(`${BASE_URL}/admin/users/${id}/enable`, _post(`${BASE_URL}/admin/users/${id}/enable`,
"User enabled successfully", tUsers("user_enable_ok"),
"Error enabling user" tUsers("user_enable_error")
); );
} }
} }
@ -121,8 +123,8 @@ function updateRevisions(event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
_post(`${BASE_URL}/admin/users/update_revision`, _post(`${BASE_URL}/admin/users/update_revision`,
"Success, clients will sync next time they connect", tUsers("sync_clients_ok"),
"Error forcing clients to sync" tUsers("sync_clients_error")
); );
} }
@ -135,8 +137,8 @@ function inviteUser(event) {
}); });
email.value = ""; email.value = "";
_post(`${BASE_URL}/admin/invite`, _post(`${BASE_URL}/admin/invite`,
"User invited correctly", tUsers("invite_user_ok"),
"Error inviting user", tUsers("invite_user_error"),
data data
); );
} }
@ -147,34 +149,34 @@ function resendUserInvite(event) {
const id = event.target.parentNode.dataset.vwUserUuid; const id = event.target.parentNode.dataset.vwUserUuid;
const email = event.target.parentNode.dataset.vwUserEmail; const email = event.target.parentNode.dataset.vwUserEmail;
if (!id || !email) { if (!id || !email) {
alert("Required parameters not found!"); alert(tUsers("required_params_not_found"));
return false; 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) { if (confirmed) {
_post(`${BASE_URL}/admin/users/${id}/invite/resend`, _post(`${BASE_URL}/admin/users/${id}/invite/resend`,
"Invite sent successfully", tUsers("resend_invite_ok"),
"Error resend invite" tUsers("resend_invite_error")
); );
} }
} }
const ORG_TYPES = { const ORG_TYPES = {
"0": { "0": {
"name": "Owner", "name": tUsers("role_owner"),
"bg": "orange", "bg": "orange",
"font": "black" "font": "black"
}, },
"1": { "1": {
"name": "Admin", "name": tUsers("role_admin"),
"bg": "blueviolet" "bg": "blueviolet"
}, },
"2": { "2": {
"name": "User", "name": tUsers("role_user"),
"bg": "blue" "bg": "blue"
}, },
"4": { "4": {
"name": "Manager", "name": tUsers("role_manager"),
"bg": "green" "bg": "green"
}, },
}; };
@ -213,8 +215,8 @@ function updateUserOrgType(event) {
const data = JSON.stringify(Object.fromEntries(new FormData(event.target).entries())); const data = JSON.stringify(Object.fromEntries(new FormData(event.target).entries()));
_post(`${BASE_URL}/admin/users/org_type`, _post(`${BASE_URL}/admin/users/org_type`,
"Updated organization type of the user successfully", tUsers("user_org_type_update_ok"),
"Error updating organization type of the user", tUsers("user_org_type_update_error"),
data data
); );
} }
@ -276,7 +278,11 @@ DataTable.ext.type.order["date-iso-pre"] = function (a) {
}; };
// onLoad events // 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) { DataTable.ext.type.detect.unshift(function (data) {
if (typeof data !== "string") { return null; } if (typeof data !== "string") { return null; }
return data.indexOf("data-sort-type=\"date-iso\"") !== -1 return data.indexOf("data-sort-type=\"date-iso\"") !== -1
@ -290,11 +296,32 @@ document.addEventListener("DOMContentLoaded", (/*event*/) => {
"drawCallback": function () { "drawCallback": function () {
initUserTable(); 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, "stateSave": true,
"responsive": true, "responsive": true,
"lengthMenu": [ "lengthMenu": [
[-1, 2, 5, 10, 25, 50], [-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 "pageLength": -1, // Default show all
"columnDefs": [{ "columnDefs": [{

16
src/static/templates/404.hbs

@ -1,11 +1,11 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="{{#if lang}}{{lang}}{{else}}en{{/if}}">
<head> <head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="robots" content="noindex,nofollow" /> <meta name="robots" content="noindex,nofollow" />
<link rel="icon" type="image/png" href="{{urlpath}}/vw_static/vaultwarden-favicon.png"> <link rel="icon" type="image/png" href="{{urlpath}}/vw_static/vaultwarden-favicon.png">
<title>Page not found!</title> <title>{{t "web.404.title" locale=lang}}</title>
<link rel="stylesheet" href="{{urlpath}}/vw_static/bootstrap.css" /> <link rel="stylesheet" href="{{urlpath}}/vw_static/bootstrap.css" />
<link rel="stylesheet" href="{{urlpath}}/vw_static/404.css" /> <link rel="stylesheet" href="{{urlpath}}/vw_static/404.css" />
</head> </head>
@ -16,7 +16,7 @@
<div class="container"> <div class="container">
<a class="navbar-brand" href="{{urlpath}}/"><img class="vaultwarden-icon" src="{{urlpath}}/vw_static/vaultwarden-icon.png" alt="V">aultwarden</a> <a class="navbar-brand" href="{{urlpath}}/"><img class="vaultwarden-icon" src="{{urlpath}}/vw_static/vaultwarden-icon.png" alt="V">aultwarden</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarCollapse" aria-expanded="false" aria-label="{{t "web.404.toggle_navigation" locale=lang}}">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarCollapse"> <div class="collapse navbar-collapse" id="navbarCollapse">
@ -26,13 +26,13 @@
</nav> </nav>
<main class="container inner content text-center"> <main class="container inner content text-center">
<h2>Page not found!</h2> <h2>{{t "web.404.title" locale=lang}}</h2>
<p class="lead">Sorry, but the page you were looking for could not be found.</p> <p class="lead">{{t "web.404.lead" locale=lang}}</p>
<p class="display-6"> <p class="display-6">
<a href="{{urlpath}}/"><img class="vw-404" src="{{urlpath}}/vw_static/404.png" alt="Return to the web vault?"></a></p> <a href="{{urlpath}}/"><img class="vw-404" src="{{urlpath}}/vw_static/404.png" alt="{{t "web.404.return_alt" locale=lang}}"></a></p>
<p>You can <a href="{{urlpath}}/">return to the web-vault</a>, or <a href="https://github.com/dani-garcia/vaultwarden">contact us</a>.</p> <p>{{t "web.404.prefix" locale=lang}} <a href="{{urlpath}}/">{{t "web.404.return_link" locale=lang}}</a>, {{t "web.404.or" locale=lang}} <a href="https://github.com/dani-garcia/vaultwarden">{{t "web.404.contact_link" locale=lang}}</a>.</p>
</main> </main>
<div class="container footer text-muted content">Vaultwarden (unofficial Bitwarden&reg; server)</div> <div class="container footer text-muted content">{{t "web.404.footer" locale=lang}}</div>
</body> </body>
</html> </html>

31
src/static/templates/admin/base.hbs

@ -1,13 +1,14 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" data-bs-theme="auto"> <html lang="{{#if lang}}{{lang}}{{else}}en{{/if}}" data-bs-theme="auto">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex,nofollow" /> <meta name="robots" content="noindex,nofollow" />
<link rel="icon" type="image/png" href="{{urlpath}}/vw_static/vaultwarden-favicon.png"> <link rel="icon" type="image/png" href="{{urlpath}}/vw_static/vaultwarden-favicon.png">
<title>Vaultwarden Admin Panel</title> <title>{{t "tpl.admin.base.title" locale=lang}}</title>
<link rel="stylesheet" href="{{urlpath}}/vw_static/bootstrap.css" /> <link rel="stylesheet" href="{{urlpath}}/vw_static/bootstrap.css" />
<link rel="stylesheet" href="{{urlpath}}/vw_static/admin.css" /> <link rel="stylesheet" href="{{urlpath}}/vw_static/admin.css" />
<script src="{{urlpath}}/vw_static/admin_i18n_loader.js"></script>
<script src="{{urlpath}}/vw_static/admin.js"></script> <script src="{{urlpath}}/vw_static/admin.js"></script>
</head> </head>
<body> <body>
@ -28,29 +29,29 @@
</svg> </svg>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4 shadow fixed-top"> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4 shadow fixed-top">
<div class="container-xxl"> <div class="container-xxl">
<a class="navbar-brand" href="{{urlpath}}/admin"><img class="vaultwarden-icon" src="{{urlpath}}/vw_static/vaultwarden-icon.png" alt="V">aultwarden Admin</a> <a class="navbar-brand" href="{{urlpath}}/admin"><img class="vaultwarden-icon" src="{{urlpath}}/vw_static/vaultwarden-icon.png" alt="V">{{t "tpl.admin.base.brand_admin" locale=lang}}</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarCollapse" aria-expanded="false" aria-label="{{t "tpl.admin.base.toggle_navigation" locale=lang}}">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarCollapse"> <div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto"> <ul class="navbar-nav me-auto">
{{#if logged_in}} {{#if logged_in}}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{urlpath}}/admin">Settings</a> <a class="nav-link" href="{{urlpath}}/admin">{{t "tpl.admin.base.nav.settings" locale=lang}}</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{urlpath}}/admin/users/overview">Users</a> <a class="nav-link" href="{{urlpath}}/admin/users/overview">{{t "tpl.admin.base.nav.users" locale=lang}}</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{urlpath}}/admin/organizations/overview">Organizations</a> <a class="nav-link" href="{{urlpath}}/admin/organizations/overview">{{t "tpl.admin.base.nav.organizations" locale=lang}}</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{urlpath}}/admin/diagnostics">Diagnostics</a> <a class="nav-link" href="{{urlpath}}/admin/diagnostics">{{t "tpl.admin.base.nav.diagnostics" locale=lang}}</a>
</li> </li>
{{/if}} {{/if}}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{urlpath}}/" target="_blank" rel="noreferrer">Vault</a> <a class="nav-link" href="{{urlpath}}/" target="_blank" rel="noreferrer">{{t "tpl.admin.base.nav.vault" locale=lang}}</a>
</li> </li>
</ul> </ul>
@ -59,13 +60,13 @@
<button <button
class="btn btn-link nav-link py-0 px-0 px-md-2 dropdown-toggle d-flex align-items-center" class="btn btn-link nav-link py-0 px-0 px-md-2 dropdown-toggle d-flex align-items-center"
id="bd-theme" type="button" aria-expanded="false" data-bs-toggle="dropdown" id="bd-theme" type="button" aria-expanded="false" data-bs-toggle="dropdown"
data-bs-display="static" aria-label="Toggle theme (auto)"> data-bs-display="static" aria-label="{{t "tpl.admin.base.theme.auto_label" locale=lang}}">
<span class="my-1 fs-4 theme-icon-active"> <span class="my-1 fs-4 theme-icon-active">
<svg class="vw-theme-icon" focusable="false" aria-hidden="true"> <svg class="vw-theme-icon" focusable="false" aria-hidden="true">
<use data-theme-icon-use href="#vw-icon-auto"></use> <use data-theme-icon-use href="#vw-icon-auto"></use>
</svg> </svg>
</span> </span>
<span class="d-md-none ms-2" id="bd-theme-text">Toggle theme</span> <span class="d-md-none ms-2" id="bd-theme-text">{{t "tpl.admin.base.theme.toggle" locale=lang}}</span>
</button> </button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="bd-theme-text"> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="bd-theme-text">
<li> <li>
@ -76,7 +77,7 @@
<use data-theme-icon-use href="#vw-icon-sun"></use> <use data-theme-icon-use href="#vw-icon-sun"></use>
</svg> </svg>
</span> </span>
Light {{t "tpl.admin.base.theme.light" locale=lang}}
</button> </button>
</li> </li>
<li> <li>
@ -87,7 +88,7 @@
<use data-theme-icon-use href="#vw-icon-moon"></use> <use data-theme-icon-use href="#vw-icon-moon"></use>
</svg> </svg>
</span> </span>
Dark {{t "tpl.admin.base.theme.dark" locale=lang}}
</button> </button>
</li> </li>
<li> <li>
@ -98,7 +99,7 @@
<use data-theme-icon-use href="#vw-icon-auto"></use> <use data-theme-icon-use href="#vw-icon-auto"></use>
</svg> </svg>
</span> </span>
Auto {{t "tpl.admin.base.theme.auto" locale=lang}}
</button> </button>
</li> </li>
</ul> </ul>
@ -106,7 +107,7 @@
</ul> </ul>
{{#if logged_in}} {{#if logged_in}}
<a class="btn btn-sm btn-secondary" href="{{urlpath}}/admin/logout">Log Out</a> <a class="btn btn-sm btn-secondary" href="{{urlpath}}/admin/logout">{{t "tpl.admin.base.logout" locale=lang}}</a>
{{/if}} {{/if}}
</div> </div>

192
src/static/templates/admin/diagnostics.hbs

@ -1,48 +1,48 @@
<main class="container-xxl"> <main class="container-xxl">
<div id="diagnostics-block" class="my-3 p-3 rounded shadow"> <div id="diagnostics-block" class="my-3 p-3 rounded shadow">
<h6 class="border-bottom pb-2 mb-2">Diagnostics</h6> <h6 class="border-bottom pb-2 mb-2">{{t "tpl.admin.diag.title" locale=@root.lang}}</h6>
<h3>Versions</h3> <h3>{{t "tpl.admin.diag.versions" locale=@root.lang}}</h3>
<div class="row"> <div class="row">
<div class="col-md"> <div class="col-md">
<dl class="row"> <dl class="row">
<dt class="col-sm-5">Server Installed <dt class="col-sm-5">{{t "tpl.admin.diag.server_installed" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="server-success" title="Latest version is installed.">Ok</span> <span class="badge bg-success d-none abbr-badge" id="server-success" title="{{t "tpl.admin.diag.title_latest_installed" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
<span class="badge bg-warning text-dark d-none abbr-badge" id="server-warning" title="An update is available.">Update</span> <span class="badge bg-warning text-dark d-none abbr-badge" id="server-warning" title="{{t "tpl.admin.diag.title_update_available" locale=@root.lang}}">{{t "tpl.admin.diag.update" locale=@root.lang}}</span>
<span class="badge bg-info text-dark d-none abbr-badge" id="server-branch" title="This is a branched version.">Branched</span> <span class="badge bg-info text-dark d-none abbr-badge" id="server-branch" title="{{t "tpl.admin.diag.title_branched_version" locale=@root.lang}}">{{t "tpl.admin.diag.branched" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="server-installed">{{page_data.current_release}}</span> <span id="server-installed">{{page_data.current_release}}</span>
</dd> </dd>
<dt class="col-sm-5">Server Latest <dt class="col-sm-5">{{t "tpl.admin.diag.server_latest" locale=@root.lang}}
<span class="badge bg-secondary d-none abbr-badge" id="server-failed" title="Unable to determine latest version.">Unknown</span> <span class="badge bg-secondary d-none abbr-badge" id="server-failed" title="{{t "tpl.admin.diag.title_unable_latest" locale=@root.lang}}">{{t "tpl.admin.diag.unknown" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="server-latest">{{page_data.latest_release}}<span id="server-latest-commit" class="d-none">-{{page_data.latest_commit}}</span></span> <span id="server-latest">{{page_data.latest_release}}<span id="server-latest-commit" class="d-none">-{{page_data.latest_commit}}</span></span>
</dd> </dd>
{{#if page_data.web_vault_enabled}} {{#if page_data.web_vault_enabled}}
<dt class="col-sm-5">Web Installed <dt class="col-sm-5">{{t "tpl.admin.diag.web_installed" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="web-success" title="Latest version is installed.">Ok</span> <span class="badge bg-success d-none abbr-badge" id="web-success" title="{{t "tpl.admin.diag.title_latest_installed" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
<span class="badge bg-warning text-dark d-none abbr-badge" id="web-warning" title="An update is available.">Update</span> <span class="badge bg-warning text-dark d-none abbr-badge" id="web-warning" title="{{t "tpl.admin.diag.title_update_available" locale=@root.lang}}">{{t "tpl.admin.diag.update" locale=@root.lang}}</span>
<span class="badge bg-info text-dark d-none abbr-badge" id="web-prerelease" title="You are using a pre-release version.">Pre-Release</span> <span class="badge bg-info text-dark d-none abbr-badge" id="web-prerelease" title="{{t "tpl.admin.diag.title_prerelease" locale=@root.lang}}">{{t "tpl.admin.diag.prerelease" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="web-installed">{{page_data.active_web_release}}</span> <span id="web-installed">{{page_data.active_web_release}}</span>
</dd> </dd>
<dt class="col-sm-5">Web Latest <dt class="col-sm-5">{{t "tpl.admin.diag.web_latest" locale=@root.lang}}
<span class="badge bg-secondary d-none abbr-badge" id="web-failed" title="Unable to determine latest version.">Unknown</span> <span class="badge bg-secondary d-none abbr-badge" id="web-failed" title="{{t "tpl.admin.diag.title_unable_latest" locale=@root.lang}}">{{t "tpl.admin.diag.unknown" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="web-latest">{{page_data.latest_web_release}}</span> <span id="web-latest">{{page_data.latest_web_release}}</span>
</dd> </dd>
{{/if}} {{/if}}
{{#unless page_data.web_vault_enabled}} {{#unless page_data.web_vault_enabled}}
<dt class="col-sm-5">Web Installed</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.web_installed" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="web-installed">Web Vault is disabled</span> <span id="web-installed">{{t "tpl.admin.diag.web_disabled" locale=@root.lang}}</span>
</dd> </dd>
{{/unless}} {{/unless}}
<dt class="col-sm-5">Database</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.database" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span><b>{{page_data.db_type}}:</b> {{page_data.db_version}}</span> <span><b>{{page_data.db_type}}:</b> {{page_data.db_version}}</span>
</dd> </dd>
@ -50,211 +50,211 @@
</div> </div>
</div> </div>
<h3>Checks</h3> <h3>{{t "tpl.admin.diag.checks" locale=@root.lang}}</h3>
<div class="row"> <div class="row">
<div class="col-md"> <div class="col-md">
<dl class="row"> <dl class="row">
<dt class="col-sm-5">OS/Arch</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.os_arch" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span class="d-block"><b>{{ page_data.host_os }} / {{ page_data.host_arch }}</b></span> <span class="d-block"><b>{{ page_data.host_os }} / {{ page_data.host_arch }}</b></span>
</dd> </dd>
<dt class="col-sm-5">Running within a container</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.running_container" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.running_within_container}} {{#if page_data.running_within_container}}
<span class="d-block"><b>Yes (Base: {{ page_data.container_base_image }})</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}} ({{t "tpl.admin.diag.base" locale=@root.lang}}: {{ page_data.container_base_image }})</b></span>
{{/if}} {{/if}}
{{#unless page_data.running_within_container}} {{#unless page_data.running_within_container}}
<span class="d-block"><b>No</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">Uses config.json</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.uses_config_json" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if (eq page_data.config_file_status "Loaded")}} {{#if (eq page_data.config_file_status "Loaded")}}
<span class="d-inline"><b>Yes</b></span> <span class="d-inline"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{#if page_data.overrides}} {{#if page_data.overrides}}
<span class="badge bg-info text-dark abbr-badge" title="Environment variables are overwritten by a config.json.&#013;&#010;{{page_data.overrides}}">Details</span> <span class="badge bg-info text-dark abbr-badge" title="{{t "tpl.admin.diag.title_env_overwritten" locale=@root.lang}}&#013;&#010;{{page_data.overrides}}">{{t "tpl.admin.diag.details" locale=@root.lang}}</span>
{{/if}} {{/if}}
{{~else if (eq page_data.config_file_status "Error")}} {{~else if (eq page_data.config_file_status "Error")}}
<span class="d-inline"><b>Errors</b></span> <span class="d-inline"><b>{{t "tpl.admin.diag.errors" locale=@root.lang}}</b></span>
<span class="badge bg-danger abbr-badge" title="Config file could not be loaded and was ignored. Check server logs for details.">Details</span> <span class="badge bg-danger abbr-badge" title="{{t "tpl.admin.diag.title_config_load_error" locale=@root.lang}}">{{t "tpl.admin.diag.details" locale=@root.lang}}</span>
{{~else}} {{~else}}
<span class="d-inline"><b>No</b></span> <span class="d-inline"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/if}} {{/if}}
</dd> </dd>
<dt class="col-sm-5">Environment variables are valid</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.env_valid" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.invalid_env_vars}} {{#if page_data.invalid_env_vars}}
<span class="d-inline"><b>No</b></span> <span class="d-inline"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
<span class="badge bg-danger abbr-badge" title="Invalid environment variables are found and defaults are used instead.&#013;&#010;{{page_data.invalid_env_vars}}">Details</span> <span class="badge bg-danger abbr-badge" title="{{t "tpl.admin.diag.title_invalid_env_vars" locale=@root.lang}}&#013;&#010;{{page_data.invalid_env_vars}}">{{t "tpl.admin.diag.details" locale=@root.lang}}</span>
{{/if}} {{/if}}
{{#unless page_data.invalid_env_vars}} {{#unless page_data.invalid_env_vars}}
<span class="d-block"><b>Yes</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">Uses custom templates</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.uses_custom_templates" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.template_overrides}} {{#if page_data.template_overrides}}
<span class="d-inline"><b>Yes</b></span> <span class="d-inline"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
<span class="badge bg-info text-dark abbr-badge" title="Custom template files are used.&#013;&#010;{{page_data.template_overrides}}">Details</span> <span class="badge bg-info text-dark abbr-badge" title="{{t "tpl.admin.diag.title_custom_templates" locale=@root.lang}}&#013;&#010;{{page_data.template_overrides}}">{{t "tpl.admin.diag.details" locale=@root.lang}}</span>
{{/if}} {{/if}}
{{#unless page_data.template_overrides}} {{#unless page_data.template_overrides}}
<span class="d-block"><b>No</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">Uses a reverse proxy</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.uses_reverse_proxy" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.ip_header_exists}} {{#if page_data.ip_header_exists}}
<span class="d-block" title="IP Header found."><b>Yes</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_ip_header_found" locale=@root.lang}}"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{/if}} {{/if}}
{{#unless page_data.ip_header_exists}} {{#unless page_data.ip_header_exists}}
<span class="d-block" title="No IP Header found."><b>No</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_ip_header_not_found" locale=@root.lang}}"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
{{!-- Only show this if the IP Header Exists --}} {{!-- Only show this if the IP Header Exists --}}
{{#if page_data.ip_header_exists}} {{#if page_data.ip_header_exists}}
<dt class="col-sm-5">IP header <dt class="col-sm-5">{{t "tpl.admin.diag.ip_header" locale=@root.lang}}
{{#if page_data.ip_header_match}} {{#if page_data.ip_header_match}}
<span class="badge bg-success abbr-badge" title="IP_HEADER config seems to be valid.">Match</span> <span class="badge bg-success abbr-badge" title="{{t "tpl.admin.diag.title_ip_header_valid" locale=@root.lang}}">{{t "tpl.admin.diag.match" locale=@root.lang}}</span>
{{/if}} {{/if}}
{{#unless page_data.ip_header_match}} {{#unless page_data.ip_header_match}}
<span class="badge bg-danger abbr-badge" title="IP_HEADER config seems to be invalid. IP's in the log could be invalid. Please fix.">No Match</span> <span class="badge bg-danger abbr-badge" title="{{t "tpl.admin.diag.title_ip_header_invalid" locale=@root.lang}}">{{t "tpl.admin.diag.no_match" locale=@root.lang}}</span>
{{/unless}} {{/unless}}
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.ip_header_match}} {{#if page_data.ip_header_match}}
<span class="d-block"><b>Config/Server:</b> {{ page_data.ip_header_name }}</span> <span class="d-block"><b>{{t "tpl.admin.diag.config_server" locale=@root.lang}}</b> {{ page_data.ip_header_name }}</span>
{{/if}} {{/if}}
{{#unless page_data.ip_header_match}} {{#unless page_data.ip_header_match}}
<span class="d-block"><b>Config:</b> {{ page_data.ip_header_config }}</span> <span class="d-block"><b>{{t "tpl.admin.diag.config" locale=@root.lang}}</b> {{ page_data.ip_header_config }}</span>
<span class="d-block"><b>Server:</b> {{ page_data.ip_header_name }}</span> <span class="d-block"><b>{{t "tpl.admin.diag.server" locale=@root.lang}}</b> {{ page_data.ip_header_name }}</span>
{{/unless}} {{/unless}}
</dd> </dd>
{{/if}} {{/if}}
{{!-- End if IP Header Exists --}} {{!-- End if IP Header Exists --}}
<dt class="col-sm-5">Internet access <dt class="col-sm-5">{{t "tpl.admin.diag.internet_access" locale=@root.lang}}
{{#if page_data.has_http_access}} {{#if page_data.has_http_access}}
<span class="badge bg-success abbr-badge" title="We have internet access!">Ok</span> <span class="badge bg-success abbr-badge" title="{{t "tpl.admin.diag.title_internet_ok" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
{{/if}} {{/if}}
{{#unless page_data.has_http_access}} {{#unless page_data.has_http_access}}
<span class="badge bg-danger abbr-badge" title="There seems to be no internet access. Please fix.">Error</span> <span class="badge bg-danger abbr-badge" title="{{t "tpl.admin.diag.title_internet_error" locale=@root.lang}}">{{t "tpl.admin.diag.error" locale=@root.lang}}</span>
{{/unless}} {{/unless}}
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.has_http_access}} {{#if page_data.has_http_access}}
<span class="d-block"><b>Yes</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{/if}} {{/if}}
{{#unless page_data.has_http_access}} {{#unless page_data.has_http_access}}
<span class="d-block"><b>No</b></span> <span class="d-block"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">Internet access via a proxy</dt> <dt class="col-sm-5">{{t "tpl.admin.diag.internet_via_proxy" locale=@root.lang}}</dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.uses_proxy}} {{#if page_data.uses_proxy}}
<span class="d-block" title="Internet access goes via a proxy (HTTPS_PROXY or HTTP_PROXY is configured)."><b>Yes</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_proxy_yes" locale=@root.lang}}"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{/if}} {{/if}}
{{#unless page_data.uses_proxy}} {{#unless page_data.uses_proxy}}
<span class="d-block" title="We have direct internet access, no outgoing proxy configured."><b>No</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_proxy_no" locale=@root.lang}}"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">Websocket enabled <dt class="col-sm-5">{{t "tpl.admin.diag.websocket_enabled" locale=@root.lang}}
{{#if page_data.enable_websocket}} {{#if page_data.enable_websocket}}
<span class="badge bg-success d-none abbr-badge" id="websocket-success" title="Websocket connection is working.">Ok</span> <span class="badge bg-success d-none abbr-badge" id="websocket-success" title="{{t "tpl.admin.diag.title_websocket_ok" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="websocket-error" title="Websocket connection error, validate your reverse proxy configuration!">Error</span> <span class="badge bg-danger d-none abbr-badge" id="websocket-error" title="{{t "tpl.admin.diag.title_websocket_error" locale=@root.lang}}">{{t "tpl.admin.diag.error" locale=@root.lang}}</span>
{{/if}} {{/if}}
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
{{#if page_data.enable_websocket}} {{#if page_data.enable_websocket}}
<span class="d-block" title="Websocket connections are enabled (ENABLE_WEBSOCKET is true)."><b>Yes</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_websocket_enabled" locale=@root.lang}}"><b>{{t "tpl.admin.diag.yes" locale=@root.lang}}</b></span>
{{/if}} {{/if}}
{{#unless page_data.enable_websocket}} {{#unless page_data.enable_websocket}}
<span class="d-block" title="Websocket connections are disabled (ENABLE_WEBSOCKET is false)."><b>No</b></span> <span class="d-block" title="{{t "tpl.admin.diag.title_websocket_disabled" locale=@root.lang}}"><b>{{t "tpl.admin.diag.no" locale=@root.lang}}</b></span>
{{/unless}} {{/unless}}
</dd> </dd>
<dt class="col-sm-5">DNS (github.com) <dt class="col-sm-5">{{t "tpl.admin.diag.dns_github" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="dns-success" title="DNS Resolving works!">Ok</span> <span class="badge bg-success d-none abbr-badge" id="dns-success" title="{{t "tpl.admin.diag.title_dns_ok" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="dns-warning" title="DNS Resolving failed. Please fix.">Error</span> <span class="badge bg-danger d-none abbr-badge" id="dns-warning" title="{{t "tpl.admin.diag.title_dns_error" locale=@root.lang}}">{{t "tpl.admin.diag.error" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="dns-resolved">{{page_data.dns_resolved}}</span> <span id="dns-resolved">{{page_data.dns_resolved}}</span>
</dd> </dd>
<dt class="col-sm-5">Date & Time (Local) <dt class="col-sm-5">{{t "tpl.admin.diag.date_local" locale=@root.lang}}
{{#if page_data.tz_env}} {{#if page_data.tz_env}}
<span class="badge bg-success abbr-badge" title="Configured TZ environment variable">{{page_data.tz_env}}</span> <span class="badge bg-success abbr-badge" title="{{t "tpl.admin.diag.title_tz_env" locale=@root.lang}}">{{page_data.tz_env}}</span>
{{/if}} {{/if}}
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span><b>Server:</b> {{page_data.server_time_local}}</span> <span><b>{{t "tpl.admin.diag.server" locale=@root.lang}}</b> {{page_data.server_time_local}}</span>
</dd> </dd>
<dt class="col-sm-5">Date & Time (UTC) <dt class="col-sm-5">{{t "tpl.admin.diag.date_utc" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="time-success" title="Server and browser times are within 15 seconds of each other.">Server/Browser Ok</span> <span class="badge bg-success d-none abbr-badge" id="time-success" title="{{t "tpl.admin.diag.title_server_browser_ok" locale=@root.lang}}">{{t "tpl.admin.diag.server_browser_ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="time-warning" title="Server and browser times are more than 15 seconds apart.">Server/Browser Error</span> <span class="badge bg-danger d-none abbr-badge" id="time-warning" title="{{t "tpl.admin.diag.title_server_browser_error" locale=@root.lang}}">{{t "tpl.admin.diag.server_browser_error" locale=@root.lang}}</span>
<span class="badge bg-success d-none abbr-badge" id="ntp-server-success" title="Server and NTP times are within 15 seconds of each other.">Server NTP Ok</span> <span class="badge bg-success d-none abbr-badge" id="ntp-server-success" title="{{t "tpl.admin.diag.title_server_ntp_ok" locale=@root.lang}}">{{t "tpl.admin.diag.server_ntp_ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="ntp-server-warning" title="Server and NTP times are more than 15 seconds apart.">Server NTP Error</span> <span class="badge bg-danger d-none abbr-badge" id="ntp-server-warning" title="{{t "tpl.admin.diag.title_server_ntp_error" locale=@root.lang}}">{{t "tpl.admin.diag.server_ntp_error" locale=@root.lang}}</span>
<span class="badge bg-success d-none abbr-badge" id="ntp-browser-success" title="Browser and NTP times are within 15 seconds of each other.">Browser NTP Ok</span> <span class="badge bg-success d-none abbr-badge" id="ntp-browser-success" title="{{t "tpl.admin.diag.title_browser_ntp_ok" locale=@root.lang}}">{{t "tpl.admin.diag.browser_ntp_ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="ntp-browser-warning" title="Browser and NTP times are more than 15 seconds apart.">Browser NTP Error</span> <span class="badge bg-danger d-none abbr-badge" id="ntp-browser-warning" title="{{t "tpl.admin.diag.title_browser_ntp_error" locale=@root.lang}}">{{t "tpl.admin.diag.browser_ntp_error" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="ntp-time" class="d-block"><b>NTP:</b> <span id="ntp-server-string">{{page_data.ntp_time}}</span></span> <span id="ntp-time" class="d-block"><b>{{t "tpl.admin.diag.ntp" locale=@root.lang}}</b> <span id="ntp-server-string">{{page_data.ntp_time}}</span></span>
<span id="time-server" class="d-block"><b>Server:</b> <span id="time-server-string">{{page_data.server_time}}</span></span> <span id="time-server" class="d-block"><b>{{t "tpl.admin.diag.server" locale=@root.lang}}</b> <span id="time-server-string">{{page_data.server_time}}</span></span>
<span id="time-browser" class="d-block"><b>Browser:</b> <span id="time-browser-string"></span></span> <span id="time-browser" class="d-block"><b>{{t "tpl.admin.diag.browser" locale=@root.lang}}</b> <span id="time-browser-string"></span></span>
</dd> </dd>
<dt class="col-sm-5">Domain configuration <dt class="col-sm-5">{{t "tpl.admin.diag.domain_config" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="domain-success" title="The domain variable matches the browser location and seems to be configured correctly.">Match</span> <span class="badge bg-success d-none abbr-badge" id="domain-success" title="{{t "tpl.admin.diag.title_domain_match" locale=@root.lang}}">{{t "tpl.admin.diag.match" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="domain-warning" title="The domain variable does not match the browser location.&#013;&#010;The domain variable does not seem to be configured correctly.&#013;&#010;Some features may not work as expected!">No Match</span> <span class="badge bg-danger d-none abbr-badge" id="domain-warning" title="{{t "tpl.admin.diag.title_domain_no_match" locale=@root.lang}}">{{t "tpl.admin.diag.no_match" locale=@root.lang}}</span>
<span class="badge bg-success d-none abbr-badge" id="https-success" title="Configured to use HTTPS">HTTPS</span> <span class="badge bg-success d-none abbr-badge" id="https-success" title="{{t "tpl.admin.diag.title_https_configured" locale=@root.lang}}">HTTPS</span>
<span class="badge bg-danger d-none abbr-badge" id="https-warning" title="Not configured to use HTTPS.&#013;&#010;Some features may not work as expected!">No HTTPS</span> <span class="badge bg-danger d-none abbr-badge" id="https-warning" title="{{t "tpl.admin.diag.title_https_not_configured" locale=@root.lang}}">{{t "tpl.admin.diag.no_https" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="domain-server" class="d-block"><b>Server:</b> <span id="domain-server-string">{{page_data.admin_url}}</span></span> <span id="domain-server" class="d-block"><b>{{t "tpl.admin.diag.server" locale=@root.lang}}</b> <span id="domain-server-string">{{page_data.admin_url}}</span></span>
<span id="domain-browser" class="d-block"><b>Browser:</b> <span id="domain-browser-string"></span></span> <span id="domain-browser" class="d-block"><b>{{t "tpl.admin.diag.browser" locale=@root.lang}}</b> <span id="domain-browser-string"></span></span>
</dd> </dd>
<dt class="col-sm-5">HTTP Response validation <dt class="col-sm-5">{{t "tpl.admin.diag.http_validation" locale=@root.lang}}
<span class="badge bg-success d-none abbr-badge" id="http-response-success" title="All headers and HTTP request responses seem to be ok.">Ok</span> <span class="badge bg-success d-none abbr-badge" id="http-response-success" title="{{t "tpl.admin.diag.title_http_ok" locale=@root.lang}}">{{t "tpl.admin.diag.ok" locale=@root.lang}}</span>
<span class="badge bg-danger d-none abbr-badge" id="http-response-warning" title="Some headers or HTTP request responses return invalid data!">Error</span> <span class="badge bg-danger d-none abbr-badge" id="http-response-warning" title="{{t "tpl.admin.diag.title_http_error" locale=@root.lang}}">{{t "tpl.admin.diag.error" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="http-response-errors" class="d-block"></span> <span id="http-response-errors" class="d-block"></span>
</dd> </dd>
{{#if page_data.invalid_feature_flags}} {{#if page_data.invalid_feature_flags}}
<dt class="col-sm-5">Invalid Feature Flags <dt class="col-sm-5">{{t "tpl.admin.diag.invalid_feature_flags" locale=@root.lang}}
<span class="badge bg-warning text-dark abbr-badge" id="feature-flag-warning" title="Some feature flags are invalid or outdated!">Warning</span> <span class="badge bg-warning text-dark abbr-badge" id="feature-flag-warning" title="{{t "tpl.admin.diag.title_invalid_flags" locale=@root.lang}}">{{t "tpl.admin.diag.warning" locale=@root.lang}}</span>
</dt> </dt>
<dd class="col-sm-7"> <dd class="col-sm-7">
<span id="feature-flags" class="d-block"><b>Flags:</b> <span id="feature-flags-string">{{page_data.invalid_feature_flags}}</span></span> <span id="feature-flags" class="d-block"><b>{{t "tpl.admin.diag.flags" locale=@root.lang}}</b> <span id="feature-flags-string">{{page_data.invalid_feature_flags}}</span></span>
</dd> </dd>
{{/if}} {{/if}}
</dl> </dl>
</div> </div>
</div> </div>
<h3>Support</h3> <h3>{{t "tpl.admin.diag.support" locale=@root.lang}}</h3>
<div class="row"> <div class="row">
<div class="col-md"> <div class="col-md">
<dl class="row"> <dl class="row">
<dd class="col-sm-12"> <dd class="col-sm-12">
If you need support please check the following links first before you create a new issue: {{t "tpl.admin.diag.support_intro" locale=@root.lang}}
<a href="https://vaultwarden.discourse.group/" target="_blank" rel="noreferrer noopener">Vaultwarden Forum</a> <a href="https://vaultwarden.discourse.group/" target="_blank" rel="noreferrer noopener">{{t "tpl.admin.diag.support_forum" locale=@root.lang}}</a>
| <a href="https://github.com/dani-garcia/vaultwarden/discussions" target="_blank" rel="noreferrer noopener">Github Discussions</a> | <a href="https://github.com/dani-garcia/vaultwarden/discussions" target="_blank" rel="noreferrer noopener">{{t "tpl.admin.diag.support_discussions" locale=@root.lang}}</a>
</dd> </dd>
</dl> </dl>
<dl class="row"> <dl class="row">
<dd class="col-sm-12"> <dd class="col-sm-12">
You can use the button below to pre-generate a string which you can copy/paste on either the Forum or when Creating a new issue at Github.<br> {{t "tpl.admin.diag.support_text_1" locale=@root.lang}}<br>
We try to hide the most sensitive values from the generated support string by default, but please verify if there is nothing in there which you want to hide!<br> {{t "tpl.admin.diag.support_text_2" locale=@root.lang}}<br>
</dd> </dd>
</dl> </dl>
<dl class="row"> <dl class="row">
<dt class="col-sm-3"> <dt class="col-sm-3">
<button type="button" id="gen-support" class="btn btn-primary">Generate Support String</button> <button type="button" id="gen-support" class="btn btn-primary">{{t "tpl.admin.diag.generate_support" locale=@root.lang}}</button>
<br><br> <br><br>
<button type="button" id="copy-support" class="btn btn-info mb-3 d-none">Copy To Clipboard</button> <button type="button" id="copy-support" class="btn btn-info mb-3 d-none">{{t "tpl.admin.diag.copy_clipboard" locale=@root.lang}}</button>
<div class="toast-container position-absolute float-start vw-copy-toast"> <div class="toast-container position-absolute float-start vw-copy-toast">
<div id="toastClipboardCopy" class="toast fade hide" role="status" aria-live="polite" aria-atomic="true" data-bs-autohide="true" data-bs-delay="1500"> <div id="toastClipboardCopy" class="toast fade hide" role="status" aria-live="polite" aria-atomic="true" data-bs-autohide="true" data-bs-delay="1500">
<div class="toast-body"> <div class="toast-body">
Copied to clipboard! {{t "tpl.admin.diag.copied_clipboard" locale=@root.lang}}
</div> </div>
</div> </div>
</div> </div>

8
src/static/templates/admin/login.hbs

@ -9,15 +9,15 @@
<div class="align-items-center p-3 mb-3 text-opacity-75 text-light bg-danger rounded shadow"> <div class="align-items-center p-3 mb-3 text-opacity-75 text-light bg-danger rounded shadow">
<div> <div>
<h6 class="mb-0 text-light">Authentication key needed to continue</h6> <h6 class="mb-0 text-light">{{t "tpl.admin.login.auth_key_needed" locale=lang}}</h6>
<small>Please provide it below:</small> <small>{{t "tpl.admin.login.provide_below" locale=lang}}</small>
<form class="form-inline" method="post" action="{{urlpath}}/admin"> <form class="form-inline" method="post" action="{{urlpath}}/admin">
<input type="password" autocomplete="password" class="form-control w-50 mr-2" name="token" placeholder="Enter admin token" autofocus="autofocus"> <input type="password" autocomplete="password" class="form-control w-50 mr-2" name="token" placeholder="{{t "tpl.admin.login.token_placeholder" locale=lang}}" autofocus="autofocus">
{{#if redirect}} {{#if redirect}}
<input type="hidden" id="redirect" name="redirect" value="/{{redirect}}"> <input type="hidden" id="redirect" name="redirect" value="/{{redirect}}">
{{/if}} {{/if}}
<button type="submit" class="btn btn-primary mt-2">Enter</button> <button type="submit" class="btn btn-primary mt-2">{{t "tpl.admin.login.enter" locale=lang}}</button>
</form> </form>
</div> </div>
</div> </div>

28
src/static/templates/admin/organizations.hbs

@ -1,16 +1,16 @@
<main class="container-xxl"> <main class="container-xxl">
<div id="organizations-block" class="my-3 p-3 rounded shadow"> <div id="organizations-block" class="my-3 p-3 rounded shadow">
<h6 class="border-bottom pb-2 mb-3">Organizations</h6> <h6 class="border-bottom pb-2 mb-3">{{t "tpl.admin.orgs.organizations" locale=lang}}</h6>
<div class="table-responsive-xl small"> <div class="table-responsive-xl small">
<table id="orgs-table" class="table table-sm table-striped table-hover"> <table id="orgs-table" class="table table-sm table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th class="vw-org-details">Organization</th> <th class="vw-org-details">{{t "tpl.admin.orgs.organization" locale=lang}}</th>
<th class="vw-users">Users</th> <th class="vw-users">{{t "tpl.admin.orgs.users" locale=lang}}</th>
<th class="vw-entries">Entries</th> <th class="vw-entries">{{t "tpl.admin.orgs.entries" locale=lang}}</th>
<th class="vw-attachments">Attachments</th> <th class="vw-attachments">{{t "tpl.admin.orgs.attachments" locale=lang}}</th>
<th class="vw-misc">Misc</th> <th class="vw-misc">{{t "tpl.admin.orgs.misc" locale=lang}}</th>
<th class="vw-actions text-end">Actions</th> <th class="vw-actions text-end">{{t "tpl.admin.orgs.actions" locale=lang}}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -33,18 +33,18 @@
<span class="d-block">{{cipher_count}}</span> <span class="d-block">{{cipher_count}}</span>
</td> </td>
<td> <td>
<span class="d-block"><strong>Amount:</strong> {{attachment_count}}</span> <span class="d-block"><strong>{{t "tpl.admin.orgs.amount" locale=../lang}}</strong> {{attachment_count}}</span>
{{#if attachment_count}} {{#if attachment_count}}
<span class="d-block"><strong>Size:</strong> {{attachment_size}}</span> <span class="d-block"><strong>{{t "tpl.admin.orgs.size" locale=../lang}}</strong> {{attachment_size}}</span>
{{/if}} {{/if}}
</td> </td>
<td> <td>
<span class="d-block"><strong>Collections:</strong> {{collection_count}}</span> <span class="d-block"><strong>{{t "tpl.admin.orgs.collections" locale=../lang}}</strong> {{collection_count}}</span>
<span class="d-block"><strong>Groups:</strong> {{group_count}}</span> <span class="d-block"><strong>{{t "tpl.admin.orgs.groups" locale=../lang}}</strong> {{group_count}}</span>
<span class="d-block"><strong>Events:</strong> {{event_count}}</span> <span class="d-block"><strong>{{t "tpl.admin.orgs.events" locale=../lang}}</strong> {{event_count}}</span>
</td> </td>
<td class="text-end px-1 small"> <td class="text-end px-1 small">
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-organization data-vw-org-uuid="{{id}}" data-vw-org-name="{{name}}" data-vw-billing-email="{{billingEmail}}">Delete Organization</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-organization data-vw-org-uuid="{{id}}" data-vw-org-name="{{name}}" data-vw-billing-email="{{billingEmail}}">{{t "tpl.admin.orgs.delete_org" locale=../lang}}</button><br>
</td> </td>
</tr> </tr>
{{/each}} {{/each}}
@ -53,7 +53,7 @@
</div> </div>
<div class="mt-3 clearfix"> <div class="mt-3 clearfix">
<button type="button" class="btn btn-sm btn-primary float-end" id="reload">Reload organizations</button> <button type="button" class="btn btn-sm btn-primary float-end" id="reload">{{t "tpl.admin.orgs.reload" locale=lang}}</button>
</div> </div>
</div> </div>
</main> </main>

77
src/static/templates/admin/settings.hbs

@ -1,48 +1,48 @@
<main class="container-xxl"> <main class="container-xxl">
<div id="admin_token_warning" class="alert alert-warning alert-dismissible fade show d-none"> <div id="admin_token_warning" class="alert alert-warning alert-dismissible fade show d-none">
<button type="button" class="btn-close" data-bs-target="admin_token_warning" data-bs-dismiss="alert" aria-label="Close"></button> <button type="button" class="btn-close" data-bs-target="admin_token_warning" data-bs-dismiss="alert" aria-label="{{t "tpl.admin.settings.close" locale=lang}}"></button>
You are using a plain text `ADMIN_TOKEN` which is insecure.<br> {{t "tpl.admin.settings.admin_token_warning_1" locale=lang}}<br>
Please generate a secure Argon2 PHC string by using `vaultwarden hash` or `argon2`.<br> {{t "tpl.admin.settings.admin_token_warning_2" locale=lang}}<br>
See: <a href="https://github.com/dani-garcia/vaultwarden/wiki/Enabling-admin-page#secure-the-admin_token" target="_blank" rel="noopener noreferrer">Enabling admin page - Secure the `ADMIN_TOKEN`</a> {{t "tpl.admin.settings.note" locale=lang}} <a href="https://github.com/dani-garcia/vaultwarden/wiki/Enabling-admin-page#secure-the-admin_token" target="_blank" rel="noopener noreferrer">{{t "tpl.admin.settings.admin_token_warning_3" locale=lang}}</a>
</div> </div>
<div id="config-block" class="align-items-center p-3 mb-3 bg-secondary rounded shadow"> <div id="config-block" class="align-items-center p-3 mb-3 bg-secondary rounded shadow">
<div> <div>
<h6 class="text-white mb-3">Configuration</h6> <h6 class="text-white mb-3">{{t "tpl.admin.settings.configuration" locale=lang}}</h6>
<div class="small text-white mb-3"> <div class="small text-white mb-3">
<span class="font-weight-bolder">NOTE:</span> The settings here override the environment variables. Once saved, it's recommended to stop setting them to avoid confusion.<br> <span class="font-weight-bolder">{{t "tpl.admin.settings.note" locale=lang}}</span> {{t "tpl.admin.settings.note_line_1" locale=lang}}<br>
This does not apply to the read-only section, which can only be set via environment variables.<br> {{t "tpl.admin.settings.note_line_2" locale=lang}}<br>
Settings which are overridden are shown with <span class="is-overridden-true alert-row px-1">a yellow colored background</span>. {{t "tpl.admin.settings.note_line_3" locale=lang}} <span class="is-overridden-true alert-row px-1">{{t "tpl.admin.settings.note_line_3_suffix" locale=lang}}</span>.
</div> </div>
<form class="form needs-validation" id="config-form" novalidate> <form class="form needs-validation" id="config-form" novalidate>
{{#each page_data.config}} {{#each page_data.config}}
{{#if groupdoc}} {{#if groupdoc}}
<div class="card mb-3"> <div class="card mb-3">
<button id="b_{{group}}" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_{{group}}" data-bs-toggle="collapse" data-bs-target="#g_{{group}}">{{groupdoc}}</button> <button id="b_{{group}}" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_{{group}}" data-bs-toggle="collapse" data-bs-target="#g_{{group}}">{{t groupdoc locale=lang}}</button>
<div id="g_{{group}}" class="card-body collapse"> <div id="g_{{group}}" class="card-body collapse">
{{#each elements}} {{#each elements}}
{{#if editable}} {{#if editable}}
<div class="row my-2 align-items-center is-overridden-{{overridden}} alert-row" title="[{{name}}] {{doc.description}}"> <div class="row my-2 align-items-center is-overridden-{{overridden}} alert-row" title="[{{name}}] {{t doc.description locale=../../lang}}">
{{#case type "text" "number" "password"}} {{#case type "text" "number" "password"}}
<label for="input_{{name}}" class="col-sm-3 col-form-label">{{doc.name}}</label> <label for="input_{{name}}" class="col-sm-3 col-form-label">{{t doc.name locale=../../lang}}</label>
<div class="col-sm-8"> <div class="col-sm-8">
<div class="input-group"> <div class="input-group">
<input class="form-control conf-{{type}}" id="input_{{name}}" type="{{type}}" <input class="form-control conf-{{type}}" id="input_{{name}}" type="{{type}}"
name="{{name}}" value="{{value}}" {{#if default}} placeholder="Default: {{default}}"{{/if}}> name="{{name}}" value="{{value}}" {{#if default}} placeholder="{{t "tpl.admin.settings.default_prefix" locale=../../lang}} {{default}}"{{/if}}>
{{#case type "password"}} {{#case type "password"}}
<button class="btn btn-outline-secondary input-group-text" type="button" data-vw-pw-toggle="input_{{name}}">Show/hide</button> <button class="btn btn-outline-secondary input-group-text" type="button" data-vw-pw-toggle="input_{{name}}">{{t "tpl.admin.settings.show_hide" locale=../../lang}}</button>
{{/case}} {{/case}}
</div> </div>
</div> </div>
{{/case}} {{/case}}
{{#case type "checkbox"}} {{#case type "checkbox"}}
<div class="col-sm-3 col-form-label">{{doc.name}}</div> <div class="col-sm-3 col-form-label">{{t doc.name locale=../../lang}}</div>
<div class="col-sm-8"> <div class="col-sm-8">
<div class="form-check"> <div class="form-check">
<input class="form-check-input conf-{{type}}" type="checkbox" id="input_{{name}}" <input class="form-check-input conf-{{type}}" type="checkbox" id="input_{{name}}"
name="{{name}}" {{#if value}} checked {{/if}}> name="{{name}}" {{#if value}} checked {{/if}}>
<label class="form-check-label" for="input_{{name}}"> Default: {{default}} </label> <label class="form-check-label" for="input_{{name}}"> {{t "tpl.admin.settings.default_prefix" locale=../../lang}} {{default}} </label>
</div> </div>
</div> </div>
{{/case}} {{/case}}
@ -50,12 +50,12 @@
{{/if}} {{/if}}
{{/each}} {{/each}}
{{#case group "smtp"}} {{#case group "smtp"}}
<div class="row my-2 align-items-center pt-3 border-top" title="Send a test email to given email address"> <div class="row my-2 align-items-center pt-3 border-top" title="{{t "tpl.admin.settings.smtp_test_title" locale=../../lang}}">
<label for="smtp-test-email" class="col-sm-3 col-form-label">Test SMTP</label> <label for="smtp-test-email" class="col-sm-3 col-form-label">{{t "tpl.admin.settings.smtp_test" locale=../../lang}}</label>
<div class="col-sm-8 input-group"> <div class="col-sm-8 input-group">
<input class="form-control" id="smtp-test-email" type="email" placeholder="Enter test email" required spellcheck="false"> <input class="form-control" id="smtp-test-email" type="email" placeholder="{{t "tpl.admin.settings.smtp_placeholder" locale=../../lang}}" required spellcheck="false">
<button type="button" class="btn btn-outline-primary input-group-text" id="smtpTest">Send test email</button> <button type="button" class="btn btn-outline-primary input-group-text" id="smtpTest">{{t "tpl.admin.settings.smtp_send" locale=../../lang}}</button>
<div class="invalid-tooltip">Please provide a valid email address</div> <div class="invalid-tooltip">{{t "tpl.admin.settings.smtp_invalid" locale=../../lang}}</div>
</div> </div>
</div> </div>
{{/case}} {{/case}}
@ -66,20 +66,18 @@
<div class="card mb-3"> <div class="card mb-3">
<button id="b_readonly" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_readonly" <button id="b_readonly" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_readonly"
data-bs-toggle="collapse" data-bs-target="#g_readonly">Read-Only Config</button> data-bs-toggle="collapse" data-bs-target="#g_readonly">{{t "tpl.admin.settings.readonly" locale=lang}}</button>
<div id="g_readonly" class="card-body collapse"> <div id="g_readonly" class="card-body collapse">
<div class="small mb-3"> <div class="small mb-3">
NOTE: These options can't be modified in the editor because they would require the server {{t "tpl.admin.settings.readonly_note" locale=lang}}
to be restarted. To modify them, you need to set the correct environment variables when
launching the server. You can check the variable names in the tooltips of each option.
</div> </div>
{{#each page_data.config}} {{#each page_data.config}}
{{#each elements}} {{#each elements}}
{{#unless editable}} {{#unless editable}}
<div class="row my-2 align-items-center alert-row" title="[{{name}}] {{doc.description}}"> <div class="row my-2 align-items-center alert-row" title="[{{name}}] {{t doc.description locale=../../lang}}">
{{#case type "text" "number" "password"}} {{#case type "text" "number" "password"}}
<label for="input_{{name}}" class="col-sm-3 col-form-label">{{doc.name}}</label> <label for="input_{{name}}" class="col-sm-3 col-form-label">{{t doc.name locale=../../lang}}</label>
<div class="col-sm-8"> <div class="col-sm-8">
<div class="input-group"> <div class="input-group">
{{!-- {{!--
@ -88,25 +86,25 @@
And sometimes this is more useful for providing support than just 3 asterisk. And sometimes this is more useful for providing support than just 3 asterisk.
--}} --}}
{{#if (eq name "database_url")}} {{#if (eq name "database_url")}}
<input readonly class="form-control" id="input_{{name}}" type="password" value="{{value}}" {{#if default}} placeholder="Default: {{default}}" {{/if}}> <input readonly class="form-control" id="input_{{name}}" type="password" value="{{value}}" {{#if default}} placeholder="{{t "tpl.admin.settings.default_prefix" locale=../../lang}} {{default}}" {{/if}}>
<button class="btn btn-outline-secondary" type="button" data-vw-pw-toggle="input_{{name}}">Show/hide</button> <button class="btn btn-outline-secondary" type="button" data-vw-pw-toggle="input_{{name}}">{{t "tpl.admin.settings.show_hide" locale=../../lang}}</button>
{{else}} {{else}}
<input readonly class="form-control" id="input_{{name}}" type="{{type}}" value="{{value}}" {{#if default}} placeholder="Default: {{default}}" {{/if}} spellcheck="false"> <input readonly class="form-control" id="input_{{name}}" type="{{type}}" value="{{value}}" {{#if default}} placeholder="{{t "tpl.admin.settings.default_prefix" locale=../../lang}} {{default}}" {{/if}} spellcheck="false">
{{#case type "password"}} {{#case type "password"}}
<button class="btn btn-outline-secondary" type="button" data-vw-pw-toggle="input_{{name}}">Show/hide</button> <button class="btn btn-outline-secondary" type="button" data-vw-pw-toggle="input_{{name}}">{{t "tpl.admin.settings.show_hide" locale=../../lang}}</button>
{{/case}} {{/case}}
{{/if}} {{/if}}
</div> </div>
</div> </div>
{{/case}} {{/case}}
{{#case type "checkbox"}} {{#case type "checkbox"}}
<div class="col-sm-3 col-form-label">{{doc.name}}</div> <div class="col-sm-3 col-form-label">{{t doc.name locale=../../lang}}</div>
<div class="col-sm-8"> <div class="col-sm-8">
<div class="form-check align-middle"> <div class="form-check align-middle">
<input disabled class="form-check-input" type="checkbox" id="input_{{name}}" <input disabled class="form-check-input" type="checkbox" id="input_{{name}}"
{{#if value}} checked {{/if}}> {{#if value}} checked {{/if}}>
<label class="form-check-label" for="input_{{name}}"> Default: {{default}} </label> <label class="form-check-label" for="input_{{name}}"> {{t "tpl.admin.settings.default_prefix" locale=../../lang}} {{default}} </label>
</div> </div>
</div> </div>
{{/case}} {{/case}}
@ -121,22 +119,19 @@
{{#if page_data.can_backup}} {{#if page_data.can_backup}}
<div class="card mb-3"> <div class="card mb-3">
<button id="b_database" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_database" <button id="b_database" type="button" class="card-header text-start btn btn-link text-decoration-none" aria-expanded="false" aria-controls="g_database"
data-bs-toggle="collapse" data-bs-target="#g_database">Backup Database</button> data-bs-toggle="collapse" data-bs-target="#g_database">{{t "tpl.admin.settings.backup_db" locale=lang}}</button>
<div id="g_database" class="card-body collapse"> <div id="g_database" class="card-body collapse">
<div class="small mb-3"> <div class="small mb-3">
WARNING: This function only creates a backup copy of the SQLite database. {{t "tpl.admin.settings.backup_warning" locale=lang}}
This does not include any configuration or file attachment data that may <a href="https://github.com/dani-garcia/vaultwarden/wiki/Backing-up-your-vault" target="_blank" rel="noopener noreferrer">{{t "tpl.admin.settings.backup_link" locale=lang}}</a>.
also be needed to fully restore a vaultwarden instance. For details on
how to perform complete backups, refer to the wiki page on
<a href="https://github.com/dani-garcia/vaultwarden/wiki/Backing-up-your-vault" target="_blank" rel="noopener noreferrer">backups</a>.
</div> </div>
<button type="button" class="btn btn-primary" id="backupDatabase">Backup Database</button> <button type="button" class="btn btn-primary" id="backupDatabase">{{t "tpl.admin.settings.backup_button" locale=lang}}</button>
</div> </div>
</div> </div>
{{/if}} {{/if}}
<button type="submit" class="btn btn-primary">Save</button> <button type="submit" class="btn btn-primary">{{t "tpl.admin.settings.save" locale=lang}}</button>
<button type="button" class="btn btn-danger float-end" id="deleteConf">Reset defaults</button> <button type="button" class="btn btn-danger float-end" id="deleteConf">{{t "tpl.admin.settings.reset_defaults" locale=lang}}</button>
</form> </form>
</div> </div>
</div> </div>

74
src/static/templates/admin/users.hbs

@ -1,20 +1,20 @@
<main class="container-xxl"> <main class="container-xxl">
<div id="users-block" class="my-3 p-3 rounded shadow"> <div id="users-block" class="my-3 p-3 rounded shadow">
<h6 class="border-bottom pb-2 mb-3">Registered Users</h6> <h6 class="border-bottom pb-2 mb-3">{{t "tpl.admin.users.registered_users" locale=lang}}</h6>
<div class="table-responsive-xl small"> <div class="table-responsive-xl small">
<table id="users-table" class="table table-sm table-striped table-hover"> <table id="users-table" class="table table-sm table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th class="vw-account-details">User</th> <th class="vw-account-details">{{t "tpl.admin.users.user" locale=lang}}</th>
{{#if sso_enabled}} {{#if sso_enabled}}
<th class="vw-sso-identifier">SSO Identifier</th> <th class="vw-sso-identifier">{{t "tpl.admin.users.sso_identifier" locale=lang}}</th>
{{/if}} {{/if}}
<th class="vw-created-at">Created at</th> <th class="vw-created-at">{{t "tpl.admin.users.created_at" locale=lang}}</th>
<th class="vw-last-active">Last Active</th> <th class="vw-last-active">{{t "tpl.admin.users.last_active" locale=lang}}</th>
<th class="vw-entries">Entries</th> <th class="vw-entries">{{t "tpl.admin.users.entries" locale=lang}}</th>
<th class="vw-attachments">Attachments</th> <th class="vw-attachments">{{t "tpl.admin.users.attachments" locale=lang}}</th>
<th class="vw-organizations">Organizations</th> <th class="vw-organizations">{{t "tpl.admin.users.organizations" locale=lang}}</th>
<th class="vw-actions text-end">Actions</th> <th class="vw-actions text-end">{{t "tpl.admin.users.actions" locale=lang}}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -27,16 +27,16 @@
<span class="d-block">{{email}}</span> <span class="d-block">{{email}}</span>
<span class="d-block"> <span class="d-block">
{{#unless user_enabled}} {{#unless user_enabled}}
<span class="badge bg-danger me-2" title="User is disabled">Disabled</span> <span class="badge bg-danger me-2" title="{{t "tpl.admin.users.badge_disabled_title" locale=../../lang}}">{{t "tpl.admin.users.badge_disabled" locale=../../lang}}</span>
{{/unless}} {{/unless}}
{{#if twoFactorEnabled}} {{#if twoFactorEnabled}}
<span class="badge bg-success me-2" title="2FA is enabled">2FA</span> <span class="badge bg-success me-2" title="{{t "tpl.admin.users.badge_2fa_title" locale=../../lang}}">2FA</span>
{{/if}} {{/if}}
{{#case _status 1}} {{#case _status 1}}
<span class="badge bg-warning text-dark me-2" title="User is invited">Invited</span> <span class="badge bg-warning text-dark me-2" title="{{t "tpl.admin.users.badge_invited_title" locale=../../lang}}">{{t "tpl.admin.users.badge_invited" locale=../../lang}}</span>
{{/case}} {{/case}}
{{#if emailVerified}} {{#if emailVerified}}
<span class="badge bg-success me-2" title="Email has been verified">Verified</span> <span class="badge bg-success me-2" title="{{t "tpl.admin.users.badge_verified_title" locale=../../lang}}">{{t "tpl.admin.users.badge_verified" locale=../../lang}}</span>
{{/if}} {{/if}}
</span> </span>
</div> </div>
@ -56,9 +56,9 @@
<span class="d-block">{{cipher_count}}</span> <span class="d-block">{{cipher_count}}</span>
</td> </td>
<td> <td>
<span class="d-block"><strong>Amount:</strong> {{attachment_count}}</span> <span class="d-block"><strong>{{t "tpl.admin.users.amount" locale=../lang}}</strong> {{attachment_count}}</span>
{{#if attachment_count}} {{#if attachment_count}}
<span class="d-block"><strong>Size:</strong> {{attachment_size}}</span> <span class="d-block"><strong>{{t "tpl.admin.users.size" locale=../lang}}</strong> {{attachment_size}}</span>
{{/if}} {{/if}}
</td> </td>
<td> <td>
@ -71,20 +71,20 @@
<td class="text-end px-1 small"> <td class="text-end px-1 small">
<span data-vw-user-uuid="{{id}}" data-vw-user-email="{{email}}"> <span data-vw-user-uuid="{{id}}" data-vw-user-email="{{email}}">
{{#if twoFactorEnabled}} {{#if twoFactorEnabled}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-remove2fa>Remove all 2FA</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-remove2fa>{{t "tpl.admin.users.remove_all_2fa" locale=../lang}}</button><br>
{{/if}} {{/if}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-deauth-user>Deauthorize sessions</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-deauth-user>{{t "tpl.admin.users.deauth_sessions" locale=../lang}}</button><br>
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-user>Delete User</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-user>{{t "tpl.admin.users.delete_user" locale=../lang}}</button><br>
{{#if ../sso_enabled}} {{#if ../sso_enabled}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-sso-user>Delete SSO Association</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-sso-user>{{t "tpl.admin.users.delete_sso_assoc" locale=../../lang}}</button><br>
{{/if}} {{/if}}
{{#if user_enabled}} {{#if user_enabled}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-disable-user>Disable User</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-disable-user>{{t "tpl.admin.users.disable_user" locale=../lang}}</button><br>
{{else}} {{else}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-enable-user>Enable User</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-enable-user>{{t "tpl.admin.users.enable_user" locale=../lang}}</button><br>
{{/if}} {{/if}}
{{#case _status 1}} {{#case _status 1}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-resend-user-invite>Resend invite</button><br> <button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-resend-user-invite>{{t "tpl.admin.users.resend_invite" locale=../lang}}</button><br>
{{/case}} {{/case}}
</span> </span>
</td> </td>
@ -96,22 +96,22 @@
<div class="mt-3 clearfix"> <div class="mt-3 clearfix">
<button type="button" class="btn btn-sm btn-danger" id="updateRevisions" <button type="button" class="btn btn-sm btn-danger" id="updateRevisions"
title="Force all clients to fetch new data next time they connect. Useful after restoring a backup to remove any stale data."> title="{{t "tpl.admin.users.force_resync_title" locale=lang}}">
Force clients to resync {{t "tpl.admin.users.force_resync" locale=lang}}
</button> </button>
<button type="button" class="btn btn-sm btn-primary float-end" id="reload">Reload users</button> <button type="button" class="btn btn-sm btn-primary float-end" id="reload">{{t "tpl.admin.users.reload" locale=lang}}</button>
</div> </div>
</div> </div>
<div id="inviteUserFormBlock" class="align-items-center p-3 mb-3 text-white-50 bg-secondary rounded shadow"> <div id="inviteUserFormBlock" class="align-items-center p-3 mb-3 text-white-50 bg-secondary rounded shadow">
<div> <div>
<h6 class="mb-0 text-white">Invite User</h6> <h6 class="mb-0 text-white">{{t "tpl.admin.users.invite_user" locale=lang}}</h6>
<small>Email:</small> <small>{{t "tpl.admin.users.email" locale=lang}}</small>
<form class="form-inline input-group w-50" id="inviteUserForm"> <form class="form-inline input-group w-50" id="inviteUserForm">
<input type="email" class="form-control me-2" id="inviteEmail" placeholder="Enter email" required spellcheck="false"> <input type="email" class="form-control me-2" id="inviteEmail" placeholder="{{t "tpl.admin.users.enter_email" locale=lang}}" required spellcheck="false">
<button type="submit" class="btn btn-primary">Invite</button> <button type="submit" class="btn btn-primary">{{t "tpl.admin.users.invite" locale=lang}}</button>
</form> </form>
</div> </div>
</div> </div>
@ -121,30 +121,30 @@
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<h6 class="modal-title"> <h6 class="modal-title">
<b>Update User Type:</b><br><b>Organization:</b> <span id="userOrgTypeDialogOrgName"></span><br><b>User:</b> <span id="userOrgTypeDialogUserEmail"></span> <b>{{t "tpl.admin.users.update_user_type" locale=lang}}</b><br><b>{{t "tpl.admin.users.organization" locale=lang}}</b> <span id="userOrgTypeDialogOrgName"></span><br><b>{{t "tpl.admin.users.user_label" locale=lang}}</b> <span id="userOrgTypeDialogUserEmail"></span>
</h6> </h6>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{t "tpl.admin.settings.close" locale=lang}}"></button>
</div> </div>
<form class="form" id="userOrgTypeForm"> <form class="form" id="userOrgTypeForm">
<input type="hidden" name="user_uuid" id="userOrgTypeUserUuid" value=""> <input type="hidden" name="user_uuid" id="userOrgTypeUserUuid" value="">
<input type="hidden" name="org_uuid" id="userOrgTypeOrgUuid" value=""> <input type="hidden" name="org_uuid" id="userOrgTypeOrgUuid" value="">
<div class="modal-body"> <div class="modal-body">
<div class="radio"> <div class="radio">
<label><input type="radio" value="2" class="form-radio-input" name="user_type" id="userOrgTypeUser">&nbsp;User</label> <label><input type="radio" value="2" class="form-radio-input" name="user_type" id="userOrgTypeUser">&nbsp;{{t "tpl.admin.users.role_user" locale=lang}}</label>
</div> </div>
<div class="radio"> <div class="radio">
<label><input type="radio" value="3" class="form-radio-input" name="user_type" id="userOrgTypeManager">&nbsp;Manager</label> <label><input type="radio" value="3" class="form-radio-input" name="user_type" id="userOrgTypeManager">&nbsp;{{t "tpl.admin.users.role_manager" locale=lang}}</label>
</div> </div>
<div class="radio"> <div class="radio">
<label><input type="radio" value="1" class="form-radio-input" name="user_type" id="userOrgTypeAdmin">&nbsp;Admin</label> <label><input type="radio" value="1" class="form-radio-input" name="user_type" id="userOrgTypeAdmin">&nbsp;{{t "tpl.admin.users.role_admin" locale=lang}}</label>
</div> </div>
<div class="radio"> <div class="radio">
<label><input type="radio" value="0" class="form-radio-input" name="user_type" id="userOrgTypeOwner">&nbsp;Owner</label> <label><input type="radio" value="0" class="form-radio-input" name="user_type" id="userOrgTypeOwner">&nbsp;{{t "tpl.admin.users.role_owner" locale=lang}}</label>
</div> </div>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">{{t "tpl.admin.users.cancel" locale=lang}}</button>
<button type="submit" class="btn btn-sm btn-primary">Change Role</button> <button type="submit" class="btn btn-sm btn-primary">{{t "tpl.admin.users.change_role" locale=lang}}</button>
</div> </div>
</form> </form>
</div> </div>

8
src/static/templates/email/admin_account_recovery.hbs

@ -1,12 +1,12 @@
Admin account recovery from {{org_name}} organization {{t "tpl.email.admin_account_recovery.subject_prefix" locale=lang}} {{org_name}} {{t "tpl.email.admin_account_recovery.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{#if reset_password}} {{#if reset_password}}
The master password for {{user_name}} has been changed. {{t "tpl.email.admin_account_recovery.body_reset_password_prefix" locale=lang}} {{user_name}} {{t "tpl.email.admin_account_recovery.body_reset_password_suffix" locale=lang}}
{{/if}} {{/if}}
{{#if reset_2fa}} {{#if reset_2fa}}
Your two-step verification providers have been reset.{{#if fallback_2fa_email}} Email two factor has been activated as a fallback.{{/if}} {{t "tpl.email.admin_account_recovery.body_reset_2fa" locale=lang}}{{#if fallback_2fa_email}} {{t "tpl.email.admin_account_recovery.body_fallback_2fa" locale=lang}}{{/if}}
{{/if}} {{/if}}
If you did not initiate this request, please reach out to your administrator immediately. {{t "tpl.email.admin_account_recovery.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

8
src/static/templates/email/admin_account_recovery.html.hbs

@ -1,17 +1,17 @@
Admin account recovery from {{org_name}} organization {{t "tpl.email.admin_account_recovery.subject_prefix" locale=lang}} {{org_name}} {{t "tpl.email.admin_account_recovery.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
{{#if reset_password}} {{#if reset_password}}
The master password for <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{user_name}}</b> has been changed. {{t "tpl.email.admin_account_recovery.body_reset_password_prefix" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{user_name}}</b> {{t "tpl.email.admin_account_recovery.body_reset_password_suffix" locale=lang}}
{{/if}} {{/if}}
{{#if reset_2fa}} {{#if reset_2fa}}
Your two-step verification providers have been reset.{{#if fallback_2fa_email}} Email two factor has been activated as a fallback.{{/if}} {{t "tpl.email.admin_account_recovery.body_reset_2fa" locale=lang}}{{#if fallback_2fa_email}} {{t "tpl.email.admin_account_recovery.body_fallback_2fa" locale=lang}}{{/if}}
{{/if}} {{/if}}
<br> <br>
If you did not initiate this request, please reach out to your administrator immediately. {{t "tpl.email.admin_account_recovery.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/change_email.hbs

@ -1,6 +1,6 @@
Your Email Change {{t "tpl.email.change_email.subject" locale=lang}}
<!----------------> <!---------------->
To finalize changing your email address enter the following code in web vault: {{token}} {{t "tpl.email.change_email.body_intro" locale=lang}}: {{token}}
If you did not try to change your email address, contact your administrator. {{t "tpl.email.change_email.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

6
src/static/templates/email/change_email.html.hbs

@ -1,15 +1,15 @@
Your Email Change {{t "tpl.email.change_email.subject" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
To finalize changing your email address enter the following code in web vault: <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{token}}</b> {{t "tpl.email.change_email.body_intro" locale=lang}}: <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{token}}</b>
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
If you did not try to change your email address, contact your administrator. {{t "tpl.email.change_email.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/change_email_existing.hbs

@ -1,6 +1,6 @@
Your Email Change {{t "tpl.email.change_email_existing.subject" locale=lang}}
<!----------------> <!---------------->
A user ({{ acting_address }}) recently tried to change their account to use this email address ({{ existing_address }}). An account already exists with this email ({{ existing_address }}). {{t "tpl.email.change_email_existing.body_intro" locale=lang}} ({{ acting_address }}) {{t "tpl.email.change_email_existing.body_intro_mid" locale=lang}} ({{ existing_address }}). {{t "tpl.email.change_email_existing.body_intro_suffix" locale=lang}} ({{ existing_address }}).
If you did not try to change an email address, contact your administrator. {{t "tpl.email.change_email_existing.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

6
src/static/templates/email/change_email_existing.html.hbs

@ -1,15 +1,15 @@
Your Email Change {{t "tpl.email.change_email_existing.subject" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
A user ({{ acting_address }}) recently tried to change their account to use this email address ({{ existing_address }}). An account already exists with this email ({{ existing_address }}). {{t "tpl.email.change_email_existing.body_intro" locale=lang}} ({{ acting_address }}) {{t "tpl.email.change_email_existing.body_intro_mid" locale=lang}} ({{ existing_address }}). {{t "tpl.email.change_email_existing.body_intro_suffix" locale=lang}} ({{ existing_address }}).
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
If you did not try to change an email address, contact your administrator. {{t "tpl.email.change_email_existing.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

12
src/static/templates/email/change_email_invited.hbs

@ -1,11 +1,11 @@
Your Email Change {{t "tpl.email.change_email_invited.subject" locale=lang}}
<!----------------> <!---------------->
A user ({{ acting_address }}) recently tried to change their account to use this email address ({{ existing_address }}). You already have been invited to join Vaultwarden using this address. {{t "tpl.email.change_email_invited.body_intro" locale=lang}} ({{ acting_address }}) {{t "tpl.email.change_email_invited.body_intro_mid" locale=lang}} ({{ existing_address }}). {{t "tpl.email.change_email_invited.body_intro_suffix" locale=lang}}
To change your email address you first would have to delete the account associated with this email address ({{ existing_address }}): {{t "tpl.email.change_email_invited.body_delete_intro" locale=lang}} ({{ existing_address }}):
Request account deletion: {{url}}/#/recover-delete {{t "tpl.email.change_email_invited.cta" locale=lang}}: {{url}}/#/recover-delete
Once that is done you can change the email address of your existing account to this address. Any invitation would have to be redone. {{t "tpl.email.change_email_invited.body_after" locale=lang}}
If you did not try to change an email address, contact your administrator. {{t "tpl.email.change_email_invited.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

12
src/static/templates/email/change_email_invited.html.hbs

@ -1,29 +1,29 @@
Your Email Change {{t "tpl.email.change_email_invited.subject" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
A user ({{ acting_address }}) recently tried to change their account to use this email address ({{ existing_address }}). You already have been invited to join Vaultwarden using this address. {{t "tpl.email.change_email_invited.body_intro" locale=lang}} ({{ acting_address }}) {{t "tpl.email.change_email_invited.body_intro_mid" locale=lang}} ({{ existing_address }}). {{t "tpl.email.change_email_invited.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
To change your email address you first would have to delete the account associated with this email address ({{ existing_address }}): {{t "tpl.email.change_email_invited.body_delete_intro" locale=lang}} ({{ existing_address }}):
<a data-testid="recover-delete" href="{{url}}/#/recover-delete" <a data-testid="recover-delete" href="{{url}}/#/recover-delete"
clicktracking=off target="_blank" style="color: #ffffff; text-decoration: none; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background-color: #3c8dbc; border-color: #3c8dbc; border-style: solid; border-width: 10px 20px; margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> clicktracking=off target="_blank" style="color: #ffffff; text-decoration: none; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background-color: #3c8dbc; border-color: #3c8dbc; border-style: solid; border-width: 10px 20px; margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
Request account deletion {{t "tpl.email.change_email_invited.cta" locale=lang}}
</a> </a>
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
Once that is done you can change the email address of your existing account to this address. Any invitation would have to be redone. {{t "tpl.email.change_email_invited.body_after" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
If you did not try to change an email address, contact your administrator. {{t "tpl.email.change_email_invited.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

8
src/static/templates/email/delete_account.hbs

@ -1,8 +1,8 @@
Delete Your Account {{t "tpl.email.delete_account.subject" locale=lang}}
<!----------------> <!---------------->
Click the link below to delete your account. {{t "tpl.email.delete_account.body_intro" locale=lang}}
Delete Your Account: {{url}}/#/verify-recover-delete?userId={{user_id}}&token={{token}}&email={{email}} {{t "tpl.email.delete_account.cta" locale=lang}}: {{url}}/#/verify-recover-delete?userId={{user_id}}&token={{token}}&email={{email}}
If you did not request this email to delete your account, you can safely ignore this email. {{t "tpl.email.delete_account.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

8
src/static/templates/email/delete_account.html.hbs

@ -1,23 +1,23 @@
Delete Your Account {{t "tpl.email.delete_account.subject" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
Click the link below to delete your account. {{t "tpl.email.delete_account.body_intro" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
<a href="{{url}}/#/verify-recover-delete?userId={{user_id}}&token={{token}}&email={{email}}" <a href="{{url}}/#/verify-recover-delete?userId={{user_id}}&token={{token}}&email={{email}}"
clicktracking=off target="_blank" style="color: #ffffff; text-decoration: none; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background-color: #3c8dbc; border-color: #3c8dbc; border-style: solid; border-width: 10px 20px; margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> clicktracking=off target="_blank" style="color: #ffffff; text-decoration: none; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background-color: #3c8dbc; border-color: #3c8dbc; border-style: solid; border-width: 10px 20px; margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
Delete Your Account {{t "tpl.email.delete_account.cta" locale=lang}}
</a> </a>
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none; text-align: center;" valign="top" align="center">
If you did not request this email to delete your account, you can safely ignore this email. {{t "tpl.email.delete_account.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

8
src/static/templates/email/emergency_access_invite_accepted.hbs

@ -1,8 +1,8 @@
Emergency access contact {{{grantee_email}}} accepted {{t "tpl.email.ea_invite_accepted.subject_prefix" locale=lang}} {{{grantee_email}}} {{t "tpl.email.ea_invite_accepted.subject_suffix" locale=lang}}
<!----------------> <!---------------->
This email is to notify you that {{grantee_email}} has accepted your invitation to become an emergency access contact. {{t "tpl.email.ea_invite_accepted.body_intro_prefix" locale=lang}} {{grantee_email}} {{t "tpl.email.ea_invite_accepted.body_intro_suffix" locale=lang}}
To confirm this user, log into the web vault ({{url}}), go to settings and confirm the user. {{t "tpl.email.ea_invite_accepted.body_confirm_prefix" locale=lang}} ({{url}}), {{t "tpl.email.ea_invite_accepted.body_confirm_suffix" locale=lang}}
If you do not wish to confirm this user, you can also remove them on the same page. {{t "tpl.email.ea_invite_accepted.body_ignore" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

8
src/static/templates/email/emergency_access_invite_accepted.html.hbs

@ -1,20 +1,20 @@
Emergency access contact {{{grantee_email}}} accepted {{t "tpl.email.ea_invite_accepted.subject_prefix" locale=lang}} {{{grantee_email}}} {{t "tpl.email.ea_invite_accepted.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
This email is to notify you that {{grantee_email}} has accepted your invitation to become an emergency access contact. {{t "tpl.email.ea_invite_accepted.body_intro_prefix" locale=lang}} {{grantee_email}} {{t "tpl.email.ea_invite_accepted.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
To confirm this user, log into the <a href="{{url}}/">web vault</a>, go to settings and confirm the user. {{t "tpl.email.ea_invite_accepted.body_confirm_html_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_invite_accepted.body_confirm_html_link" locale=lang}}</a>, {{t "tpl.email.ea_invite_accepted.body_confirm_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
If you do not wish to confirm this user, you can also remove them on the same page. {{t "tpl.email.ea_invite_accepted.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/emergency_access_invite_confirmed.hbs

@ -1,6 +1,6 @@
Emergency access contact for {{{grantor_name}}} confirmed {{t "tpl.email.ea_invite_confirmed.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_invite_confirmed.subject_suffix" locale=lang}}
<!----------------> <!---------------->
This email is to notify you that you have been confirmed as an emergency access contact for *{{grantor_name}}*. {{t "tpl.email.ea_invite_confirmed.body_intro_prefix" locale=lang}} *{{grantor_name}}*.
You can now initiate emergency access requests from the web vault ({{url}}). {{t "tpl.email.ea_invite_confirmed.body_access_prefix" locale=lang}} ({{url}}).
{{> email/email_footer_text }} {{> email/email_footer_text }}

6
src/static/templates/email/emergency_access_invite_confirmed.html.hbs

@ -1,15 +1,15 @@
Emergency access contact for {{{grantor_name}}} confirmed {{t "tpl.email.ea_invite_confirmed.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_invite_confirmed.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
This email is to notify you that you have been confirmed as an emergency access contact for <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b>. {{t "tpl.email.ea_invite_confirmed.body_intro_prefix" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b>.
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
You can now initiate emergency access requests from the <a href="{{url}}/">web vault</a>. {{t "tpl.email.ea_invite_confirmed.body_access_html_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_invite_confirmed.body_access_html_link" locale=lang}}</a>.
</td> </td>
</tr> </tr>
</table> </table>

4
src/static/templates/email/emergency_access_recovery_approved.hbs

@ -1,4 +1,4 @@
Emergency access request for {{{grantor_name}}} approved {{t "tpl.email.ea_recovery_approved.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_recovery_approved.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{grantor_name}} has approved your emergency access request. You may now login on the web vault ({{url}}) and access their account. {{grantor_name}} {{t "tpl.email.ea_recovery_approved.body_intro_mid" locale=lang}} ({{url}}) {{t "tpl.email.ea_recovery_approved.body_intro_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

4
src/static/templates/email/emergency_access_recovery_approved.html.hbs

@ -1,10 +1,10 @@
Emergency access request for {{{grantor_name}}} approved {{t "tpl.email.ea_recovery_approved.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_recovery_approved.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b> has approved your emergency access request. You may now login on the <a href="{{url}}/">web vault</a> and access their account. <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b> {{t "tpl.email.ea_recovery_approved.body_intro_mid" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_recovery_approved.body_intro_link" locale=lang}}</a> {{t "tpl.email.ea_recovery_approved.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/emergency_access_recovery_initiated.hbs

@ -1,6 +1,6 @@
Emergency access request by {{{grantee_name}}} initiated {{t "tpl.email.ea_recovery_initiated.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_initiated.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{grantee_name}} has initiated an emergency access request to {{atype}} your account. You may login on the web vault ({{url}}) and manually approve or reject this request. {{grantee_name}} {{t "tpl.email.ea_recovery_initiated.body_intro_mid" locale=lang}} {{atype}} {{t "tpl.email.ea_recovery_initiated.body_intro_suffix_prefix" locale=lang}} ({{url}}) {{t "tpl.email.ea_recovery_initiated.body_intro_suffix" locale=lang}}
If you do nothing, the request will automatically be approved after {{wait_time_days}} day(s). {{t "tpl.email.ea_recovery_initiated.body_wait_prefix" locale=lang}} {{wait_time_days}} {{t "tpl.email.ea_recovery_initiated.body_wait_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

6
src/static/templates/email/emergency_access_recovery_initiated.html.hbs

@ -1,15 +1,15 @@
Emergency access request by {{{grantee_name}}} initiated {{t "tpl.email.ea_recovery_initiated.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_initiated.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> has initiated an emergency access request to <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> your account. You may login on the <a href="{{url}}/">web vault</a> and manually approve or reject this request. <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> {{t "tpl.email.ea_recovery_initiated.body_intro_mid" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> {{t "tpl.email.ea_recovery_initiated.body_intro_suffix_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_recovery_initiated.body_intro_link" locale=lang}}</a> {{t "tpl.email.ea_recovery_initiated.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
If you do nothing, the request will automatically be approved after <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{wait_time_days}}</b> day(s). {{t "tpl.email.ea_recovery_initiated.body_wait_prefix" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{wait_time_days}}</b> {{t "tpl.email.ea_recovery_initiated.body_wait_suffix" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

4
src/static/templates/email/emergency_access_recovery_rejected.hbs

@ -1,4 +1,4 @@
Emergency access request to {{{grantor_name}}} rejected {{t "tpl.email.ea_recovery_rejected.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_recovery_rejected.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{grantor_name}} has rejected your emergency access request. {{grantor_name}} {{t "tpl.email.ea_recovery_rejected.body_intro" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

4
src/static/templates/email/emergency_access_recovery_rejected.html.hbs

@ -1,10 +1,10 @@
Emergency access request to {{{grantor_name}}} rejected {{t "tpl.email.ea_recovery_rejected.subject_prefix" locale=lang}} {{{grantor_name}}} {{t "tpl.email.ea_recovery_rejected.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b> has rejected your emergency access request. <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantor_name}}</b> {{t "tpl.email.ea_recovery_rejected.body_intro" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/emergency_access_recovery_reminder.hbs

@ -1,6 +1,6 @@
Emergency access request by {{{grantee_name}}} is pending {{t "tpl.email.ea_recovery_reminder.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_reminder.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{grantee_name}} has a pending emergency access request to {{atype}} your account. You may login on the web vault ({{url}}) and manually approve or reject this request. {{grantee_name}} {{t "tpl.email.ea_recovery_reminder.body_intro_mid" locale=lang}} {{atype}} {{t "tpl.email.ea_recovery_reminder.body_intro_suffix_prefix" locale=lang}} ({{url}}) {{t "tpl.email.ea_recovery_reminder.body_intro_suffix" locale=lang}}
If you do nothing, the request will automatically be approved after {{days_left}} day(s). {{t "tpl.email.ea_recovery_reminder.body_wait_prefix" locale=lang}} {{days_left}} {{t "tpl.email.ea_recovery_reminder.body_wait_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

6
src/static/templates/email/emergency_access_recovery_reminder.html.hbs

@ -1,15 +1,15 @@
Emergency access request by {{{grantee_name}}} is pending {{t "tpl.email.ea_recovery_reminder.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_reminder.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> has a pending emergency access request to <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> your account. You may login on the <a href="{{url}}/">web vault</a> and manually approve or reject this request. <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> {{t "tpl.email.ea_recovery_reminder.body_intro_mid" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> {{t "tpl.email.ea_recovery_reminder.body_intro_suffix_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_recovery_reminder.body_intro_link" locale=lang}}</a> {{t "tpl.email.ea_recovery_reminder.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
If you do nothing, the request will automatically be approved after <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{days_left}}</b> day(s). {{t "tpl.email.ea_recovery_reminder.body_wait_prefix" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{days_left}}</b> {{t "tpl.email.ea_recovery_reminder.body_wait_suffix" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

4
src/static/templates/email/emergency_access_recovery_timed_out.hbs

@ -1,4 +1,4 @@
Emergency access request by {{{grantee_name}}} granted {{t "tpl.email.ea_recovery_timed_out.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_timed_out.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{grantee_name}} has been granted emergency access to {{atype}} your account. You may login on the web vault ({{url}}) and manually revoke this request. {{grantee_name}} {{t "tpl.email.ea_recovery_timed_out.body_intro_mid" locale=lang}} {{atype}} {{t "tpl.email.ea_recovery_timed_out.body_intro_suffix_prefix" locale=lang}} ({{url}}) {{t "tpl.email.ea_recovery_timed_out.body_intro_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

4
src/static/templates/email/emergency_access_recovery_timed_out.html.hbs

@ -1,10 +1,10 @@
Emergency access request by {{{grantee_name}}} granted {{t "tpl.email.ea_recovery_timed_out.subject_prefix" locale=lang}} {{{grantee_name}}} {{t "tpl.email.ea_recovery_timed_out.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> has been granted emergency access to <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> your account. You may login on the <a href="{{url}}/">web vault</a> and manually revoke this request. <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{grantee_name}}</b> {{t "tpl.email.ea_recovery_timed_out.body_intro_mid" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{atype}}</b> {{t "tpl.email.ea_recovery_timed_out.body_intro_suffix_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.ea_recovery_timed_out.body_intro_link" locale=lang}}</a> {{t "tpl.email.ea_recovery_timed_out.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

14
src/static/templates/email/incomplete_2fa_login.hbs

@ -1,11 +1,11 @@
Incomplete Two-Step Login From {{{device_name}}} {{t "tpl.email.incomplete_2fa.subject_prefix" locale=lang}} {{{device_name}}}
<!----------------> <!---------------->
Someone attempted to log into your account with the correct master password, but did not provide the correct token or action required to complete the two-step login process within {{time_limit}} minutes of the initial login attempt. {{t "tpl.email.incomplete_2fa.body_intro_prefix" locale=lang}} {{time_limit}} {{t "tpl.email.incomplete_2fa.body_intro_suffix" locale=lang}}
* Date: {{datetime}} * {{t "tpl.email.incomplete_2fa.label_date" locale=lang}}: {{datetime}}
* IP Address: {{ip}} * {{t "tpl.email.incomplete_2fa.label_ip" locale=lang}}: {{ip}}
* Device Name: {{device_name}} * {{t "tpl.email.incomplete_2fa.label_device_name" locale=lang}}: {{device_name}}
* Device Type: {{device_type}} * {{t "tpl.email.incomplete_2fa.label_device_type" locale=lang}}: {{device_type}}
If this was not you or someone you authorized, then you should change your master password as soon as possible, as it is likely to be compromised. {{t "tpl.email.incomplete_2fa.body_warning" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

14
src/static/templates/email/incomplete_2fa_login.html.hbs

@ -1,35 +1,35 @@
Incomplete Two-Step Login From {{{device_name}}} {{t "tpl.email.incomplete_2fa.subject_prefix" locale=lang}} {{{device_name}}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
Someone attempted to log into your account with the correct master password, but did not provide the correct token or action required to complete the two-step login process within {{time_limit}} minutes of the initial login attempt. {{t "tpl.email.incomplete_2fa.body_intro_prefix" locale=lang}} {{time_limit}} {{t "tpl.email.incomplete_2fa.body_intro_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Date</b>: {{datetime}} <b>{{t "tpl.email.incomplete_2fa.label_date" locale=lang}}</b>: {{datetime}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>IP Address:</b> {{ip}} <b>{{t "tpl.email.incomplete_2fa.label_ip" locale=lang}}:</b> {{ip}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Device Name:</b> {{device_name}} <b>{{t "tpl.email.incomplete_2fa.label_device_name" locale=lang}}:</b> {{device_name}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Device Type:</b> {{device_type}} <b>{{t "tpl.email.incomplete_2fa.label_device_type" locale=lang}}:</b> {{device_type}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
If this was not you or someone you authorized, then you should change your master password as soon as possible, as it is likely to be compromised. {{t "tpl.email.incomplete_2fa.body_warning" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/invite_accepted.hbs

@ -1,5 +1,5 @@
Invitation to {{{org_name}}} accepted {{t "tpl.email.invite_accepted.subject_prefix" locale=lang}} {{{org_name}}} {{t "tpl.email.invite_accepted.subject_suffix" locale=lang}}
<!----------------> <!---------------->
This email is to notify you that {{email}} has accepted your invitation to join {{org_name}}. {{t "tpl.email.invite_accepted.body_intro_prefix" locale=lang}} {{email}} {{t "tpl.email.invite_accepted.body_intro_mid" locale=lang}} {{org_name}}.
Please log in via {{url}} to the vaultwarden server and confirm them from the organization management page. {{t "tpl.email.invite_accepted.body_login_prefix" locale=lang}} {{url}} {{t "tpl.email.invite_accepted.body_login_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

8
src/static/templates/email/invite_accepted.html.hbs

@ -1,20 +1,20 @@
Invitation to {{{org_name}}} accepted {{t "tpl.email.invite_accepted.subject_prefix" locale=lang}} {{{org_name}}} {{t "tpl.email.invite_accepted.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
This email is to notify you that {{email}} has accepted your invitation to join <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{org_name}}</b>. {{t "tpl.email.invite_accepted.body_intro_prefix" locale=lang}} {{email}} {{t "tpl.email.invite_accepted.body_intro_mid" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{org_name}}</b>.
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
Please <a href="{{url}}/">log in</a> to the vaultwarden server and confirm them from the organization management page. {{t "tpl.email.invite_accepted.body_login_html_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.invite_accepted.body_login_html_link" locale=lang}}</a> {{t "tpl.email.invite_accepted.body_login_suffix" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
If you do not wish to confirm this user, you can also remove them from the organization on the same page. {{t "tpl.email.invite_accepted.body_ignore" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

6
src/static/templates/email/invite_confirmed.hbs

@ -1,5 +1,5 @@
Invitation to {{{org_name}}} confirmed {{t "tpl.email.invite_confirmed.subject_prefix" locale=lang}} {{{org_name}}} {{t "tpl.email.invite_confirmed.subject_suffix" locale=lang}}
<!----------------> <!---------------->
This email is to notify you that you have been confirmed as a user of {{org_name}}. {{t "tpl.email.invite_confirmed.body_intro_prefix" locale=lang}} {{org_name}}.
Any collections and logins being shared with you by this organization will now appear in your Vaultwarden vault at {{url}}. {{t "tpl.email.invite_confirmed.body_collections_prefix" locale=lang}} {{url}}.
{{> email/email_footer_text }} {{> email/email_footer_text }}

8
src/static/templates/email/invite_confirmed.html.hbs

@ -1,16 +1,16 @@
Invitation to {{{org_name}}} confirmed {{t "tpl.email.invite_confirmed.subject_prefix" locale=lang}} {{{org_name}}} {{t "tpl.email.invite_confirmed.subject_suffix" locale=lang}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
This email is to notify you that you have been confirmed as a user of <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{org_name}}</b>. {{t "tpl.email.invite_confirmed.body_intro_prefix" locale=lang}} <b style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">{{org_name}}</b>.
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
Any collections and logins being shared with you by this organization will now appear in your Vaultwarden vault. <br> {{t "tpl.email.invite_confirmed.body_collections_html" locale=lang}} <br>
<a href="{{url}}/">Log in</a> <a href="{{url}}/">{{t "tpl.email.invite_confirmed.body_login_link" locale=lang}}</a>
</td> </td>
</tr> </tr>
</table> </table>

14
src/static/templates/email/new_device_logged_in.hbs

@ -1,11 +1,11 @@
New Device Logged In From {{{device_name}}} {{t "tpl.email.new_device.subject_prefix" locale=lang}} {{{device_name}}}
<!----------------> <!---------------->
Your account was just logged into from a new device. {{t "tpl.email.new_device.body_intro" locale=lang}}
* Date: {{datetime}} * {{t "tpl.email.new_device.label_date" locale=lang}}: {{datetime}}
* IP Address: {{ip}} * {{t "tpl.email.new_device.label_ip" locale=lang}}: {{ip}}
* Device Name: {{device_name}} * {{t "tpl.email.new_device.label_device_name" locale=lang}}: {{device_name}}
* Device Type: {{device_type}} * {{t "tpl.email.new_device.label_device_type" locale=lang}}: {{device_type}}
You can deauthorize all devices that have access to your account from the web vault ( {{url}} ) under Settings > My Account > Deauthorize Sessions. {{t "tpl.email.new_device.body_deauth_prefix" locale=lang}} ( {{url}} ) {{t "tpl.email.new_device.body_deauth_suffix" locale=lang}}
{{> email/email_footer_text }} {{> email/email_footer_text }}

14
src/static/templates/email/new_device_logged_in.html.hbs

@ -1,35 +1,35 @@
New Device Logged In From {{{device_name}}} {{t "tpl.email.new_device.subject_prefix" locale=lang}} {{{device_name}}}
<!----------------> <!---------------->
{{> email/email_header }} {{> email/email_header }}
<table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
Your account was just logged into from a new device. {{t "tpl.email.new_device.body_intro" locale=lang}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Date:</b> {{datetime}} <b>{{t "tpl.email.new_device.label_date" locale=lang}}:</b> {{datetime}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>IP Address:</b> {{ip}} <b>{{t "tpl.email.new_device.label_ip" locale=lang}}:</b> {{ip}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Device Name:</b> {{device_name}} <b>{{t "tpl.email.new_device.label_device_name" locale=lang}}:</b> {{device_name}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0 0 10px; -webkit-text-size-adjust: none;" valign="top">
<b>Device Type:</b> {{device_type}} <b>{{t "tpl.email.new_device.label_device_type" locale=lang}}:</b> {{device_type}}
</td> </td>
</tr> </tr>
<tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;"> <tr style="margin: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;">
<td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top"> <td class="content-block last" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 16px; color: #333; line-height: 25px; margin: 0; -webkit-font-smoothing: antialiased; padding: 0; -webkit-text-size-adjust: none;" valign="top">
You can deauthorize all devices that have access to your account from the <a href="{{url}}/">web vault</a> under Settings > My Account > Deauthorize Sessions. {{t "tpl.email.new_device.body_deauth_html_prefix" locale=lang}} <a href="{{url}}/">{{t "tpl.email.new_device.body_deauth_html_link" locale=lang}}</a> {{t "tpl.email.new_device.body_deauth_suffix" locale=lang}}
</td> </td>
</tr> </tr>
</table> </table>

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save