Skip to content

Commit

Permalink
feat: separate view-tokens from push-tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
ssaavedra committed Aug 27, 2024
1 parent 4d785ea commit 574f66b
Show file tree
Hide file tree
Showing 9 changed files with 227 additions and 53 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions migrations/0006_view_only_tokens.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- Add down migration script here

DROP INDEX IF EXISTS idx_view_tokens_token;
DROP TABLE view_tokens;
19 changes: 19 additions & 0 deletions migrations/0006_view_only_tokens.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-- Add up migration script here

CREATE TABLE view_tokens (
id SERIAL PRIMARY KEY,
token TEXT NOT NULL,
user_id INT NOT NULL,
view_token_valid_until TIMESTAMP NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_accessed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

FOREIGN KEY (user_id) REFERENCES users (id)
);

CREATE INDEX IF NOT EXISTS idx_view_tokens_token ON view_tokens (token);

-- Insert all existing tokens also as view tokens
INSERT INTO view_tokens (token, user_id, view_token_valid_until)
SELECT token, user_id, datetime('now', '+60 years') as view_token_valid_until
FROM tokens;
15 changes: 11 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use rocket::serde::{json::Json, Deserialize};
use rocket::{catchers, fairing, get, launch, post, routes};
use rocket_db_pools::{sqlx, Connection, Database};
use rocket_governor::{rocket_governor_catcher, RocketGovernable, RocketGovernor};
use token::{Token, ValidDbToken};
use token::{Token, ValidDbToken, ValidViewToken};

mod alive_check;
mod car;
Expand Down Expand Up @@ -148,6 +148,13 @@ async fn post_token(
format!("OK")
}

#[get("/log/<_>/check")]
async fn check_token_valid(
token: &ValidDbToken,
) -> String {
format!("Token {} is valid", token.simplified())
}

/// Route GET /log/:token/html will return the data in HTML format
#[get("/log/<_>/html?<page>&<count>&<start>&<end>&<interval>&<tz>", rank = 1)]
async fn list_table_html(
Expand All @@ -157,7 +164,7 @@ async fn list_table_html(
end: HtmlInputParseableDateTime,
interval: Option<i32>,
tz: form::Tz,
token: &ValidDbToken,
token: &ValidViewToken,
mut db: Connection<Logs>,
_ratelimit: RocketGovernor<'_, RateLimitGuard>,
) -> (ContentType, String) {
Expand Down Expand Up @@ -249,7 +256,7 @@ async fn list_table_json(
end: HtmlInputParseableDateTime,
interval: Option<i32>,
tz: form::Tz,
token: &ValidDbToken,
token: &ValidViewToken,
mut db: Connection<Logs>,
_ratelimit: RocketGovernor<'_, RateLimitGuard>,
) -> rocket::response::content::RawJson<String> {
Expand Down Expand Up @@ -291,7 +298,7 @@ async fn list_table_svg(
end: HtmlInputParseableDateTime,
interval: Option<i32>,
tz: form::Tz,
token: &ValidDbToken,
token: &ValidViewToken,
mut db: Connection<Logs>,
_ratelimit: RocketGovernor<'_, RateLimitGuard>,
) -> (ContentType, String) {
Expand Down
20 changes: 12 additions & 8 deletions src/print_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use serde::Serialize;

use crate::{
form::HtmlInputParseableDateTime,
token::{DbToken, Token, ValidDbToken},
token::{DbToken, Token, ValidViewToken},
};

pub struct Pagination {
Expand Down Expand Up @@ -142,7 +142,7 @@ impl RowInfo {
/// rows to be fetched.
pub async fn get_paginated_rows_for_token(
db: &mut Connection<crate::Logs>,
token: &ValidDbToken,
token: &ValidViewToken,
pagination: &PaginationResult,
tz: &chrono_tz::Tz,
) -> (Vec<RowInfo>, bool) {
Expand All @@ -162,13 +162,15 @@ pub async fn get_paginated_rows_for_token(
let end = end.format("%Y-%m-%d %H:%M:%S").to_string();

let db_rows = sqlx::query!(
"SELECT amps, volts, watts, created_at, user_agent, client_ip, energy_log.token as token, u.location as location
"SELECT amps, volts, watts, energy_log.created_at as created_at, user_agent, client_ip, energy_log.token as token, u.location as location
FROM energy_log
INNER JOIN tokens t
ON t.token = energy_log.token
INNER JOIN users u
ON u.id = t.user_id
WHERE energy_log.token = ?
INNER JOIN view_tokens vt
ON vt.user_id = u.id
WHERE vt.token = ?
AND energy_log.created_at BETWEEN ? AND ?
ORDER BY created_at DESC
LIMIT ?
Expand Down Expand Up @@ -218,7 +220,7 @@ pub async fn get_paginated_rows_for_token(
/// interval passed as a parameter.
pub async fn get_avg_max_rows_for_token<Tz: chrono::TimeZone>(
db: &mut Connection<crate::Logs>,
token: &ValidDbToken,
token: &ValidViewToken,
start: &DateTime<Tz>,
end: &DateTime<Tz>,
interval: i32,
Expand All @@ -229,14 +231,16 @@ pub async fn get_avg_max_rows_for_token<Tz: chrono::TimeZone>(
let end = end.naive_utc();

let db_rows = sqlx::query!(
"SELECT AVG(amps) as amps, MAX(amps) as max_amps, AVG(volts) as volts, AVG(watts) as watts, MAX(watts) as max_watts, created_at, user_agent, client_ip, energy_log.token as token, u.location as location
"SELECT AVG(amps) as amps, MAX(amps) as max_amps, AVG(volts) as volts, AVG(watts) as watts, MAX(watts) as max_watts, energy_log.created_at as created_at, user_agent, client_ip, energy_log.token as token, u.location as location
FROM energy_log
INNER JOIN tokens t
ON t.token = energy_log.token
INNER JOIN users u
ON u.id = t.user_id
WHERE energy_log.token = ? AND created_at BETWEEN ? AND ?
GROUP BY strftime('%s', created_at) / ?
INNER JOIN view_tokens vt
ON vt.user_id = u.id
WHERE vt.token = ? AND energy_log.created_at BETWEEN ? AND ?
GROUP BY strftime('%s', energy_log.created_at) / ?
ORDER BY created_at DESC",
token,
start,
Expand Down
Loading

0 comments on commit 574f66b

Please sign in to comment.