Skip to content

Commit af9beb7

Browse files
chore: general cleanup, fix non-admin password updated, add invalidate sessions api
Signed-off-by: Henry <mail@henrygressmann.de>
1 parent c5f3985 commit af9beb7

31 files changed

Lines changed: 867 additions & 853 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/liwan/src/app/core/reports/graph.rs‎

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::app::DuckDBConn;
22
use crate::utils::duckdb::{ParamVec, repeat_vars};
33
use anyhow::{Context, Result};
4-
use chrono::{DateTime, Days, Duration, LocalResult, NaiveDate, TimeZone, Timelike, Utc};
4+
use chrono::{DateTime, Days, Duration, LocalResult, NaiveDate, Offset, TimeZone, Timelike, Utc};
55
use chrono_tz::Tz;
66

77
use super::shared::{build_filter_clause, metric_aggregate_sql};
@@ -26,7 +26,8 @@ fn resolve_local_day_start(timezone: Tz, date: NaiveDate) -> Result<DateTime<Utc
2626
let mut resolved = None;
2727

2828
for _ in 0..180 {
29-
candidate += Duration::minutes(1);
29+
candidate =
30+
candidate.checked_add_signed(Duration::minutes(1)).context("Local date is out of bounds")?;
3031
match timezone.from_local_datetime(&candidate) {
3132
LocalResult::Single(dt) => {
3233
resolved = Some(dt);
@@ -47,6 +48,14 @@ fn resolve_local_day_start(timezone: Tz, date: NaiveDate) -> Result<DateTime<Utc
4748
Ok(resolved.with_timezone(&Utc))
4849
}
4950

51+
fn local_date(timezone: Tz, datetime: DateTime<Utc>) -> Result<NaiveDate> {
52+
datetime
53+
.naive_utc()
54+
.checked_add_offset(datetime.with_timezone(&timezone).offset().fix())
55+
.map(|datetime| datetime.date())
56+
.context("Local date is out of bounds")
57+
}
58+
5059
/// Split a date range into graph buckets aligned to the selected timezone
5160
pub fn build_graph_buckets(
5261
range: &DateRange,
@@ -64,46 +73,31 @@ pub fn build_graph_buckets(
6473
let aligned_start = match interval {
6574
GraphInterval::Hour => {
6675
let start_local = range.start.with_timezone(&timezone);
67-
range.start
68-
- Duration::minutes(i64::from(start_local.minute()))
69-
- Duration::seconds(i64::from(start_local.second()))
70-
- Duration::nanoseconds(i64::from(start_local.nanosecond()))
76+
range
77+
.start
78+
.checked_sub_signed(
79+
Duration::minutes(i64::from(start_local.minute()))
80+
+ Duration::seconds(i64::from(start_local.second()))
81+
+ Duration::nanoseconds(i64::from(start_local.nanosecond())),
82+
)
83+
.context("Graph start is out of bounds")?
7184
}
72-
GraphInterval::Day => resolve_local_day_start(timezone, range.start.with_timezone(&timezone).date_naive())?,
85+
GraphInterval::Day => resolve_local_day_start(timezone, local_date(timezone, range.start)?)?,
7386
};
7487

75-
let mut bucket_count = 0;
88+
let mut buckets = Vec::new();
7689
let mut bucket_start = aligned_start;
7790

7891
while bucket_start < range.end {
79-
let next_bucket_start = match interval {
80-
GraphInterval::Hour => bucket_start + Duration::hours(1),
81-
GraphInterval::Day => {
82-
let next_date = bucket_start
83-
.with_timezone(&timezone)
84-
.date_naive()
85-
.checked_add_days(Days::new(1))
86-
.context("Failed to advance bucket date")?;
87-
resolve_local_day_start(timezone, next_date)?
88-
}
89-
};
90-
91-
bucket_count += 1;
92-
if bucket_count > max_datapoints {
92+
if buckets.len() >= max_datapoints {
9393
anyhow::bail!("Too many data points");
9494
}
95-
bucket_start = next_bucket_start;
96-
}
97-
98-
let mut buckets = Vec::with_capacity(bucket_count);
99-
bucket_start = aligned_start;
100-
while bucket_start < range.end {
10195
let next_bucket_start = match interval {
102-
GraphInterval::Hour => bucket_start + Duration::hours(1),
96+
GraphInterval::Hour => {
97+
bucket_start.checked_add_signed(Duration::hours(1)).context("Graph end is out of bounds")?
98+
}
10399
GraphInterval::Day => {
104-
let next_date = bucket_start
105-
.with_timezone(&timezone)
106-
.date_naive()
100+
let next_date = local_date(timezone, bucket_start)?
107101
.checked_add_days(Days::new(1))
108102
.context("Failed to advance bucket date")?;
109103
resolve_local_day_start(timezone, next_date)?

‎crates/liwan/src/app/core/reports/mod.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pub use dimension::dimension_report;
99
pub use graph::{build_graph_buckets, overall_report};
1010
pub use stats::{earliest_timestamp, online_users, overall_stats};
1111

12-
use anyhow::{Result, bail};
12+
use anyhow::{Context, Result, bail};
1313
use chrono::{DateTime, Duration, Utc};
1414
use schemars::JsonSchema;
1515
use serde::{Deserialize, Serialize};
@@ -51,9 +51,10 @@ pub struct DateRange {
5151

5252
impl DateRange {
5353
/// Return the immediately preceding range with the same duration
54-
pub fn prev(&self) -> Self {
54+
pub fn prev(&self) -> Result<Self> {
5555
let duration = self.end - self.start;
56-
Self { start: self.start - duration, end: self.start }
56+
let start = self.start.checked_sub_signed(duration).context("Previous report range is out of bounds")?;
57+
Ok(Self { start, end: self.start })
5758
}
5859

5960
/// Return whether the range ends after the current time

‎crates/liwan/src/app/core/sessions.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::app::{SqlitePool, models};
22
use anyhow::Result;
33
use chrono::{DateTime, Utc};
4+
use rusqlite::OptionalExtension;
45

56
#[derive(Clone)]
67
pub struct LiwanSessions {
@@ -55,11 +56,13 @@ impl LiwanSessions {
5556
})
5657
});
5758

58-
user.map(Some).or_else(
59-
|err| {
60-
if err == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(err.into()) }
61-
},
62-
)
59+
Ok(user.optional()?)
60+
}
61+
62+
/// Revoke all sessions belonging to a user.
63+
pub fn revoke_user(&self, username: &str) -> Result<()> {
64+
self.pool.get()?.execute("delete from sessions where lower(username) = ?", [username.to_lowercase()])?;
65+
Ok(())
6366
}
6467

6568
/// Expire a session

‎crates/liwan/src/app/core/settings.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use std::sync::{Arc, RwLock};
55
use anyhow::{Result, bail};
66
use rusqlite::OptionalExtension;
77

8+
use crate::app::models::{DisplayOverride, GeoDetail, ProjectDisplaySettings, ResolvedCollectionSettings};
9+
use crate::app::reports::{Dimension, Metric};
810
use crate::app::{SqlitePool, models};
911

1012
#[derive(Clone)]
@@ -57,6 +59,15 @@ impl LiwanSettings {
5759
models::ResolvedCollectionSettings::resolve(cache.global.clone(), cache.entities.get(entity_id).cloned())
5860
}
5961

62+
/// Resolve collection settings for a project's entities from one cache snapshot.
63+
pub fn resolved_for_entities(&self, entity_ids: &[String]) -> Vec<ResolvedCollectionSettings> {
64+
let cache = self.cache.read().expect("collection settings cache poisoned");
65+
entity_ids
66+
.iter()
67+
.map(|id| ResolvedCollectionSettings::resolve(cache.global.clone(), cache.entities.get(id).cloned()))
68+
.collect()
69+
}
70+
6071
/// Update global collection settings and refresh the cache
6172
pub fn update_global(&self, settings: &models::CollectionSettings) -> Result<()> {
6273
if settings.data_retention == models::DataRetention::Inherit {
@@ -205,6 +216,44 @@ impl LiwanProjectSettings {
205216
}
206217
}
207218

219+
impl ProjectDisplaySettings {
220+
/// Return whether a metric is hidden by project or collection settings.
221+
pub fn is_metric_hidden(&self, entities: &[ResolvedCollectionSettings], metric: Metric) -> bool {
222+
match self.metric_display_overrides.get(&metric.to_string()).copied().unwrap_or(DisplayOverride::Auto) {
223+
DisplayOverride::Show => false,
224+
DisplayOverride::Hide => true,
225+
DisplayOverride::Auto => match metric {
226+
Metric::Views | Metric::UniqueVisitors => false,
227+
Metric::BounceRate | Metric::AvgTimeOnSite => entities.iter().any(|settings| !settings.track_sessions),
228+
},
229+
}
230+
}
231+
232+
/// Return the custom-events card visibility preference.
233+
pub fn custom_events_display(&self) -> DisplayOverride {
234+
self.metric_display_overrides.get("custom_events").copied().unwrap_or(DisplayOverride::Auto)
235+
}
236+
237+
/// Return whether a dimension is hidden by project or collection settings.
238+
pub fn is_dimension_hidden(&self, entities: &[ResolvedCollectionSettings], dimension: Dimension) -> bool {
239+
match self.dimension_display_overrides.get(&dimension.to_string()).copied().unwrap_or(DisplayOverride::Auto) {
240+
DisplayOverride::Show => false,
241+
DisplayOverride::Hide => true,
242+
DisplayOverride::Auto => match dimension {
243+
Dimension::UrlEntry | Dimension::UrlExit => entities.iter().any(|settings| !settings.track_sessions),
244+
Dimension::Country => entities.iter().any(|settings| settings.track_geo == GeoDetail::None),
245+
Dimension::City => entities.iter().any(|settings| settings.track_geo != GeoDetail::City),
246+
Dimension::UtmSource
247+
| Dimension::UtmMedium
248+
| Dimension::UtmCampaign
249+
| Dimension::UtmContent
250+
| Dimension::UtmTerm => entities.iter().any(|settings| !settings.track_utm_params),
251+
_ => false,
252+
},
253+
}
254+
}
255+
}
256+
208257
impl SettingsCache {
209258
fn load(pool: &SqlitePool) -> Result<Self> {
210259
let conn = pool.get()?;

‎crates/liwan/src/app/core/users.rs‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::app::{SqlitePool, models};
22
use crate::utils::hash::{hash_password, verify_password};
33
use crate::utils::validate;
44
use anyhow::{Result, bail};
5+
use rusqlite::OptionalExtension;
56

67
#[derive(Clone)]
78
pub struct LiwanUsers {
@@ -94,14 +95,46 @@ impl LiwanUsers {
9495
Ok(())
9596
}
9697

97-
/// Update a user's password
98-
pub fn update_password(&self, username: &str, password: &str) -> Result<()> {
99-
let conn = self.pool.get()?;
98+
/// Update a password and revoke other sessions. CLI resets may omit the current password and session.
99+
pub fn update_password(
100+
&self,
101+
username: &str,
102+
password: &str,
103+
current_password: Option<&str>,
104+
session_id: Option<&str>,
105+
) -> Result<bool> {
106+
let username = username.to_lowercase();
107+
let Some(previous_hash) = self
108+
.pool
109+
.get()?
110+
.query_row("select password_hash from users where username = ?", [&username], |row| {
111+
row.get::<_, Option<String>>(0)
112+
})
113+
.optional()?
114+
else {
115+
return Ok(false);
116+
};
117+
if let Some(current_password) = current_password
118+
&& previous_hash.as_deref().is_none_or(|hash| verify_password(current_password, hash).is_err())
119+
{
120+
return Ok(false);
121+
}
100122
let password_hash = hash_password(password)?;
101-
let mut stmt =
102-
conn.prepare_cached("update users set password_hash = :password_hash where username = :username")?;
103-
stmt.execute(rusqlite::named_params! { ":password_hash": password_hash, ":username": username })?;
104-
Ok(())
123+
let mut conn = self.pool.get()?;
124+
let tx = conn.transaction()?;
125+
if tx.execute(
126+
"update users set password_hash = ? where username = ? and password_hash is ?",
127+
rusqlite::params![password_hash, username, previous_hash],
128+
)? == 0
129+
{
130+
return Ok(false);
131+
}
132+
tx.execute(
133+
"delete from sessions where lower(username) = ? and id != ?",
134+
[&username, session_id.unwrap_or_default()],
135+
)?;
136+
tx.commit()?;
137+
Ok(true)
105138
}
106139

107140
/// Delete a user

0 commit comments

Comments
 (0)