✨ (user): Respeta las preferencias por usuario
This commit is contained in:
parent
0472e698ae
commit
a29f0f2b75
24 changed files with 239 additions and 201 deletions
|
|
@ -2,7 +2,7 @@ use pagetop::prelude::*;
|
|||
|
||||
use tokio::sync::{Notify, watch};
|
||||
|
||||
use crate::config::{CronMode, JobSettings, SETTINGS};
|
||||
use crate::config;
|
||||
use crate::schedule::Trigger;
|
||||
use crate::{AfterJobRun, CronError, CronJobs, Job, JobContext, JobOutcome, JobRun, JobStatus};
|
||||
use crate::{Overlap, RunTrigger, Schedule};
|
||||
|
|
@ -102,18 +102,19 @@ fn build(jobs: Vec<Job>, now: DateTime<Utc>) -> Result<Registry, CronError> {
|
|||
if !is_valid_key(&key) {
|
||||
return Err(CronError::InvalidKey(key));
|
||||
}
|
||||
let entry = Entry::new(job, SETTINGS.jobs.get(&key), default_tz, now).map_err(|err| {
|
||||
CronError::InvalidJob {
|
||||
key: key.clone(),
|
||||
source: Box::new(err),
|
||||
}
|
||||
})?;
|
||||
let entry =
|
||||
Entry::new(job, config::SETTINGS.jobs.get(&key), default_tz, now).map_err(|err| {
|
||||
CronError::InvalidJob {
|
||||
key: key.clone(),
|
||||
source: Box::new(err),
|
||||
}
|
||||
})?;
|
||||
if !keys.insert(key.clone()) {
|
||||
return Err(CronError::DuplicateJob(key));
|
||||
}
|
||||
entries.push(Arc::new(entry));
|
||||
}
|
||||
for key in SETTINGS.jobs.keys() {
|
||||
for key in config::SETTINGS.jobs.keys() {
|
||||
if !keys.contains(key) {
|
||||
trace::warn!("Unknown cron job \"{key}\" in [cron.jobs], ignored. Check settings");
|
||||
}
|
||||
|
|
@ -132,7 +133,7 @@ fn is_valid_key(key: &str) -> bool {
|
|||
// El modo externo necesita una clave larga y que se pueda escribir tal cual en la cabecera, y un
|
||||
// intervalo entre llamadas válido.
|
||||
fn check_external_settings() -> Result<(), CronError> {
|
||||
if SETTINGS.mode != CronMode::External {
|
||||
if config::SETTINGS.mode != config::CronMode::External {
|
||||
return Ok(());
|
||||
}
|
||||
let valid = trigger_token().is_some_and(|token| {
|
||||
|
|
@ -160,11 +161,14 @@ fn check_external_settings() -> Result<(), CronError> {
|
|||
}
|
||||
|
||||
fn trigger_token() -> Option<&'static str> {
|
||||
SETTINGS.trigger_token.as_deref().and_then(util::non_blank)
|
||||
config::SETTINGS
|
||||
.trigger_token
|
||||
.as_deref()
|
||||
.and_then(util::non_blank)
|
||||
}
|
||||
|
||||
fn trigger_interval() -> Option<Duration> {
|
||||
let secs = i64::try_from(SETTINGS.trigger_interval_secs).ok()?;
|
||||
let secs = i64::try_from(config::SETTINGS.trigger_interval_secs).ok()?;
|
||||
Duration::try_seconds(secs)
|
||||
.filter(|interval| *interval >= Duration::seconds(1) && *interval <= Duration::days(36_500))
|
||||
}
|
||||
|
|
@ -195,7 +199,7 @@ pub(crate) fn token_matches(given: &str) -> bool {
|
|||
impl Entry {
|
||||
fn new(
|
||||
job: Job,
|
||||
settings: Option<&JobSettings>,
|
||||
settings: Option<&config::JobSettings>,
|
||||
default_tz: Tz,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<Self, CronError> {
|
||||
|
|
@ -231,7 +235,7 @@ impl Entry {
|
|||
|
||||
// Con el modo externo, la próxima ejecución se conoce desde el arranque; la del arranque,
|
||||
// si la hay, la hace la primera llamada.
|
||||
let external = enabled && SETTINGS.mode == CronMode::External;
|
||||
let external = enabled && config::SETTINGS.mode == config::CronMode::External;
|
||||
let pending_start = external && job.run_on_start();
|
||||
let next_run = match (external, pending_start) {
|
||||
(true, true) => Some(now),
|
||||
|
|
@ -440,7 +444,7 @@ pub async fn run_now(key: impl AsRef<str>) -> Result<JobRun, CronError> {
|
|||
/// hasta el final. Si se abandona la espera (p. ej. el programa externo cierra la conexión), los
|
||||
/// trabajos siguen igualmente hasta terminar o agotar su tiempo máximo.
|
||||
pub async fn run_due() -> Vec<JobRun> {
|
||||
if SETTINGS.mode != CronMode::External {
|
||||
if config::SETTINGS.mode != config::CronMode::External {
|
||||
trace::warn!("Cron run_due() ignored: [cron].mode is not \"external\"");
|
||||
return Vec::new();
|
||||
}
|
||||
|
|
@ -493,17 +497,17 @@ pub(crate) fn start() {
|
|||
}
|
||||
let total = registry.entries.len();
|
||||
let enabled = registry.entries.iter().filter(|e| e.enabled).count();
|
||||
match SETTINGS.mode {
|
||||
CronMode::Internal => {
|
||||
match config::SETTINGS.mode {
|
||||
config::CronMode::Internal => {
|
||||
for entry in registry.entries.iter().filter(|e| e.enabled) {
|
||||
tokio::spawn(job_loop(Arc::clone(entry)));
|
||||
}
|
||||
trace::info!("Cron scheduler started with {enabled} of {total} jobs");
|
||||
}
|
||||
CronMode::External => trace::info!(
|
||||
config::CronMode::External => trace::info!(
|
||||
"Cron jobs ({enabled} of {total}) run on authorized calls to POST {TRIGGER_PATH}"
|
||||
),
|
||||
CronMode::Off => {
|
||||
config::CronMode::Off => {
|
||||
trace::info!("Cron jobs ({total}) only run on demand: [cron].mode is \"off\"");
|
||||
}
|
||||
}
|
||||
|
|
@ -674,7 +678,7 @@ pub(crate) async fn shutdown() {
|
|||
if active == 0 {
|
||||
return;
|
||||
}
|
||||
let limit = SETTINGS.shutdown_timeout_secs;
|
||||
let limit = config::SETTINGS.shutdown_timeout_secs;
|
||||
trace::info!("Waiting up to {limit} s for {active} running cron jobs to finish");
|
||||
let idle = async {
|
||||
loop {
|
||||
|
|
@ -707,7 +711,7 @@ mod tests {
|
|||
|
||||
// Settings come from this crate's `config/common.toml` (external mode, Madrid timezone).
|
||||
fn load_settings() {
|
||||
SETTINGS.load().unwrap();
|
||||
config::SETTINGS.load().unwrap();
|
||||
}
|
||||
|
||||
async fn noop(_cx: JobContext) -> crate::JobResult {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
|||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::config::{self, MailTransport, SmtpSecurity};
|
||||
use crate::config;
|
||||
use crate::{Email, LOCALES_MAIL, Mailbox};
|
||||
|
||||
// Ruta de la página, relativa a la raíz del panel.
|
||||
|
|
@ -124,8 +124,8 @@ async fn test_mail_post(
|
|||
// Aviso si el transporte configurado no entrega los correos.
|
||||
fn not_delivered_warning() -> Option<Lc> {
|
||||
let key = match config::SETTINGS.transport {
|
||||
MailTransport::Log => "test_log_warning",
|
||||
MailTransport::Memory => "test_memory_warning",
|
||||
config::MailTransport::Log => "test_log_warning",
|
||||
config::MailTransport::Memory => "test_memory_warning",
|
||||
_ => return None,
|
||||
};
|
||||
Some(Lc::t(key, &LOCALES_MAIL))
|
||||
|
|
@ -138,11 +138,11 @@ fn settings_summary() -> Block {
|
|||
let text = |value: &Option<String>| value.clone().map_or_else(none, Lc::n);
|
||||
|
||||
let transport = match settings.transport {
|
||||
MailTransport::Smtp => "transport_smtp",
|
||||
MailTransport::Sendmail => "transport_sendmail",
|
||||
MailTransport::File => "transport_file",
|
||||
MailTransport::Log => "transport_log",
|
||||
MailTransport::Memory => "transport_memory",
|
||||
config::MailTransport::Smtp => "transport_smtp",
|
||||
config::MailTransport::Sendmail => "transport_sendmail",
|
||||
config::MailTransport::File => "transport_file",
|
||||
config::MailTransport::Log => "transport_log",
|
||||
config::MailTransport::Memory => "transport_memory",
|
||||
};
|
||||
let mut rows = vec![
|
||||
("test_transport", Lc::t(transport, &LOCALES_MAIL)),
|
||||
|
|
@ -153,25 +153,25 @@ fn settings_summary() -> Block {
|
|||
rows.push(("test_redirect_to", text(&settings.redirect_to)));
|
||||
}
|
||||
match settings.transport {
|
||||
MailTransport::Smtp => {
|
||||
config::MailTransport::Smtp => {
|
||||
let smtp = &settings.smtp;
|
||||
let (security, default_port) = match smtp.security {
|
||||
SmtpSecurity::None => ("security_none", 25),
|
||||
SmtpSecurity::Opportunistic => ("security_opportunistic", 25),
|
||||
SmtpSecurity::StartTls => ("security_starttls", 587),
|
||||
SmtpSecurity::Tls => ("security_tls", 465),
|
||||
config::SmtpSecurity::None => ("security_none", 25),
|
||||
config::SmtpSecurity::Opportunistic => ("security_opportunistic", 25),
|
||||
config::SmtpSecurity::StartTls => ("security_starttls", 587),
|
||||
config::SmtpSecurity::Tls => ("security_tls", 465),
|
||||
};
|
||||
let port = smtp.port.unwrap_or(default_port).to_string();
|
||||
rows.push(("test_smtp_server", Lc::n(util::join!(smtp.host, ":", port))));
|
||||
rows.push(("test_smtp_security", Lc::t(security, &LOCALES_MAIL)));
|
||||
}
|
||||
MailTransport::Sendmail => {
|
||||
config::MailTransport::Sendmail => {
|
||||
rows.push(("test_sendmail_command", text(&settings.sendmail.command)));
|
||||
}
|
||||
MailTransport::File => {
|
||||
config::MailTransport::File => {
|
||||
rows.push(("test_file_dir", Lc::n(settings.file.dir.clone())));
|
||||
}
|
||||
MailTransport::Log | MailTransport::Memory => {}
|
||||
config::MailTransport::Log | config::MailTransport::Memory => {}
|
||||
}
|
||||
|
||||
let mut table = Table::new();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
use pagetop::prelude::*;
|
||||
|
||||
use crate::config::{self, MailTransport, SmtpSecurity, SmtpSettings};
|
||||
use crate::config;
|
||||
use crate::{Email, MailError, Mailbox, outbox};
|
||||
|
||||
use lettre::Transport as _;
|
||||
|
|
@ -289,22 +289,28 @@ impl Mailer {
|
|||
#[cfg(feature = "queue")]
|
||||
crate::queue::check_settings()?;
|
||||
let slots = match settings.transport {
|
||||
MailTransport::Smtp => slots("mail.smtp.pool_max_size", settings.smtp.pool_max_size)?,
|
||||
MailTransport::Sendmail => slots(
|
||||
config::MailTransport::Smtp => {
|
||||
slots("mail.smtp.pool_max_size", settings.smtp.pool_max_size)?
|
||||
}
|
||||
config::MailTransport::Sendmail => slots(
|
||||
"mail.sendmail.max_concurrent",
|
||||
settings.sendmail.max_concurrent,
|
||||
)?,
|
||||
MailTransport::File => slots("mail.file.max_concurrent", settings.file.max_concurrent)?,
|
||||
config::MailTransport::File => {
|
||||
slots("mail.file.max_concurrent", settings.file.max_concurrent)?
|
||||
}
|
||||
// Sin turnos: se entregan al momento.
|
||||
MailTransport::Log | MailTransport::Memory => 1,
|
||||
config::MailTransport::Log | config::MailTransport::Memory => 1,
|
||||
};
|
||||
let transport = match settings.transport {
|
||||
MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
|
||||
MailTransport::Sendmail => Transport::Sendmail(match &settings.sendmail.command {
|
||||
Some(command) => AsyncSendmailTransport::new_with_command(command),
|
||||
None => AsyncSendmailTransport::new(),
|
||||
}),
|
||||
MailTransport::File => {
|
||||
config::MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
|
||||
config::MailTransport::Sendmail => {
|
||||
Transport::Sendmail(match &settings.sendmail.command {
|
||||
Some(command) => AsyncSendmailTransport::new_with_command(command),
|
||||
None => AsyncSendmailTransport::new(),
|
||||
})
|
||||
}
|
||||
config::MailTransport::File => {
|
||||
let dir = PathBuf::from(&settings.file.dir);
|
||||
std::fs::create_dir_all(&dir).map_err(|source| MailError::CreateDir {
|
||||
path: dir.clone(),
|
||||
|
|
@ -312,8 +318,8 @@ impl Mailer {
|
|||
})?;
|
||||
Transport::File(AsyncFileTransport::new(dir))
|
||||
}
|
||||
MailTransport::Log => Transport::Log,
|
||||
MailTransport::Memory => Transport::Memory,
|
||||
config::MailTransport::Log => Transport::Log,
|
||||
config::MailTransport::Memory => Transport::Memory,
|
||||
};
|
||||
let redirect_to = match settings.redirect_to.as_deref().and_then(util::non_blank) {
|
||||
Some(address) => Some(address.parse::<Address>().map_err(|source| {
|
||||
|
|
@ -410,7 +416,7 @@ fn tickets(slots: usize, max_waiting: u32) -> usize {
|
|||
.min(Semaphore::MAX_PERMITS)
|
||||
}
|
||||
|
||||
fn smtp_transport(smtp: &SmtpSettings) -> Result<SmtpTransport, MailError> {
|
||||
fn smtp_transport(smtp: &config::SmtpSettings) -> Result<SmtpTransport, MailError> {
|
||||
let tls_parameters = || {
|
||||
TlsParameters::builder(smtp.host.clone())
|
||||
.dangerous_accept_invalid_certs(smtp.accept_invalid_certs)
|
||||
|
|
@ -418,10 +424,10 @@ fn smtp_transport(smtp: &SmtpSettings) -> Result<SmtpTransport, MailError> {
|
|||
.map_err(|err| invalid_setting("mail.smtp", MailError::Smtp(err)))
|
||||
};
|
||||
let (tls, default_port) = match smtp.security {
|
||||
SmtpSecurity::None => (Tls::None, 25),
|
||||
SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
|
||||
SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
|
||||
SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
|
||||
config::SmtpSecurity::None => (Tls::None, 25),
|
||||
config::SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
|
||||
config::SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
|
||||
config::SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
|
||||
};
|
||||
let mut builder = SmtpTransport::builder_dangerous(&smtp.host)
|
||||
.port(smtp.port.unwrap_or(default_port))
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
|||
use pagetop_seaorm::db::*;
|
||||
|
||||
use crate::account::UserStatus;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::{role_permission, user, user_identity};
|
||||
use crate::error::AuthError;
|
||||
use crate::identity::{self, Email, Username};
|
||||
|
|
@ -101,7 +101,7 @@ pub(crate) async fn login(
|
|||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
let fallback = SETTINGS.login.local_fallback;
|
||||
let fallback = config::SETTINGS.login.local_fallback;
|
||||
let mut released = false;
|
||||
if let Some(user) = local
|
||||
.as_ref()
|
||||
|
|
@ -288,7 +288,7 @@ pub async fn register(
|
|||
plain_password: &str,
|
||||
confirm_password: &str,
|
||||
) -> Result<i32, AuthError> {
|
||||
let username = identity::username(username, SETTINGS.identity_policy, None)?;
|
||||
let username = identity::username(username, config::SETTINGS.identity_policy, None)?;
|
||||
let email = identity::email(email)?;
|
||||
password::validate_strength(plain_password)?;
|
||||
password::passwords_match(plain_password, confirm_password)?;
|
||||
|
|
@ -297,7 +297,7 @@ pub async fn register(
|
|||
|
||||
let hash = password::hash_password_async(plain_password).await?;
|
||||
let now = Utc::now();
|
||||
let status = if SETTINGS.require_email_verification {
|
||||
let status = if config::SETTINGS.require_email_verification {
|
||||
UserStatus::Pending
|
||||
} else {
|
||||
UserStatus::Active
|
||||
|
|
@ -556,9 +556,9 @@ async fn register_failed_login(
|
|||
user_model.failed_login_at,
|
||||
now,
|
||||
FailedLoginPolicy {
|
||||
max: SETTINGS.max_failed_logins,
|
||||
window: Duration::seconds(SETTINGS.failed_login_window_secs),
|
||||
locked_for: Duration::seconds(SETTINGS.locked_for_secs),
|
||||
max: config::SETTINGS.max_failed_logins,
|
||||
window: Duration::seconds(config::SETTINGS.failed_login_window_secs),
|
||||
locked_for: Duration::seconds(config::SETTINGS.locked_for_secs),
|
||||
},
|
||||
);
|
||||
user::ActiveModel {
|
||||
|
|
@ -617,8 +617,8 @@ fn failed_login_outcome(
|
|||
/// Falla con [`AuthError::InvalidSetting`] si el nombre de usuario o el email configurados no son
|
||||
/// válidos, aunque ya existan usuarios, como cualquier otro ajuste no válido.
|
||||
pub(crate) async fn seed_initial_data() -> Result<(), AuthError> {
|
||||
let cfg = &SETTINGS.seed;
|
||||
let username = identity::username(&cfg.admin_username, SETTINGS.identity_policy, None)
|
||||
let cfg = &config::SETTINGS.seed;
|
||||
let username = identity::username(&cfg.admin_username, config::SETTINGS.identity_policy, None)
|
||||
.map_err(|err| invalid_setting("user.seed.admin_username", err))?;
|
||||
let email = identity::email(&cfg.admin_email)
|
||||
.map_err(|err| invalid_setting("user.seed.admin_email", err))?;
|
||||
|
|
@ -639,7 +639,7 @@ async fn do_seed(username: Username, email: Email) {
|
|||
return;
|
||||
}
|
||||
|
||||
let cfg = &SETTINGS.seed;
|
||||
let cfg = &config::SETTINGS.seed;
|
||||
let (admin_password, generated) = match &cfg.admin_password {
|
||||
Some(p) if !p.is_empty() => (p.clone(), false),
|
||||
_ => {
|
||||
|
|
|
|||
|
|
@ -26,10 +26,9 @@ use pagetop::prelude::*;
|
|||
|
||||
use crate::account::UserStatus;
|
||||
use crate::component::admin::status_key;
|
||||
use crate::config::{user_language_applies, user_timezone_applies};
|
||||
use crate::entity::user;
|
||||
use crate::provider;
|
||||
use crate::{LOCALES_USER, PROFILE_PATH};
|
||||
use crate::{config, provider};
|
||||
|
||||
// Texto libre de varias líneas como contenido seguro: cada salto de línea se convierte en `<br>`,
|
||||
// sin depender del CSS del tema. Se usa para mostrar el "Sobre mí" del usuario.
|
||||
|
|
@ -138,26 +137,28 @@ pub(crate) async fn user_details(user: &user::Model, cx: &mut Context) -> Block
|
|||
)),
|
||||
);
|
||||
// Sólo se muestran si se aplican, igual que en el formulario de edición.
|
||||
if user_language_applies() {
|
||||
if config::user_language_applies() {
|
||||
table = table.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(Lc::t("field-language", &LOCALES_USER))
|
||||
.with_cell(language_name(user.language.as_deref())),
|
||||
);
|
||||
}
|
||||
if user_timezone_applies() {
|
||||
if config::user_timezone_applies() {
|
||||
table = table.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(Lc::t("field-timezone", &LOCALES_USER))
|
||||
.with_cell(user.timezone.as_deref().unwrap_or("-")),
|
||||
);
|
||||
}
|
||||
table = table
|
||||
.with_row(
|
||||
if config::user_theme_applies() {
|
||||
table = table.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(Lc::t("field-theme", &LOCALES_USER))
|
||||
.with_cell(theme_name(user.theme.as_deref())),
|
||||
)
|
||||
);
|
||||
}
|
||||
table = table
|
||||
.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(Lc::t("col-status", &LOCALES_USER))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::{LOCALES_USER, LOGIN_PATH, LOGOUT_PATH, PROFILE_PATH, REGISTER_PATH};
|
||||
|
||||
/// Construye el menú de cuenta como un [`Nav`] justificado al final de su contenedor.
|
||||
|
|
@ -59,7 +59,7 @@ pub fn account_menu(cx: &Context) -> Nav {
|
|||
Lc::t("menu-login", &LOCALES_USER),
|
||||
cx.route(LOGIN_PATH),
|
||||
));
|
||||
if SETTINGS.allow_registration {
|
||||
if config::SETTINGS.allow_registration {
|
||||
nav.with_item(nav::Item::link(
|
||||
Lc::t("link-register", &LOCALES_USER),
|
||||
cx.route(REGISTER_PATH),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::LOCALES_USER;
|
||||
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
||||
use crate::config;
|
||||
use crate::user_path;
|
||||
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
|
||||
|
||||
|
|
@ -102,12 +102,12 @@ impl Component for UserForm {
|
|||
} else if username_readonly {
|
||||
Lc::none()
|
||||
} else {
|
||||
username_help(SETTINGS.identity_policy)
|
||||
username_help(config::SETTINGS.identity_policy)
|
||||
})
|
||||
.with_required(true)
|
||||
.with_readonly(username_readonly)
|
||||
.with_minlength(USERNAME_MIN_CHARS)
|
||||
.with_maxlength(username_max_chars(SETTINGS.identity_policy)),
|
||||
.with_maxlength(username_max_chars(config::SETTINGS.identity_policy)),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
|
|
@ -135,9 +135,9 @@ impl Component for UserForm {
|
|||
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
|
||||
);
|
||||
|
||||
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y
|
||||
// `config::user_timezone_applies()`).
|
||||
if user_language_applies() {
|
||||
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()`,
|
||||
// `config::user_timezone_applies()` y `config::user_theme_applies()`).
|
||||
if config::user_language_applies() {
|
||||
form = form.with_child(
|
||||
form::SelectLanguage::new()
|
||||
.with_name("language")
|
||||
|
|
@ -146,7 +146,7 @@ impl Component for UserForm {
|
|||
.with_selected(self.language()),
|
||||
);
|
||||
}
|
||||
if user_timezone_applies() {
|
||||
if config::user_timezone_applies() {
|
||||
form = form.with_child(
|
||||
form::SelectTimezone::new()
|
||||
.with_name("timezone")
|
||||
|
|
@ -156,13 +156,15 @@ impl Component for UserForm {
|
|||
.with_selected(self.timezone()),
|
||||
);
|
||||
}
|
||||
form = form.with_child(
|
||||
form::SelectTheme::new()
|
||||
.with_name("theme")
|
||||
.with_label(Lc::t("field-theme", &LOCALES_USER))
|
||||
.with_disabled(managed(UserField::Theme))
|
||||
.with_selected(self.theme()),
|
||||
);
|
||||
if config::user_theme_applies() {
|
||||
form = form.with_child(
|
||||
form::SelectTheme::new()
|
||||
.with_name("theme")
|
||||
.with_label(Lc::t("field-theme", &LOCALES_USER))
|
||||
.with_disabled(managed(UserField::Theme))
|
||||
.with_selected(self.theme()),
|
||||
);
|
||||
}
|
||||
|
||||
match (self.mode(), self.provider()) {
|
||||
// Una cuenta que entrará con un proveedor no tiene contraseña local.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::component::error_banner;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::provider::{self, HelpLink, ResetLink};
|
||||
use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ impl Component for LoginForm {
|
|||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let action = self.waypoint().append_to(cx.route(LOGIN_PATH));
|
||||
let strict = SETTINGS.login.strict;
|
||||
let strict = config::SETTINGS.login.strict;
|
||||
let (notes, reset) = provider::login_hints();
|
||||
|
||||
// En modo estricto se dificulta que el navegador recuerde o autorrellene las
|
||||
|
|
@ -83,7 +83,7 @@ impl Component for LoginForm {
|
|||
Button::submit(Lc::t("btn-login", &LOCALES_USER))
|
||||
.with_style(button::Style::Solid(Intent::Primary)),
|
||||
)
|
||||
.with_child(links(SETTINGS.allow_registration, notes, reset));
|
||||
.with_child(links(config::SETTINGS.allow_registration, notes, reset));
|
||||
|
||||
if strict {
|
||||
form = form
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::LOCALES_USER;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
|
||||
/// Campos de contraseña y confirmación, compuestos a partir de
|
||||
/// [`form::input::Field::password()`] del core. No valida en ningún momento que ambos valores
|
||||
|
|
@ -35,7 +35,7 @@ impl Component for PasswordConfirm {
|
|||
// `minlength` cuenta unidades UTF-16 y el servidor caracteres: con caracteres fuera del
|
||||
// plano básico (emojis) el navegador puede aceptar una contraseña que el servidor rechaza,
|
||||
// pero nunca al revés.
|
||||
let min_length = SETTINGS.password.min_length;
|
||||
let min_length = config::SETTINGS.password.min_length;
|
||||
let mut password = form::input::Field::password()
|
||||
.with_name("password")
|
||||
.with_label(self.password_label().clone())
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
|||
use crate::LOCALES_USER;
|
||||
use crate::REGISTER_PATH;
|
||||
use crate::component::{PasswordConfirm, error_banner};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
|
||||
|
||||
/// Formulario de registro de una cuenta nueva.
|
||||
|
|
@ -37,9 +37,9 @@ impl Component for RegisterForm {
|
|||
.with_name("username")
|
||||
.with_value(&self.username)
|
||||
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
|
||||
.with_help_text(username_help(SETTINGS.identity_policy))
|
||||
.with_help_text(username_help(config::SETTINGS.identity_policy))
|
||||
.with_minlength(USERNAME_MIN_CHARS)
|
||||
.with_maxlength(username_max_chars(SETTINGS.identity_policy))
|
||||
.with_maxlength(username_max_chars(config::SETTINGS.identity_policy))
|
||||
.with_autocomplete(Some(form::Autocomplete::username()))
|
||||
.with_autofocus(true)
|
||||
.with_required(true),
|
||||
|
|
|
|||
|
|
@ -427,6 +427,12 @@ pub(crate) fn user_timezone_applies() -> bool {
|
|||
global::SETTINGS.app.timezone_per_user
|
||||
}
|
||||
|
||||
// Si se aplica el tema propio del usuario (`app.theme_per_user`). Si no se aplica, no se ofrece
|
||||
// elegirlo ni se borra el guardado.
|
||||
pub(crate) fn user_theme_applies() -> bool {
|
||||
global::SETTINGS.app.theme_per_user
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{UserSettings, config};
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use pagetop::prelude::*;
|
|||
use pagetop_seaorm::db::*;
|
||||
|
||||
use crate::account::UserStatus;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::{role, user, user_role};
|
||||
use crate::error::AuthError;
|
||||
use crate::identity;
|
||||
|
|
@ -91,8 +91,11 @@ async fn create_demo_users(
|
|||
let now = Utc::now();
|
||||
|
||||
for n in 1..=USER_COUNT {
|
||||
let username =
|
||||
identity::username(&format!("demo_user_{n:02}"), SETTINGS.identity_policy, None)?;
|
||||
let username = identity::username(
|
||||
&format!("demo_user_{n:02}"),
|
||||
config::SETTINGS.identity_policy,
|
||||
None,
|
||||
)?;
|
||||
let email = identity::email(&format!("demo_user_{n:02}@example.com"))?;
|
||||
let mut new_user = user::ActiveModel {
|
||||
id: ActiveValue::NotSet,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use crate::LOCALES_USER;
|
|||
use crate::component::admin::{
|
||||
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable, delete_dialog,
|
||||
};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::role;
|
||||
use crate::handlers::admin::{back_link, map_auth_error};
|
||||
use crate::permission::UserPermission;
|
||||
|
|
@ -38,7 +38,7 @@ pub(crate) async fn list_get(
|
|||
sort: RoleSortField::from_query(query.sort.as_deref()),
|
||||
dir: SortDir::from_query(query.dir.as_deref()),
|
||||
page: query.page.unwrap_or(1).max(1),
|
||||
per_page: SETTINGS.admin.list_page_size,
|
||||
per_page: config::SETTINGS.admin.list_page_size,
|
||||
};
|
||||
|
||||
let result = match role_admin::list_roles_page(¶ms).await {
|
||||
|
|
@ -350,7 +350,7 @@ pub(crate) async fn delete_post(
|
|||
sort: RoleSortField::from_query(query.sort.as_deref()),
|
||||
dir: SortDir::from_query(query.dir.as_deref()),
|
||||
page: query.page.unwrap_or(1).max(1),
|
||||
per_page: SETTINGS.admin.list_page_size,
|
||||
per_page: config::SETTINGS.admin.list_page_size,
|
||||
};
|
||||
let page_result = role_admin::list_roles_page(¶ms)
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ use crate::component::admin::{
|
|||
AdminPasswordForm, USER_ADMIN_FORM_ID, UserForm, UserFormMode, UserTable,
|
||||
};
|
||||
use crate::component::{cancel_link, user_details};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::{role, user};
|
||||
use crate::error::AuthError;
|
||||
use crate::handlers::account::managed_or;
|
||||
|
|
@ -51,7 +51,7 @@ pub(crate) async fn list_get(
|
|||
sort: UserSortField::from_query(query.sort.as_deref()),
|
||||
dir: SortDir::from_query(query.dir.as_deref()),
|
||||
page: query.page.unwrap_or(1).max(1),
|
||||
per_page: SETTINGS.admin.list_page_size,
|
||||
per_page: config::SETTINGS.admin.list_page_size,
|
||||
};
|
||||
|
||||
let result = match user_admin::list_users(¶ms).await {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use pagetop_htmx::prelude::*;
|
|||
|
||||
use crate::auth;
|
||||
use crate::component::{LoginForm, PasswordResetConfirmForm, PasswordResetForm, RegisterForm};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::error::AuthError;
|
||||
use crate::handlers::admin::map_auth_error;
|
||||
use crate::handlers::{confirm_page, message_page, no_referrer};
|
||||
|
|
@ -195,7 +195,7 @@ pub async fn logout_post(request: HttpRequest) -> Response {
|
|||
|
||||
/// GET /user/register - Formulario de registro de cuenta.
|
||||
pub async fn register_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
if !SETTINGS.allow_registration {
|
||||
if !config::SETTINGS.allow_registration {
|
||||
return Err(ErrorPage::NotFound(request));
|
||||
}
|
||||
Page::new(request)
|
||||
|
|
@ -212,7 +212,7 @@ pub async fn register_post(
|
|||
request: HttpRequest,
|
||||
web::Form(form): web::Form<RegisterFormData>,
|
||||
) -> Response {
|
||||
if !SETTINGS.allow_registration {
|
||||
if !config::SETTINGS.allow_registration {
|
||||
return ErrorPage::NotFound(request).into_response();
|
||||
}
|
||||
let cx = Context::new(request.clone());
|
||||
|
|
@ -228,7 +228,7 @@ pub async fn register_post(
|
|||
Err(AuthError::TooManyRequests)
|
||||
};
|
||||
match result {
|
||||
Ok(user_id) if SETTINGS.require_email_verification => {
|
||||
Ok(user_id) if config::SETTINGS.require_email_verification => {
|
||||
send_verification_mail(&request, user_id).await;
|
||||
let title = Lc::t("title-register", &LOCALES_USER);
|
||||
message_page(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Nombre de usuario y email que identifican una cuenta: normalización y validación.
|
||||
//!
|
||||
//! Las reglas públicas se documentan en `IdentityPolicy`. Aquí se separan dos cosas:
|
||||
//! Las reglas públicas se documentan en `config::IdentityPolicy`. Aquí se separan dos cosas:
|
||||
//!
|
||||
//! - **Buscar y comparar**, igual con cualquier política: `*_key` (sin espacios en los extremos,
|
||||
//! NFKC en el nombre de usuario y en minúsculas) y el esqueleto de confusión del nombre
|
||||
|
|
@ -23,7 +23,7 @@ use unicode_security::{GeneralSecurityProfile, MixedScript, skeleton};
|
|||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::LOCALES_USER;
|
||||
use crate::config::IdentityPolicy;
|
||||
use crate::config;
|
||||
use crate::entity::user;
|
||||
use crate::error::AuthError;
|
||||
|
||||
|
|
@ -35,10 +35,10 @@ pub(crate) const USERNAME_MIN_CHARS: u16 = 3;
|
|||
pub(crate) const EMAIL_MAX_CHARS: u16 = 254;
|
||||
|
||||
// Longitud máxima del nombre de usuario según la política. La de `Permissive` es la de Drupal.
|
||||
pub(crate) fn username_max_chars(policy: IdentityPolicy) -> u16 {
|
||||
pub(crate) fn username_max_chars(policy: config::IdentityPolicy) -> u16 {
|
||||
match policy {
|
||||
IdentityPolicy::Strict | IdentityPolicy::Unicode => 32,
|
||||
IdentityPolicy::Permissive => 60,
|
||||
config::IdentityPolicy::Strict | config::IdentityPolicy::Unicode => 32,
|
||||
config::IdentityPolicy::Permissive => 60,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ impl Username {
|
|||
// más abierta pueda seguir guardando su perfil.
|
||||
pub(crate) fn username(
|
||||
raw: &str,
|
||||
policy: IdentityPolicy,
|
||||
policy: config::IdentityPolicy,
|
||||
current_key: Option<&str>,
|
||||
) -> Result<Username, AuthError> {
|
||||
let value = raw.trim().nfkc().collect::<String>();
|
||||
|
|
@ -119,10 +119,10 @@ fn skeleton_hash(key: &str) -> String {
|
|||
// clases que definen los identificadores de Rust (XID, UAX #31), que incluyen las marcas
|
||||
// combinables de escrituras como el devanagari; `identifier_allowed()` descarta los caracteres
|
||||
// que UTS #39 desaconseja (invisibles, obsoletos...) y `is_single_script()` la mezcla de alfabetos.
|
||||
fn accepts(name: &str, policy: IdentityPolicy) -> bool {
|
||||
fn accepts(name: &str, policy: config::IdentityPolicy) -> bool {
|
||||
let symbols: &[char] = match policy {
|
||||
IdentityPolicy::Strict | IdentityPolicy::Unicode => &['.', '_', '-'],
|
||||
IdentityPolicy::Permissive => &['.', '_', '-', ' ', '\'', '+'],
|
||||
config::IdentityPolicy::Strict | config::IdentityPolicy::Unicode => &['.', '_', '-'],
|
||||
config::IdentityPolicy::Permissive => &['.', '_', '-', ' ', '\'', '+'],
|
||||
};
|
||||
let length = usize::from(USERNAME_MIN_CHARS)..=usize::from(username_max_chars(policy));
|
||||
if !length.contains(&name.chars().count()) {
|
||||
|
|
@ -132,13 +132,13 @@ fn accepts(name: &str, policy: IdentityPolicy) -> bool {
|
|||
return false;
|
||||
};
|
||||
match policy {
|
||||
IdentityPolicy::Strict => {
|
||||
config::IdentityPolicy::Strict => {
|
||||
first.is_ascii_alphanumeric()
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || symbols.contains(&c))
|
||||
}
|
||||
IdentityPolicy::Unicode | IdentityPolicy::Permissive => {
|
||||
config::IdentityPolicy::Unicode | config::IdentityPolicy::Permissive => {
|
||||
let letter_or_digit = |c: char| {
|
||||
c.identifier_allowed()
|
||||
&& (is_xid_start(c) || (is_xid_continue(c) && c.is_numeric()))
|
||||
|
|
@ -196,11 +196,11 @@ pub(crate) fn email_key(raw: &str) -> String {
|
|||
// **< Textos >*************************************************************************************
|
||||
|
||||
// Reglas del nombre de usuario de la política, como texto de ayuda de los formularios.
|
||||
pub(crate) fn username_help(policy: IdentityPolicy) -> Lc {
|
||||
pub(crate) fn username_help(policy: config::IdentityPolicy) -> Lc {
|
||||
let key = match policy {
|
||||
IdentityPolicy::Strict => "help-username-strict",
|
||||
IdentityPolicy::Unicode => "help-username-unicode",
|
||||
IdentityPolicy::Permissive => "help-username-permissive",
|
||||
config::IdentityPolicy::Strict => "help-username-strict",
|
||||
config::IdentityPolicy::Unicode => "help-username-unicode",
|
||||
config::IdentityPolicy::Permissive => "help-username-permissive",
|
||||
};
|
||||
Lc::t(key, &LOCALES_USER)
|
||||
.with_number("min", u32::from(USERNAME_MIN_CHARS))
|
||||
|
|
@ -211,14 +211,18 @@ pub(crate) fn username_help(policy: IdentityPolicy) -> Lc {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn accepted(raw: &str, policy: IdentityPolicy) -> bool {
|
||||
fn accepted(raw: &str, policy: config::IdentityPolicy) -> bool {
|
||||
username(raw, policy, None).is_ok()
|
||||
}
|
||||
|
||||
fn skeleton_of(raw: &str) -> String {
|
||||
username(raw, IdentityPolicy::Permissive, Some(&username_key(raw)))
|
||||
.unwrap()
|
||||
.skeleton
|
||||
username(
|
||||
raw,
|
||||
config::IdentityPolicy::Permissive,
|
||||
Some(&username_key(raw)),
|
||||
)
|
||||
.unwrap()
|
||||
.skeleton
|
||||
}
|
||||
|
||||
const ALWAYS_REJECTED: &[&str] = &[
|
||||
|
|
@ -234,13 +238,13 @@ mod tests {
|
|||
|
||||
#[pagetop::test]
|
||||
async fn strict_accepts_only_ascii_identifiers() {
|
||||
let name = username(" Ana.Perez_01 ", IdentityPolicy::Strict, None).unwrap();
|
||||
let name = username(" Ana.Perez_01 ", config::IdentityPolicy::Strict, None).unwrap();
|
||||
assert_eq!(name.value, "Ana.Perez_01", "the value keeps its case");
|
||||
assert_eq!(name.key, "ana.perez_01");
|
||||
assert!(accepted("a-b", IdentityPolicy::Strict));
|
||||
assert!(accepted("a-b", config::IdentityPolicy::Strict));
|
||||
// Full-width letters are normalized to ASCII (NFKC).
|
||||
assert_eq!(
|
||||
username("Ana", IdentityPolicy::Strict, None)
|
||||
username("Ana", config::IdentityPolicy::Strict, None)
|
||||
.unwrap()
|
||||
.value,
|
||||
"Ana"
|
||||
|
|
@ -253,7 +257,7 @@ mod tests {
|
|||
.chain(["peña", "аna", "ana perez", too_long.as_str()])
|
||||
{
|
||||
assert!(
|
||||
!accepted(name, IdentityPolicy::Strict),
|
||||
!accepted(name, config::IdentityPolicy::Strict),
|
||||
"{name:?} must be rejected"
|
||||
);
|
||||
}
|
||||
|
|
@ -274,7 +278,7 @@ mod tests {
|
|||
"ana_01",
|
||||
] {
|
||||
assert!(
|
||||
accepted(name, IdentityPolicy::Unicode),
|
||||
accepted(name, config::IdentityPolicy::Unicode),
|
||||
"{name:?} must be accepted"
|
||||
);
|
||||
}
|
||||
|
|
@ -288,7 +292,7 @@ mod tests {
|
|||
too_long.as_str(),
|
||||
]) {
|
||||
assert!(
|
||||
!accepted(name, IdentityPolicy::Unicode),
|
||||
!accepted(name, config::IdentityPolicy::Unicode),
|
||||
"{name:?} must be rejected"
|
||||
);
|
||||
}
|
||||
|
|
@ -298,7 +302,7 @@ mod tests {
|
|||
async fn permissive_adds_spaces_apostrophes_and_plus() {
|
||||
for name in ["Ana Pérez", "O'Brien", "ana+test", "José María"] {
|
||||
assert!(
|
||||
accepted(name, IdentityPolicy::Permissive),
|
||||
accepted(name, config::IdentityPolicy::Permissive),
|
||||
"{name:?} must be accepted"
|
||||
);
|
||||
}
|
||||
|
|
@ -310,7 +314,7 @@ mod tests {
|
|||
.chain(["ana perez", "pаypal", too_long.as_str()])
|
||||
{
|
||||
assert!(
|
||||
!accepted(name, IdentityPolicy::Permissive),
|
||||
!accepted(name, config::IdentityPolicy::Permissive),
|
||||
"{name:?} must be rejected"
|
||||
);
|
||||
}
|
||||
|
|
@ -328,7 +332,7 @@ mod tests {
|
|||
// the column, whatever the name.
|
||||
#[pagetop::test]
|
||||
async fn longest_names_fit_their_columns() {
|
||||
let name = username(&"꽦".repeat(60), IdentityPolicy::Permissive, None).unwrap();
|
||||
let name = username(&"꽦".repeat(60), config::IdentityPolicy::Permissive, None).unwrap();
|
||||
assert_eq!(name.skeleton.len(), 64);
|
||||
assert!(name.key.chars().count() <= 255);
|
||||
}
|
||||
|
|
@ -336,8 +340,8 @@ mod tests {
|
|||
#[pagetop::test]
|
||||
async fn unchanged_names_skip_the_policy() {
|
||||
let current = username_key("Ana Pérez");
|
||||
assert!(username("ana pérez", IdentityPolicy::Strict, Some(¤t)).is_ok());
|
||||
assert!(username("Eva Pérez", IdentityPolicy::Strict, Some(¤t)).is_err());
|
||||
assert!(username("ana pérez", config::IdentityPolicy::Strict, Some(¤t)).is_ok());
|
||||
assert!(username("Eva Pérez", config::IdentityPolicy::Strict, Some(¤t)).is_err());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ use pagetop::prelude::*;
|
|||
|
||||
use crate::account::{Account, PermissionSet};
|
||||
use crate::actions::AfterSessionResolved;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::session;
|
||||
|
||||
// Permisos del rol "anonymous", insertados en las peticiones sin sesión. Un tipo propio para que no
|
||||
|
|
@ -62,7 +62,7 @@ pub(crate) async fn session_middleware(
|
|||
// sesión). Las demás (mensajes, estado de un listado) conviven con la renovación: si la
|
||||
// impidieran, la cookie caducaría en el navegador antes que la sesión.
|
||||
if let Some(cookie) = renewed_cookie
|
||||
&& !sets_cookie(response.headers(), &SETTINGS.session.cookie_name)
|
||||
&& !sets_cookie(response.headers(), &config::SETTINGS.session.cookie_name)
|
||||
{
|
||||
match web::http::HeaderValue::try_from(cookie) {
|
||||
Ok(value) => {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use rand_core::OsRng;
|
|||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::error::AuthError;
|
||||
|
||||
// Lo que se guarda como contraseña de una cuenta sin contraseña local (las que gestiona un
|
||||
|
|
@ -22,9 +22,9 @@ pub(crate) const UNUSABLE_HASH: &str = "!external";
|
|||
/// Genera el hash PHC de una contraseña usando Argon2id con los parámetros configurados.
|
||||
pub fn hash_password(plain: &str) -> Result<String, AuthError> {
|
||||
let params = ParamsBuilder::new()
|
||||
.m_cost(SETTINGS.password.argon2_m_cost)
|
||||
.t_cost(SETTINGS.password.argon2_t_cost)
|
||||
.p_cost(SETTINGS.password.argon2_p_cost)
|
||||
.m_cost(config::SETTINGS.password.argon2_m_cost)
|
||||
.t_cost(config::SETTINGS.password.argon2_t_cost)
|
||||
.p_cost(config::SETTINGS.password.argon2_p_cost)
|
||||
.build()
|
||||
.map_err(|e| AuthError::PasswordHash(e.to_string()))?;
|
||||
|
||||
|
|
@ -85,7 +85,7 @@ pub fn needs_rehash(phc: &str) -> bool {
|
|||
return true;
|
||||
};
|
||||
let cost = |name: &str| parsed.params.get_decimal(name);
|
||||
let password = &SETTINGS.password;
|
||||
let password = &config::SETTINGS.password;
|
||||
parsed.algorithm != argon2::Algorithm::Argon2id.ident()
|
||||
|| cost("m") != Some(password.argon2_m_cost)
|
||||
|| cost("t") != Some(password.argon2_t_cost)
|
||||
|
|
@ -94,7 +94,7 @@ pub fn needs_rehash(phc: &str) -> bool {
|
|||
|
||||
/// Valida la longitud mínima, en caracteres, y devuelve error si no se cumple.
|
||||
pub fn validate_strength(plain: &str) -> Result<(), AuthError> {
|
||||
let min = SETTINGS.password.min_length;
|
||||
let min = config::SETTINGS.password.min_length;
|
||||
if plain.chars().count() < min {
|
||||
Err(AuthError::PasswordTooShort(min))
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ use pagetop::prelude::*;
|
|||
use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
|
||||
|
||||
use crate::account::UserStatus;
|
||||
use crate::config::{LocalFallback, SETTINGS};
|
||||
use crate::config;
|
||||
use crate::entity::{user, user_identity};
|
||||
use crate::error::AuthError;
|
||||
|
||||
|
|
@ -240,8 +240,8 @@ pub trait AuthProvider: Send + Sync + 'static {
|
|||
///
|
||||
/// Una cuenta liberada se trata como local:
|
||||
///
|
||||
/// - **Al iniciar sesión**, con [`LocalFallback::Released`], puede entrar con su contraseña
|
||||
/// local aunque `"local"` no esté en `sources`.
|
||||
/// - **Al iniciar sesión**, con [`config::LocalFallback::Released`], puede entrar con su
|
||||
/// contraseña local aunque `"local"` no esté en `sources`.
|
||||
/// - **Al confirmar una operación sensible** (cambiar el email o la contraseña), se comprueba
|
||||
/// su contraseña local en lugar de llamar a [`reauthenticate()`](Self::reauthenticate).
|
||||
///
|
||||
|
|
@ -417,7 +417,7 @@ pub(crate) fn initialize() -> Result<(), AuthError> {
|
|||
}
|
||||
let mut declared = AuthProviders::default();
|
||||
dispatch_actions(|action: &DeclareAuthProviders| (action.f)(&mut declared));
|
||||
let sources = resolve_sources(&SETTINGS.login.sources, &declared.providers)?;
|
||||
let sources = resolve_sources(&config::SETTINGS.login.sources, &declared.providers)?;
|
||||
|
||||
for provider in &declared.providers {
|
||||
if !sources
|
||||
|
|
@ -432,7 +432,7 @@ pub(crate) fn initialize() -> Result<(), AuthError> {
|
|||
}
|
||||
}
|
||||
let has_providers = sources.iter().any(|s| matches!(s, Source::Provider(_)));
|
||||
if has_providers && SETTINGS.allow_registration {
|
||||
if has_providers && config::SETTINGS.allow_registration {
|
||||
trace::warn!(
|
||||
"Local registration is open (user.allow_registration) while an authentication \
|
||||
provider is active: anyone can create a local account, and a name taken here can \
|
||||
|
|
@ -503,15 +503,15 @@ pub(crate) fn local_is_source() -> bool {
|
|||
// cuenta que algún proveedor libera (`released`) con `Released` o `Admins`.
|
||||
pub(crate) fn login_chain(
|
||||
sources: &[Source],
|
||||
fallback: LocalFallback,
|
||||
fallback: config::LocalFallback,
|
||||
local: Option<&UserRef>,
|
||||
released: bool,
|
||||
) -> Vec<Source> {
|
||||
let mut chain = Vec::with_capacity(sources.len() + 1);
|
||||
let has_local = sources.iter().any(|s| matches!(s, Source::Local));
|
||||
if !has_local && let Some(user) = local {
|
||||
let admin = fallback == LocalFallback::Admins && user.is_admin();
|
||||
let freed = fallback != LocalFallback::None && released;
|
||||
let admin = fallback == config::LocalFallback::Admins && user.is_admin();
|
||||
let freed = fallback != config::LocalFallback::None && released;
|
||||
if admin || freed {
|
||||
chain.push(Source::Local);
|
||||
}
|
||||
|
|
@ -521,10 +521,13 @@ pub(crate) fn login_chain(
|
|||
}
|
||||
|
||||
// Si hace falta preguntar a los proveedores si liberan la cuenta para construir la cadena.
|
||||
pub(crate) fn needs_release_check(fallback: LocalFallback, local: Option<&UserRef>) -> bool {
|
||||
pub(crate) fn needs_release_check(
|
||||
fallback: config::LocalFallback,
|
||||
local: Option<&UserRef>,
|
||||
) -> bool {
|
||||
!local_is_source()
|
||||
&& fallback != LocalFallback::None
|
||||
&& local.is_some_and(|user| !(fallback == LocalFallback::Admins && user.is_admin()))
|
||||
&& fallback != config::LocalFallback::None
|
||||
&& local.is_some_and(|user| !(fallback == config::LocalFallback::Admins && user.is_admin()))
|
||||
}
|
||||
|
||||
// Proveedores (por identificador) a los que está vinculada la cuenta; vacío si es local.
|
||||
|
|
@ -668,7 +671,7 @@ mod tests {
|
|||
let both = resolve_sources(&ids(&["fake", "local"]), &declared).unwrap();
|
||||
let admin = user(true);
|
||||
let plain = user(false);
|
||||
use LocalFallback::*;
|
||||
use config::LocalFallback::*;
|
||||
|
||||
// "local" already in the sources: the chain is the configured one.
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use pagetop_seaorm::db::*;
|
|||
|
||||
use crate::account::UserStatus;
|
||||
use crate::actions::AfterUserStatusChanged;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::{role, session, user, user_identity, user_role, user_token};
|
||||
use crate::error::AuthError;
|
||||
use crate::identity::{self, Email, Username};
|
||||
|
|
@ -22,7 +22,8 @@ use crate::service::user_admin::{
|
|||
/// Aplica la política de identidad configurada ([`IdentityPolicy`](crate::config::IdentityPolicy))
|
||||
/// y lo devuelve normalizado, tal como se guardaría. No comprueba si está en uso.
|
||||
pub fn validate_username(username: &str) -> Result<String, AuthError> {
|
||||
identity::username(username, SETTINGS.identity_policy, None).map(|u| u.value().to_owned())
|
||||
identity::username(username, config::SETTINGS.identity_policy, None)
|
||||
.map(|u| u.value().to_owned())
|
||||
}
|
||||
|
||||
/// Comprueba que `email` es una dirección válida y la devuelve tal como se guardaría.
|
||||
|
|
@ -375,7 +376,7 @@ impl ProviderHandle {
|
|||
) {
|
||||
return Err(AuthError::InvalidStatus);
|
||||
}
|
||||
let username = identity::username(&data.username, SETTINGS.identity_policy, None)?;
|
||||
let username = identity::username(&data.username, config::SETTINGS.identity_policy, None)?;
|
||||
let email = identity::email(&data.email)?;
|
||||
ensure_username_available(&username, None).await?;
|
||||
ensure_email_available(&email, None).await?;
|
||||
|
|
@ -723,7 +724,7 @@ impl ProviderHandle {
|
|||
let current = find_user(user_id).await?;
|
||||
let username: Username = identity::username(
|
||||
new_username,
|
||||
SETTINGS.identity_policy,
|
||||
config::SETTINGS.identity_policy,
|
||||
Some(¤t.username_key),
|
||||
)?;
|
||||
ensure_username_available(&username, Some(user_id)).await?;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use pagetop::prelude::*;
|
|||
use pagetop_seaorm::db::*;
|
||||
|
||||
use crate::account::UserStatus;
|
||||
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
||||
use crate::config;
|
||||
use crate::entity::{role, user, user_role};
|
||||
use crate::error::AuthError;
|
||||
use crate::identity::{self, Email, Username};
|
||||
|
|
@ -211,25 +211,29 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
|
|||
if data.link_provider.is_some() && data.is_admin {
|
||||
return Err(AuthError::ProtectedAccount);
|
||||
}
|
||||
let username = identity::username(data.username, SETTINGS.identity_policy, None)?;
|
||||
let username = identity::username(data.username, config::SETTINGS.identity_policy, None)?;
|
||||
let email = identity::email(data.email)?;
|
||||
if let Some((plain, confirm)) = data.password {
|
||||
password::validate_strength(plain)?;
|
||||
password::passwords_match(plain, confirm)?;
|
||||
}
|
||||
// El idioma y la zona horaria que no se aplican no se ofrecen en el formulario: se ignora lo
|
||||
// que pudiera llegar y el usuario se crea sin ellos.
|
||||
let language = if user_language_applies() {
|
||||
// El idioma, la zona horaria y el tema que no se aplican no se ofrecen en el formulario: se
|
||||
// ignora lo que pudiera llegar y el usuario se crea sin ellos.
|
||||
let language = if config::user_language_applies() {
|
||||
validate_language(data.language)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let timezone = if user_timezone_applies() {
|
||||
let timezone = if config::user_timezone_applies() {
|
||||
validate_timezone(data.timezone)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let theme = validate_theme(data.theme)?;
|
||||
let theme = if config::user_theme_applies() {
|
||||
validate_theme(data.theme)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
validate_display_name(data.display_name)?;
|
||||
ensure_username_available(&username, None).await?;
|
||||
ensure_email_available(&email, None).await?;
|
||||
|
|
@ -343,18 +347,18 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
|||
let current = find_user(user_id).await?;
|
||||
let username = identity::username(
|
||||
data.username,
|
||||
SETTINGS.identity_policy,
|
||||
config::SETTINGS.identity_policy,
|
||||
Some(¤t.username_key),
|
||||
)?;
|
||||
let email = identity::email(data.email)?;
|
||||
// El idioma y la zona horaria que no se aplican tampoco se ofrecen en el formulario, así que no
|
||||
// llegan: se conserva lo guardado por si se vuelven a aplicar.
|
||||
let language = if user_language_applies() {
|
||||
// El idioma, la zona horaria y el tema que no se aplican tampoco se ofrecen en el formulario,
|
||||
// así que no llegan: se conserva lo guardado por si se vuelven a aplicar.
|
||||
let language = if config::user_language_applies() {
|
||||
Set(validate_language(data.language)?.map(str::to_owned))
|
||||
} else {
|
||||
ActiveValue::NotSet
|
||||
};
|
||||
let timezone = if user_timezone_applies() {
|
||||
let timezone = if config::user_timezone_applies() {
|
||||
let timezone = match validate_timezone(data.timezone) {
|
||||
Err(AuthError::InvalidTimezone) => {
|
||||
keep_current_timezone(data.timezone, current.timezone.as_deref())?
|
||||
|
|
@ -365,7 +369,11 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
|||
} else {
|
||||
ActiveValue::NotSet
|
||||
};
|
||||
let theme = validate_theme(data.theme)?;
|
||||
let theme = if config::user_theme_applies() {
|
||||
Set(validate_theme(data.theme)?.map(str::to_owned))
|
||||
} else {
|
||||
ActiveValue::NotSet
|
||||
};
|
||||
validate_display_name(data.display_name)?;
|
||||
// El navegador envía los saltos de línea de un `<textarea>` como `\r\n`, pero `maxlength` puede
|
||||
// contarlos como un único carácter: se normalizan antes de medir para no rechazar un texto que
|
||||
|
|
@ -382,7 +390,7 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
|||
about: Set(about),
|
||||
language,
|
||||
timezone,
|
||||
theme: Set(theme.map(str::to_owned)),
|
||||
theme,
|
||||
updated_at: Set(now),
|
||||
..Default::default()
|
||||
};
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, QuerySelect};
|
|||
use pagetop_seaorm::db::{Condition, DbErr, Set, dbconn};
|
||||
|
||||
use crate::account::{Account, PermissionSet, UserStatus};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::{role_permission, session, user, user_role};
|
||||
use crate::{ANONYMOUS_ROLE_ID, AUTHENTICATED_ROLE_ID};
|
||||
|
||||
|
|
@ -42,20 +42,20 @@ fn bytes_to_hex(bytes: &[u8]) -> String {
|
|||
/// Con `remember`, la cookie dura `remember_idle_secs`; sin él, es de sesión del navegador. Se marca
|
||||
/// como `Secure` según `secure_cookies` de `[server]`.
|
||||
pub fn build_cookie(sid: &str, remember: bool) -> String {
|
||||
let max_age =
|
||||
remember.then(|| u64::try_from(SETTINGS.session.remember_idle_secs).unwrap_or_default());
|
||||
web::cookie_header(&SETTINGS.session.cookie_name, sid, "/", max_age)
|
||||
let max_age = remember
|
||||
.then(|| u64::try_from(config::SETTINGS.session.remember_idle_secs).unwrap_or_default());
|
||||
web::cookie_header(&config::SETTINGS.session.cookie_name, sid, "/", max_age)
|
||||
}
|
||||
|
||||
/// Construye la cookie de expiración (Max-Age=0) para borrar la sesión del navegador.
|
||||
pub fn expiry_cookie() -> String {
|
||||
web::cookie_header(&SETTINGS.session.cookie_name, "", "/", Some(0))
|
||||
web::cookie_header(&config::SETTINGS.session.cookie_name, "", "/", Some(0))
|
||||
}
|
||||
|
||||
/// Extrae el session ID de las cabeceras HTTP de la petición, si existe y tiene el formato de los
|
||||
/// que genera [`generate_sid`].
|
||||
pub fn extract_sid(headers: Option<&web::http::HeaderMap>) -> Option<&str> {
|
||||
let name = SETTINGS.session.cookie_name.as_str();
|
||||
let name = config::SETTINGS.session.cookie_name.as_str();
|
||||
// Con HTTP/2 el navegador puede repartir las cookies en varias cabeceras `cookie`.
|
||||
headers?
|
||||
.get_all(web::http::header::COOKIE)
|
||||
|
|
@ -156,7 +156,7 @@ pub async fn load_user_from_session(sid: &str) -> (CurrentUser, Option<Account>,
|
|||
sess.last_activity_at,
|
||||
now,
|
||||
idle_period(sess.remember),
|
||||
Duration::seconds(SETTINGS.session.write_interval_secs),
|
||||
Duration::seconds(config::SETTINGS.session.write_interval_secs),
|
||||
) {
|
||||
if sess.remember {
|
||||
renewed_cookie = Some(build_cookie(sid, true));
|
||||
|
|
@ -198,9 +198,9 @@ pub async fn load_user_from_session(sid: &str) -> (CurrentUser, Option<Account>,
|
|||
// Tiempo sin uso tras el que caduca una sesión, según se iniciara o no con "recordarme".
|
||||
fn idle_period(remember: bool) -> Duration {
|
||||
Duration::seconds(if remember {
|
||||
SETTINGS.session.remember_idle_secs
|
||||
config::SETTINGS.session.remember_idle_secs
|
||||
} else {
|
||||
SETTINGS.session.idle_secs
|
||||
config::SETTINGS.session.idle_secs
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -341,7 +341,7 @@ pub(crate) fn invalidate_anonymous_permissions() {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
DateTime, Duration, SETTINGS, Utc, bytes_to_hex, extract_sid, generate_sid, renewed_expiry,
|
||||
DateTime, Duration, Utc, bytes_to_hex, config, extract_sid, generate_sid, renewed_expiry,
|
||||
web,
|
||||
};
|
||||
|
||||
|
|
@ -419,7 +419,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn extracts_sid_among_other_cookies() {
|
||||
let name = &SETTINGS.session.cookie_name;
|
||||
let name = &config::SETTINGS.session.cookie_name;
|
||||
let headers = cookie_headers(&[&format!("a=1; {name}={SID}; b=2")]);
|
||||
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
||||
}
|
||||
|
|
@ -427,14 +427,14 @@ mod tests {
|
|||
#[test]
|
||||
fn extracts_sid_from_split_cookie_headers() {
|
||||
// HTTP/2 clients may send each cookie in its own header field.
|
||||
let name = &SETTINGS.session.cookie_name;
|
||||
let name = &config::SETTINGS.session.cookie_name;
|
||||
let headers = cookie_headers(&["a=1", &format!("{name}={SID}")]);
|
||||
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_cookies_with_a_longer_name_or_invalid_value() {
|
||||
let name = &SETTINGS.session.cookie_name;
|
||||
let name = &config::SETTINGS.session.cookie_name;
|
||||
let headers = cookie_headers(&[&format!("{name}x={SID}; {name}=bogus")]);
|
||||
assert_eq!(extract_sid(Some(&headers)), None);
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
use pagetop::prelude::*;
|
||||
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::hash::Hash;
|
||||
|
|
@ -53,8 +53,8 @@ pub(crate) fn allow(request: &HttpRequest) -> bool {
|
|||
&mut lock(&REQUESTS),
|
||||
network(ip),
|
||||
Instant::now(),
|
||||
SETTINGS.max_ip_requests,
|
||||
window(SETTINGS.ip_request_window_secs),
|
||||
config::SETTINGS.max_ip_requests,
|
||||
window(config::SETTINGS.ip_request_window_secs),
|
||||
);
|
||||
if !allowed {
|
||||
trace::warn!("Request limit reached for address {ip}");
|
||||
|
|
@ -95,20 +95,20 @@ impl LoginKeys {
|
|||
/// se anota en ningún límite.
|
||||
pub(crate) fn allow_login(keys: &LoginKeys) -> bool {
|
||||
let now = Instant::now();
|
||||
let ip_window = window(SETTINGS.ip_failed_login_window_secs);
|
||||
let ip_window = window(config::SETTINGS.ip_failed_login_window_secs);
|
||||
let ip_allowed = match keys.ip {
|
||||
Some(ip) => allow_at(
|
||||
&mut lock(&FAILED_LOGINS),
|
||||
ip,
|
||||
now,
|
||||
SETTINGS.max_ip_failed_logins,
|
||||
config::SETTINGS.max_ip_failed_logins,
|
||||
ip_window,
|
||||
),
|
||||
None if keys.anywhere => allow_at(
|
||||
&mut lock(&FAILED_ANYWHERE),
|
||||
(),
|
||||
now,
|
||||
SETTINGS.max_ip_failed_logins,
|
||||
config::SETTINGS.max_ip_failed_logins,
|
||||
ip_window,
|
||||
),
|
||||
None => true,
|
||||
|
|
@ -120,13 +120,13 @@ pub(crate) fn allow_login(keys: &LoginKeys) -> bool {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
let max = u32::try_from(SETTINGS.max_failed_logins).unwrap_or(0);
|
||||
let max = u32::try_from(config::SETTINGS.max_failed_logins).unwrap_or(0);
|
||||
let identifier_allowed = allow_at(
|
||||
&mut lock(&FAILED_IDENTIFIERS),
|
||||
keys.identifier.clone(),
|
||||
now,
|
||||
max,
|
||||
window(SETTINGS.failed_login_window_secs),
|
||||
window(config::SETTINGS.failed_login_window_secs),
|
||||
);
|
||||
if !identifier_allowed {
|
||||
trace::warn!("Failed login limit reached for an identifier");
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use pagetop_seaorm::db::{
|
|||
ActiveValue, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set, dbconn,
|
||||
};
|
||||
|
||||
use crate::config::SETTINGS;
|
||||
use crate::config;
|
||||
use crate::entity::user_token;
|
||||
use crate::error::AuthError;
|
||||
|
||||
|
|
@ -85,12 +85,12 @@ impl TokenKind {
|
|||
fn limit(self) -> (u32, i64) {
|
||||
match self {
|
||||
TokenKind::PasswordReset => (
|
||||
SETTINGS.max_password_resets,
|
||||
SETTINGS.password_reset_window_secs,
|
||||
config::SETTINGS.max_password_resets,
|
||||
config::SETTINGS.password_reset_window_secs,
|
||||
),
|
||||
TokenKind::EmailChange => (
|
||||
SETTINGS.max_email_changes,
|
||||
SETTINGS.email_change_window_secs,
|
||||
config::SETTINGS.max_email_changes,
|
||||
config::SETTINGS.email_change_window_secs,
|
||||
),
|
||||
TokenKind::EmailVerification => (0, 0),
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue