Can log actions in JSON format
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-10-28 11:43:07 +01:00
parent a128e4a597
commit 2a729d4153
12 changed files with 261 additions and 117 deletions

View File

@@ -17,7 +17,7 @@ use crate::data::provider::ProviderID;
use crate::utils::string_utils::rand_str; use crate::utils::string_utils::rand_str;
use crate::utils::time::time; use crate::utils::time::time;
#[derive(Debug, Clone)] #[derive(Debug, Clone, serde::Serialize)]
pub struct ProviderLoginState { pub struct ProviderLoginState {
pub provider_id: ProviderID, pub provider_id: ProviderID,
pub state_id: String, pub state_id: String,

View File

@@ -104,7 +104,7 @@ pub struct AddSuccessful2FALogin(pub UserID, pub IpAddr);
#[rtype(result = "bool")] #[rtype(result = "bool")]
pub struct Clear2FALoginHistory(pub UserID); pub struct Clear2FALoginHistory(pub UserID);
#[derive(Eq, PartialEq, Debug, Clone)] #[derive(Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct AuthorizedAuthenticationSources { pub struct AuthorizedAuthenticationSources {
pub local: bool, pub local: bool,
pub upstream: Vec<ProviderID>, pub upstream: Vec<ProviderID>,

View File

@@ -65,7 +65,9 @@ pub async fn delete_user(
let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap(); let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap();
if res { if res {
action_logger.log(Action::AdminDeleteUser(&user)); action_logger.log(Action::AdminDeleteUser {
user: user.loggable(),
});
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
} else { } else {
HttpResponse::InternalServerError().finish() HttpResponse::InternalServerError().finish()

View File

@@ -165,7 +165,10 @@ pub async fn users_route(
let factors_to_keep = update.0.two_factor.split(';').collect::<Vec<_>>(); let factors_to_keep = update.0.two_factor.split(';').collect::<Vec<_>>();
for factor in &edited_user.two_factor { for factor in &edited_user.two_factor {
if !factors_to_keep.contains(&factor.id.0.as_str()) { if !factors_to_keep.contains(&factor.id.0.as_str()) {
logger.log(Action::AdminRemoveUserFactor(&edited_user, factor)); logger.log(Action::AdminRemoveUserFactor {
user: edited_user.loggable(),
factor: factor.loggable(),
});
users users
.send(users_actor::Remove2FAFactor( .send(users_actor::Remove2FAFactor(
edited_user.uid.clone(), edited_user.uid.clone(),
@@ -186,10 +189,10 @@ pub async fn users_route(
}; };
if edited_user.authorized_authentication_sources() != auth_sources { if edited_user.authorized_authentication_sources() != auth_sources {
logger.log(Action::AdminSetAuthorizedAuthenticationSources( logger.log(Action::AdminSetAuthorizedAuthenticationSources {
&edited_user, user: edited_user.loggable(),
&auth_sources, sources: &auth_sources,
)); });
users users
.send(users_actor::SetAuthorizedAuthenticationSources( .send(users_actor::SetAuthorizedAuthenticationSources(
edited_user.uid.clone(), edited_user.uid.clone(),
@@ -216,10 +219,10 @@ pub async fn users_route(
}; };
if edited_user.granted_clients() != granted_clients { if edited_user.granted_clients() != granted_clients {
logger.log(Action::AdminSetNewGrantedClientsList( logger.log(Action::AdminSetNewGrantedClientsList {
&edited_user, user: edited_user.loggable(),
&granted_clients, clients: &granted_clients,
)); });
users users
.send(users_actor::SetGrantedClients( .send(users_actor::SetGrantedClients(
edited_user.uid.clone(), edited_user.uid.clone(),
@@ -231,7 +234,9 @@ pub async fn users_route(
// Clear user 2FA history if requested // Clear user 2FA history if requested
if update.0.clear_2fa_history.is_some() { if update.0.clear_2fa_history.is_some() {
logger.log(Action::AdminClear2FAHistory(&edited_user)); logger.log(Action::AdminClear2FAHistory {
user: edited_user.loggable(),
});
users users
.send(users_actor::Clear2FALoginHistory(edited_user.uid.clone())) .send(users_actor::Clear2FALoginHistory(edited_user.uid.clone()))
.await .await
@@ -242,7 +247,9 @@ pub async fn users_route(
let new_password = match update.0.gen_new_password.is_some() { let new_password = match update.0.gen_new_password.is_some() {
false => None, false => None,
true => { true => {
logger.log(Action::AdminResetUserPassword(&edited_user)); logger.log(Action::AdminResetUserPassword {
user: edited_user.loggable(),
});
let temp_pass = rand_str(TEMPORARY_PASSWORDS_LEN); let temp_pass = rand_str(TEMPORARY_PASSWORDS_LEN);
users users
@@ -269,11 +276,15 @@ pub async fn users_route(
} else { } else {
success = Some(match is_creating { success = Some(match is_creating {
true => { true => {
logger.log(Action::AdminCreateUser(&edited_user)); logger.log(Action::AdminCreateUser {
user: edited_user.loggable(),
});
format!("User {} was successfully created!", edited_user.full_name()) format!("User {} was successfully created!", edited_user.full_name())
} }
false => { false => {
logger.log(Action::AdminUpdateUser(&edited_user)); logger.log(Action::AdminUpdateUser {
user: edited_user.loggable(),
});
format!("User {} was successfully updated!", edited_user.full_name()) format!("User {} was successfully updated!", edited_user.full_name())
} }
}); });

View File

@@ -111,7 +111,7 @@ pub async fn login_route(
// Check if user session must be closed // Check if user session must be closed
if let Some(true) = query.logout { if let Some(true) = query.logout {
if let Some(id) = id { if let Some(id) = id {
logger.log(Action::Signout); logger.log(Action::SignOut);
id.logout(); id.logout();
} }
success = Some("Goodbye!".to_string()); success = Some("Goodbye!".to_string());
@@ -155,14 +155,20 @@ pub async fn login_route(
match response { match response {
LoginResult::Success(user) => { LoginResult::Success(user) => {
let status = if user.need_reset_password { let status = if user.need_reset_password {
logger.log(Action::UserNeedNewPasswordOnLogin(&user)); logger.log(Action::UserNeedNewPasswordOnLogin {
user: user.loggable(),
});
SessionStatus::NeedNewPassword SessionStatus::NeedNewPassword
} else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) } else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0)
{ {
logger.log(Action::UserNeed2FAOnLogin(&user)); logger.log(Action::UserNeed2FAOnLogin {
user: user.loggable(),
});
SessionStatus::Need2FA SessionStatus::Need2FA
} else { } else {
logger.log(Action::UserSuccessfullyAuthenticated(&user)); logger.log(Action::UserSuccessfullyAuthenticated {
user: user.loggable(),
});
SessionStatus::SignedIn SessionStatus::SignedIn
}; };
@@ -172,7 +178,7 @@ pub async fn login_route(
LoginResult::AccountDisabled => { LoginResult::AccountDisabled => {
log::warn!("Failed login for username {} : account is disabled", &login); log::warn!("Failed login for username {} : account is disabled", &login);
logger.log(Action::TryLoginWithDisabledAccount(&login)); logger.log(Action::TryLoginWithDisabledAccount { login: &login });
danger = Some("Your account is disabled!".to_string()); danger = Some("Your account is disabled!".to_string());
} }
@@ -181,7 +187,7 @@ pub async fn login_route(
"Failed login for username {} : attempted to use local auth, but it is forbidden", "Failed login for username {} : attempted to use local auth, but it is forbidden",
&login &login
); );
logger.log(Action::TryLocalLoginFromUnauthorizedAccount(&login)); logger.log(Action::TryLocalLoginFromUnauthorizedAccount { login: &login });
danger = Some("You cannot login from local auth with your account!".to_string()); danger = Some("You cannot login from local auth with your account!".to_string());
} }
@@ -191,7 +197,7 @@ pub async fn login_route(
c => { c => {
log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}"); log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}");
logger.log(Action::FailedLoginWithBadCredentials(&login)); logger.log(Action::FailedLoginWithBadCredentials { login: &login });
danger = Some("Login failed.".to_string()); danger = Some("Login failed.".to_string());
bruteforce bruteforce
@@ -272,7 +278,7 @@ pub async fn reset_password_route(
danger = Some("Failed to change password!".to_string()); danger = Some("Failed to change password!".to_string());
} else { } else {
SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn); SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::UserChangedPasswordOnLogin(&user_id)); logger.log(Action::UserChangedPasswordOnLogin { user_id: &user_id });
return redirect_user(query.redirect.get()); return redirect_user(query.redirect.get());
} }
} }
@@ -395,7 +401,7 @@ pub async fn login_with_otp(
{ {
logger.log(Action::OTPLoginAttempt { logger.log(Action::OTPLoginAttempt {
success: false, success: false,
user: &user, user: user.loggable(),
}); });
danger = Some("Specified code is invalid!".to_string()); danger = Some("Specified code is invalid!".to_string());
} else { } else {
@@ -412,7 +418,7 @@ pub async fn login_with_otp(
session.set_status(&http_req, SessionStatus::SignedIn); session.set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::OTPLoginAttempt { logger.log(Action::OTPLoginAttempt {
success: true, success: true,
user: &user, user: user.loggable(),
}); });
return redirect_user(query.redirect.get()); return redirect_user(query.redirect.get());
} }

View File

@@ -239,7 +239,7 @@ pub async fn authorize(
.unwrap(); .unwrap();
log::trace!("New OpenID session: {session:#?}"); log::trace!("New OpenID session: {session:#?}");
logger.log(Action::NewOpenIDSession { client: &client }); logger.log(Action::NewOpenIDSession { client: &client.id });
Ok(HttpResponse::Found() Ok(HttpResponse::Found()
.append_header(( .append_header((
@@ -273,7 +273,7 @@ pub async fn authorize(
}; };
log::trace!("New OpenID id token: {:#?}", &id_token); log::trace!("New OpenID id token: {:#?}", &id_token);
logger.log(Action::NewOpenIDSuccessfulImplicitAuth { client: &client }); logger.log(Action::NewOpenIDSuccessfulImplicitAuth { client: &client.id });
Ok(HttpResponse::Found() Ok(HttpResponse::Found()
.append_header(( .append_header((

View File

@@ -357,14 +357,18 @@ pub async fn finish_login(
logger.log(Action::ProviderLoginSuccessful { logger.log(Action::ProviderLoginSuccessful {
provider: &provider, provider: &provider,
user: &user, user: user.loggable(),
}); });
let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) { let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) {
logger.log(Action::UserNeed2FAOnLogin(&user)); logger.log(Action::UserNeed2FAOnLogin {
user: user.loggable(),
});
SessionStatus::Need2FA SessionStatus::Need2FA
} else { } else {
logger.log(Action::UserSuccessfullyAuthenticated(&user)); logger.log(Action::UserSuccessfullyAuthenticated {
user: user.loggable(),
});
SessionStatus::SignedIn SessionStatus::SignedIn
}; };

View File

@@ -57,7 +57,9 @@ pub async fn save_totp_factor(
name: factor_name, name: factor_name,
kind: TwoFactorType::TOTP(key), kind: TwoFactorType::TOTP(key),
}; };
logger.log(Action::AddNewFactor(&factor)); logger.log(Action::AddNewFactor {
factor: factor.loggable(),
});
let res = users let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor)) .send(users_actor::Add2FAFactor(user.uid.clone(), factor))
@@ -104,7 +106,9 @@ pub async fn save_webauthn_factor(
name: factor_name, name: factor_name,
kind: TwoFactorType::WEBAUTHN(Box::new(key)), kind: TwoFactorType::WEBAUTHN(Box::new(key)),
}; };
logger.log(Action::AddNewFactor(&factor)); logger.log(Action::AddNewFactor {
factor: factor.loggable(),
});
let res = users let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor)) .send(users_actor::Add2FAFactor(user.uid.clone(), factor))

View File

@@ -11,21 +11,113 @@ use actix_web::{Error, FromRequest, HttpRequest, web};
use crate::actors::providers_states_actor::ProviderLoginState; use crate::actors::providers_states_actor::ProviderLoginState;
use crate::actors::users_actor; use crate::actors::users_actor;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor}; use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
use crate::data::client::Client; use crate::data::app_config::{ActionLoggerFormat, AppConfig};
use crate::data::client::ClientID;
use crate::data::provider::{Provider, ProviderID}; use crate::data::provider::{Provider, ProviderID};
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID}; use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID};
use crate::utils::time::time;
#[derive(serde::Serialize)]
pub struct LoggableUser {
pub uid: UserID,
pub username: String,
pub email: String,
pub admin: bool,
}
impl LoggableUser {
pub fn quick_identity(&self) -> String {
format!(
"{} {} {} ({:?})",
match self.admin {
true => "admin",
false => "user",
},
self.username,
self.email,
self.uid
)
}
}
impl User {
pub fn loggable(&self) -> LoggableUser {
LoggableUser {
uid: self.uid.clone(),
username: self.username.clone(),
email: self.email.clone(),
admin: self.admin,
}
}
}
#[derive(Debug, serde::Serialize)]
pub enum LoggableFactorType {
TOTP,
WEBAUTHN,
}
#[derive(serde::Serialize)]
pub struct LoggableFactor {
pub id: FactorID,
pub name: String,
pub kind: LoggableFactorType,
}
impl LoggableFactor {
pub fn quick_description(&self) -> String {
format!(
"#{} of type {:?} and name '{}'",
self.id.0, self.kind, self.name
)
}
}
impl TwoFactor {
pub fn loggable(&self) -> LoggableFactor {
LoggableFactor {
id: self.id.clone(),
name: self.name.to_string(),
kind: match self.kind {
TwoFactorType::TOTP(_) => LoggableFactorType::TOTP,
TwoFactorType::WEBAUTHN(_) => LoggableFactorType::WEBAUTHN,
},
}
}
}
#[derive(serde::Serialize)]
#[serde(tag = "type")]
pub enum Action<'a> { pub enum Action<'a> {
AdminCreateUser(&'a User), AdminCreateUser {
AdminUpdateUser(&'a User), user: LoggableUser,
AdminDeleteUser(&'a User), },
AdminResetUserPassword(&'a User), AdminUpdateUser {
AdminRemoveUserFactor(&'a User, &'a TwoFactor), user: LoggableUser,
AdminSetAuthorizedAuthenticationSources(&'a User, &'a AuthorizedAuthenticationSources), },
AdminSetNewGrantedClientsList(&'a User, &'a GrantedClients), AdminDeleteUser {
AdminClear2FAHistory(&'a User), user: LoggableUser,
},
AdminResetUserPassword {
user: LoggableUser,
},
AdminRemoveUserFactor {
user: LoggableUser,
factor: LoggableFactor,
},
AdminSetAuthorizedAuthenticationSources {
user: LoggableUser,
sources: &'a AuthorizedAuthenticationSources,
},
AdminSetNewGrantedClientsList {
user: LoggableUser,
clients: &'a GrantedClients,
},
AdminClear2FAHistory {
user: LoggableUser,
},
LoginWebauthnAttempt { LoginWebauthnAttempt {
success: bool, success: bool,
user_id: UserID, user_id: UserID,
@@ -73,29 +165,45 @@ pub enum Action<'a> {
}, },
ProviderLoginSuccessful { ProviderLoginSuccessful {
provider: &'a Provider, provider: &'a Provider,
user: &'a User, user: LoggableUser,
},
SignOut,
UserNeed2FAOnLogin {
user: LoggableUser,
},
UserSuccessfullyAuthenticated {
user: LoggableUser,
},
UserNeedNewPasswordOnLogin {
user: LoggableUser,
},
TryLoginWithDisabledAccount {
login: &'a str,
},
TryLocalLoginFromUnauthorizedAccount {
login: &'a str,
},
FailedLoginWithBadCredentials {
login: &'a str,
},
UserChangedPasswordOnLogin {
user_id: &'a UserID,
}, },
Signout,
UserNeed2FAOnLogin(&'a User),
UserSuccessfullyAuthenticated(&'a User),
UserNeedNewPasswordOnLogin(&'a User),
TryLoginWithDisabledAccount(&'a str),
TryLocalLoginFromUnauthorizedAccount(&'a str),
FailedLoginWithBadCredentials(&'a str),
UserChangedPasswordOnLogin(&'a UserID),
OTPLoginAttempt { OTPLoginAttempt {
user: &'a User, user: LoggableUser,
success: bool, success: bool,
}, },
NewOpenIDSession { NewOpenIDSession {
client: &'a Client, client: &'a ClientID,
}, },
NewOpenIDSuccessfulImplicitAuth { NewOpenIDSuccessfulImplicitAuth {
client: &'a Client, client: &'a ClientID,
}, },
ChangedHisPassword, ChangedHisPassword,
ClearedHisLoginHistory, ClearedHisLoginHistory,
AddNewFactor(&'a TwoFactor), AddNewFactor {
factor: LoggableFactor,
},
Removed2FAFactor { Removed2FAFactor {
factor_id: &'a FactorID, factor_id: &'a FactorID,
}, },
@@ -104,35 +212,35 @@ pub enum Action<'a> {
impl Action<'_> { impl Action<'_> {
pub fn as_string(&self) -> String { pub fn as_string(&self) -> String {
match self { match self {
Action::AdminDeleteUser(user) => { Action::AdminDeleteUser { user } => {
format!("deleted account of {}", user.quick_identity()) format!("deleted account of {}", user.quick_identity())
} }
Action::AdminCreateUser(user) => { Action::AdminCreateUser { user } => {
format!("created account of {}", user.quick_identity()) format!("created account of {}", user.quick_identity())
} }
Action::AdminUpdateUser(user) => { Action::AdminUpdateUser { user } => {
format!("updated account of {}", user.quick_identity()) format!("updated account of {}", user.quick_identity())
} }
Action::AdminResetUserPassword(user) => { Action::AdminResetUserPassword { user } => {
format!( format!(
"set a temporary password for the account of {}", "set a temporary password for the account of {}",
user.quick_identity() user.quick_identity()
) )
} }
Action::AdminRemoveUserFactor(user, factor) => format!( Action::AdminRemoveUserFactor { user, factor } => format!(
"removed 2 factor ({}) of user ({})", "removed 2 factor ({}) of user ({})",
factor.quick_description(), factor.quick_description(),
user.quick_identity() user.quick_identity()
), ),
Action::AdminClear2FAHistory(user) => { Action::AdminClear2FAHistory { user } => {
format!("cleared 2FA history of {}", user.quick_identity()) format!("cleared 2FA history of {}", user.quick_identity())
} }
Action::AdminSetAuthorizedAuthenticationSources(user, sources) => format!( Action::AdminSetAuthorizedAuthenticationSources { user, sources } => format!(
"update authorized authentication sources ({:?}) for user ({})", "update authorized authentication sources ({:?}) for user ({})",
sources, sources,
user.quick_identity() user.quick_identity()
), ),
Action::AdminSetNewGrantedClientsList(user, clients) => format!( Action::AdminSetNewGrantedClientsList { user, clients } => format!(
"set new granted clients list ({:?}) for user ({})", "set new granted clients list ({:?}) for user ({})",
clients, clients,
user.quick_identity() user.quick_identity()
@@ -191,32 +299,32 @@ impl Action<'_> {
provider.id.0, provider.id.0,
user.quick_identity() user.quick_identity()
), ),
Action::Signout => "signed out".to_string(), Action::SignOut => "signed out".to_string(),
Action::UserNeed2FAOnLogin(user) => { Action::UserNeed2FAOnLogin { user } => {
format!( format!(
"successfully authenticated as user {:?} but need to do 2FA authentication", "successfully authenticated as user {:?} but need to do 2FA authentication",
user.quick_identity() user.quick_identity()
) )
} }
Action::UserSuccessfullyAuthenticated(user) => { Action::UserSuccessfullyAuthenticated { user } => {
format!("successfully authenticated as {}", user.quick_identity()) format!("successfully authenticated as {}", user.quick_identity())
} }
Action::UserNeedNewPasswordOnLogin(user) => format!( Action::UserNeedNewPasswordOnLogin { user } => format!(
"successfully authenticated as {}, but need to set a new password", "successfully authenticated as {}, but need to set a new password",
user.quick_identity() user.quick_identity()
), ),
Action::TryLoginWithDisabledAccount(login) => { Action::TryLoginWithDisabledAccount { login } => {
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT") format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
} }
Action::TryLocalLoginFromUnauthorizedAccount(login) => { Action::TryLocalLoginFromUnauthorizedAccount { login } => {
format!( format!(
"successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!" "successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!"
) )
} }
Action::FailedLoginWithBadCredentials(login) => { Action::FailedLoginWithBadCredentials { login } => {
format!("attempted to authenticate as {login} but with a WRONG PASSWORD") format!("attempted to authenticate as {login} but with a WRONG PASSWORD")
} }
Action::UserChangedPasswordOnLogin(user_id) => { Action::UserChangedPasswordOnLogin { user_id } => {
format!("set a new password at login as user {user_id:?}") format!("set a new password at login as user {user_id:?}")
} }
Action::OTPLoginAttempt { user, success } => match success { Action::OTPLoginAttempt { user, success } => match success {
@@ -230,15 +338,15 @@ impl Action<'_> {
), ),
}, },
Action::NewOpenIDSession { client } => { Action::NewOpenIDSession { client } => {
format!("opened a new OpenID session with {:?}", client.id) format!("opened a new OpenID session with {:?}", client)
} }
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!( Action::NewOpenIDSuccessfulImplicitAuth { client } => format!(
"finished an implicit flow connection for client {:?}", "finished an implicit flow connection for client {:?}",
client.id client
), ),
Action::ChangedHisPassword => "changed his password".to_string(), Action::ChangedHisPassword => "changed his password".to_string(),
Action::ClearedHisLoginHistory => "cleared his login history".to_string(), Action::ClearedHisLoginHistory => "cleared his login history".to_string(),
Action::AddNewFactor(factor) => format!( Action::AddNewFactor { factor } => format!(
"added a new factor to his account : {}", "added a new factor to his account : {}",
factor.quick_description(), factor.quick_description(),
), ),
@@ -247,6 +355,15 @@ impl Action<'_> {
} }
} }
#[derive(serde::Serialize)]
struct JsonActionData<'a> {
time: u64,
ip: IpAddr,
user: Option<LoggableUser>,
#[serde(flatten)]
action: Action<'a>,
}
pub struct ActionLogger { pub struct ActionLogger {
ip: IpAddr, ip: IpAddr,
user: Option<User>, user: Option<User>,
@@ -254,15 +371,27 @@ pub struct ActionLogger {
impl ActionLogger { impl ActionLogger {
pub fn log(&self, action: Action) { pub fn log(&self, action: Action) {
log::info!( match AppConfig::get().action_logger_format {
"{} from {} has {}", ActionLoggerFormat::Text => log::info!(
match &self.user { "{} from {} has {}",
None => "Anonymous user".to_string(), match &self.user {
Some(u) => u.quick_identity(), None => "Anonymous user".to_string(),
Some(u) => u.loggable().quick_identity(),
},
self.ip,
action.as_string()
),
ActionLoggerFormat::Json => match serde_json::to_string(&JsonActionData {
time: time(),
ip: self.ip,
user: self.user.as_ref().map(User::loggable),
action,
}) {
Ok(j) => println!("{j}"),
Err(e) => log::error!("Failed to serialize event to JSON! {e}"),
}, },
self.ip, ActionLoggerFormat::None => {}
action.as_string() }
)
} }
} }

View File

@@ -6,6 +6,15 @@ use crate::constants::{
APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE, APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE,
}; };
/// Action logger format
#[derive(Copy, Clone, Eq, PartialEq, Debug, clap::ValueEnum, Default)]
pub enum ActionLoggerFormat {
#[default]
Text,
Json,
None,
}
/// Basic OIDC provider /// Basic OIDC provider
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
@@ -45,6 +54,10 @@ pub struct AppConfig {
/// Example: "https://api.geoip.rs" /// Example: "https://api.geoip.rs"
#[arg(long, short, env)] #[arg(long, short, env)]
pub ip_location_service: Option<String>, pub ip_location_service: Option<String>,
/// Action logger output format
#[arg(long, env, default_value_t, value_enum)]
pub action_logger_format: ActionLoggerFormat,
} }
lazy_static::lazy_static! { lazy_static::lazy_static! {

View File

@@ -26,7 +26,7 @@ pub struct GeneralSettings {
pub is_admin: bool, pub is_admin: bool,
} }
#[derive(Eq, PartialEq, Clone, Debug)] #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize)]
pub enum GrantedClients { pub enum GrantedClients {
AllClients, AllClients,
SomeClients(Vec<ClientID>), SomeClients(Vec<ClientID>),
@@ -60,15 +60,6 @@ pub struct TwoFactor {
} }
impl TwoFactor { impl TwoFactor {
pub fn quick_description(&self) -> String {
format!(
"#{} of type {} and name '{}'",
self.id.0,
self.type_str(),
self.name
)
}
pub fn type_str(&self) -> &'static str { pub fn type_str(&self) -> &'static str {
match self.kind { match self.kind {
TwoFactorType::TOTP(_) => "Authenticator app", TwoFactorType::TOTP(_) => "Authenticator app",
@@ -170,19 +161,6 @@ impl User {
format!("{} {}", self.first_name, self.last_name) format!("{} {}", self.first_name, self.last_name)
} }
pub fn quick_identity(&self) -> String {
format!(
"{} {} {} ({:?})",
match self.admin {
true => "admin",
false => "user",
},
self.username,
self.email,
self.uid
)
}
/// Get the list of sources from which a user can authenticate from /// Get the list of sources from which a user can authenticate from
pub fn authorized_authentication_sources(&self) -> AuthorizedAuthenticationSources { pub fn authorized_authentication_sources(&self) -> AuthorizedAuthenticationSources {
AuthorizedAuthenticationSources { AuthorizedAuthenticationSources {

View File

@@ -31,28 +31,25 @@ fn hash_password<P: AsRef<[u8]>>(pwd: P) -> Res<String> {
} }
fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool { fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
match bcrypt::verify(pwd, hash) { bcrypt::verify(pwd, hash).unwrap_or_else(|e| {
Ok(r) => r, log::warn!("Failed to verify password! {e:?}");
Err(e) => { false
log::warn!("Failed to verify password! {e:?}"); })
false
}
}
} }
impl UsersSyncBackend for EntityManager<User> { impl UsersSyncBackend for EntityManager<User> {
fn find_by_email(&self, u: &str) -> Res<Option<User>> { fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() { for entry in self.iter() {
if entry.email.eq(u) { if entry.username.eq(u) || entry.email.eq(u) {
return Ok(Some(entry.clone())); return Ok(Some(entry.clone()));
} }
} }
Ok(None) Ok(None)
} }
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> { fn find_by_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() { for entry in self.iter() {
if entry.username.eq(u) || entry.email.eq(u) { if entry.email.eq(u) {
return Ok(Some(entry.clone())); return Ok(Some(entry.clone()));
} }
} }