2024-12-14 06:17:58 -06:00
|
|
|
#![feature(iter_collect_into, macro_metavar_expr)]
|
2024-10-05 16:07:33 -05:00
|
|
|
use {
|
2024-10-14 06:25:38 -05:00
|
|
|
argon2::{password_hash::SaltString, PasswordVerifier},
|
2024-10-08 17:17:13 -05:00
|
|
|
axum::{
|
2024-10-10 08:48:08 -05:00
|
|
|
body::Bytes,
|
2024-11-18 04:28:47 -06:00
|
|
|
extract::{DefaultBodyLimit, Path},
|
2024-11-23 03:18:05 -06:00
|
|
|
http::{header::COOKIE, request::Parts, StatusCode},
|
2024-10-08 17:17:13 -05:00
|
|
|
response::{AppendHeaders, Html},
|
2024-10-05 16:07:33 -05:00
|
|
|
},
|
2024-10-14 15:04:18 -05:00
|
|
|
const_format::formatcp,
|
2024-10-08 17:17:13 -05:00
|
|
|
core::fmt,
|
|
|
|
htmlm::{html, write_html},
|
2024-10-14 06:25:38 -05:00
|
|
|
rand_core::OsRng,
|
2024-10-08 17:17:13 -05:00
|
|
|
serde::{Deserialize, Serialize},
|
2024-10-14 06:25:38 -05:00
|
|
|
std::{
|
|
|
|
collections::{HashMap, HashSet},
|
2024-10-14 15:04:18 -05:00
|
|
|
fmt::{Display, Write},
|
2024-10-14 06:25:38 -05:00
|
|
|
net::Ipv4Addr,
|
|
|
|
},
|
2024-10-05 16:07:33 -05:00
|
|
|
};
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
const MAX_NAME_LENGTH: usize = 32;
|
|
|
|
const MAX_POSTNAME_LENGTH: usize = 64;
|
2024-10-13 13:01:18 -05:00
|
|
|
const MAX_CODE_LENGTH: usize = 1024 * 4;
|
2024-10-08 17:17:13 -05:00
|
|
|
const SESSION_DURATION_SECS: u64 = 60 * 60;
|
2024-10-14 15:04:18 -05:00
|
|
|
const MAX_FEED_SIZE: usize = 8 * 1024;
|
2024-10-08 17:17:13 -05:00
|
|
|
|
|
|
|
type Redirect<const COUNT: usize = 1> = AppendHeaders<[(&'static str, &'static str); COUNT]>;
|
|
|
|
|
2024-10-10 08:48:08 -05:00
|
|
|
macro_rules! static_asset {
|
|
|
|
($mime:literal, $body:literal) => {
|
|
|
|
get(|| async {
|
|
|
|
axum::http::Response::builder()
|
|
|
|
.header("content-type", $mime)
|
2024-10-12 08:04:58 -05:00
|
|
|
.header("content-encoding", "gzip")
|
|
|
|
.body(axum::body::Body::from(Bytes::from_static(include_bytes!(concat!(
|
|
|
|
$body, ".gz"
|
|
|
|
)))))
|
2024-10-10 08:48:08 -05:00
|
|
|
.unwrap()
|
|
|
|
})
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
async fn amain() {
|
|
|
|
use axum::routing::{delete, get, post};
|
|
|
|
|
|
|
|
let debug = cfg!(debug_assertions);
|
|
|
|
|
|
|
|
log::set_logger(&Logger).unwrap();
|
|
|
|
log::set_max_level(if debug { log::LevelFilter::Warn } else { log::LevelFilter::Error });
|
|
|
|
|
|
|
|
db::init();
|
|
|
|
|
|
|
|
let router = axum::Router::new()
|
2024-10-12 06:07:49 -05:00
|
|
|
.route("/index.css", static_asset!("text/css", "index.css"))
|
|
|
|
.route("/index.js", static_asset!("text/javascript", "index.js"))
|
2024-10-12 08:04:58 -05:00
|
|
|
.route("/hbfmt.wasm", static_asset!("application/wasm", "hbfmt.wasm"))
|
|
|
|
.route("/hbc.wasm", static_asset!("application/wasm", "hbc.wasm"))
|
2024-12-14 06:17:58 -06:00
|
|
|
.route("/", get(Index::page))
|
|
|
|
.route("/index-view", get(Index::get_with_blog))
|
|
|
|
.route("/blogs/index-view", get(Index::get))
|
|
|
|
.route("/blogs/developing-hblang", get(DevelopingHblang::page))
|
|
|
|
.route("/blogs/developing-hblang-view", get(DevelopingHblang::get))
|
2024-10-14 15:04:18 -05:00
|
|
|
.route("/feed", get(Feed::page))
|
|
|
|
.route("/feed-view", get(Feed::get))
|
|
|
|
.route("/feed-more", post(Feed::more))
|
2024-10-08 17:17:13 -05:00
|
|
|
.route("/profile", get(Profile::page))
|
|
|
|
.route("/profile-view", get(Profile::get))
|
2024-10-14 15:04:18 -05:00
|
|
|
.route("/profile/:name", get(Profile::get_other_page))
|
2024-11-18 03:31:30 -06:00
|
|
|
.route("/profile/password", post(PasswordChange::post))
|
2024-10-14 15:04:18 -05:00
|
|
|
.route("/profile-view/:name", get(Profile::get_other))
|
2024-10-08 17:17:13 -05:00
|
|
|
.route("/post", get(Post::page))
|
|
|
|
.route("/post-view", get(Post::get))
|
|
|
|
.route("/post", post(Post::post))
|
2024-11-23 03:18:05 -06:00
|
|
|
.route("/post/run", post(Post::run))
|
2024-10-14 06:25:38 -05:00
|
|
|
.route("/code", post(fetch_code))
|
2024-10-08 17:17:13 -05:00
|
|
|
.route("/login", get(Login::page))
|
|
|
|
.route("/login-view", get(Login::get))
|
|
|
|
.route("/login", post(Login::post))
|
|
|
|
.route("/login", delete(Login::delete))
|
|
|
|
.route("/signup", get(Signup::page))
|
|
|
|
.route("/signup-view", get(Signup::get))
|
|
|
|
.route("/signup", post(Signup::post))
|
|
|
|
.route(
|
|
|
|
"/hot-reload",
|
|
|
|
get({
|
|
|
|
let id = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_millis();
|
|
|
|
move || async move { id.to_string() }
|
|
|
|
}),
|
2024-11-18 04:28:47 -06:00
|
|
|
)
|
|
|
|
.layer(DefaultBodyLimit::max(16 * 1024));
|
2024-10-08 17:17:13 -05:00
|
|
|
|
2024-10-14 15:04:18 -05:00
|
|
|
#[cfg(feature = "tls")]
|
|
|
|
{
|
|
|
|
let addr =
|
|
|
|
(Ipv4Addr::UNSPECIFIED, std::env::var("DEPELL_PORT").unwrap().parse::<u16>().unwrap());
|
|
|
|
let config = axum_server::tls_rustls::RustlsConfig::from_pem_file(
|
|
|
|
std::env::var("DEPELL_CERT_PATH").unwrap(),
|
|
|
|
std::env::var("DEPELL_KEY_PATH").unwrap(),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
axum_server::bind_rustls(addr.into(), config)
|
|
|
|
.serve(router.into_make_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
2024-10-10 08:48:08 -05:00
|
|
|
}
|
2024-10-14 15:04:18 -05:00
|
|
|
#[cfg(not(feature = "tls"))]
|
|
|
|
{
|
|
|
|
let addr = (Ipv4Addr::UNSPECIFIED, 8080);
|
|
|
|
let socket = tokio::net::TcpListener::bind(addr).await.unwrap();
|
|
|
|
axum::serve(socket, router).await.unwrap();
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-14 06:25:38 -05:00
|
|
|
async fn fetch_code(
|
|
|
|
axum::Json(paths): axum::Json<Vec<String>>,
|
|
|
|
) -> axum::Json<HashMap<String, String>> {
|
|
|
|
let mut deps = HashMap::<String, String>::new();
|
|
|
|
db::with(|db| {
|
|
|
|
for path in &paths {
|
|
|
|
let Some((author, name)) = path.split_once('/') else { continue };
|
|
|
|
db.fetch_deps
|
|
|
|
.query_map((name, author), |r| {
|
|
|
|
Ok((
|
|
|
|
r.get::<_, String>(1)? + "/" + r.get_ref(0)?.as_str()?,
|
|
|
|
r.get::<_, String>(2)?,
|
|
|
|
))
|
|
|
|
})
|
2024-10-14 15:04:18 -05:00
|
|
|
.log("fetch deps query")
|
2024-10-14 06:25:38 -05:00
|
|
|
.into_iter()
|
|
|
|
.flatten()
|
2024-10-14 15:04:18 -05:00
|
|
|
.filter_map(|r| r.log("deps row"))
|
2024-10-14 06:25:38 -05:00
|
|
|
.collect_into(&mut deps);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
axum::Json(deps)
|
|
|
|
}
|
|
|
|
|
2024-10-14 15:04:18 -05:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
enum Feed {
|
|
|
|
Before { before_timestamp: u64 },
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Before {
|
|
|
|
before_timestamp: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Feed {
|
|
|
|
async fn more(session: Session, axum::Form(data): axum::Form<Before>) -> Html<String> {
|
|
|
|
Self::Before { before_timestamp: data.before_timestamp }.render(&session)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Feed {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::Before { before_timestamp: now() + 3600 }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Page for Feed {
|
|
|
|
fn render_to_buf(self, _: &Session, buf: &mut String) {
|
|
|
|
db::with(|db| {
|
|
|
|
let cursor = match self {
|
|
|
|
Feed::Before { before_timestamp } => db
|
|
|
|
.get_pots_before
|
|
|
|
.query_map((before_timestamp,), Post::from_row)
|
|
|
|
.log("fetch before posts query")
|
|
|
|
.into_iter()
|
|
|
|
.flatten()
|
|
|
|
.filter_map(|r| r.log("fetch before posts row")),
|
|
|
|
};
|
|
|
|
|
|
|
|
let base_len = buf.len();
|
|
|
|
let mut last_timestamp = None;
|
|
|
|
for post in cursor {
|
|
|
|
write!(buf, "{}", post).unwrap();
|
|
|
|
if buf.len() - base_len > MAX_FEED_SIZE {
|
2024-10-17 08:48:22 -05:00
|
|
|
last_timestamp = Some(post.timestamp);
|
2024-10-14 15:04:18 -05:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
write_html!((*buf)
|
|
|
|
if let Some(last_timestamp) = last_timestamp {
|
|
|
|
<div "hx-post"="/feed-more"
|
|
|
|
"hx-trigger"="intersect once"
|
|
|
|
"hx-swap"="outerHTML"
|
|
|
|
"hx-vals"={format_args!("{{\"before_timestamp\":{last_timestamp}}}")}
|
|
|
|
>"there might be more"</div>
|
|
|
|
} else {
|
|
|
|
"no more stuff"
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-14 06:17:58 -06:00
|
|
|
macro_rules! decl_static_pages {
|
|
|
|
($(
|
|
|
|
#[derive(PublicPage)]
|
|
|
|
#[page(static = $file:literal)]
|
|
|
|
struct $name:ident;
|
|
|
|
)*) => {
|
|
|
|
const ALL_STATIC_PAGES: [&str; ${count($file)}] = [$($file),*];
|
|
|
|
|
|
|
|
$(
|
|
|
|
#[derive(Default)]
|
|
|
|
struct $name;
|
|
|
|
|
|
|
|
impl PublicPage for $name {
|
|
|
|
fn render_to_buf(self, buf: &mut String) {
|
|
|
|
buf.push_str(include_str!(concat!("static-pages/", $file, ".html")));
|
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-12-14 06:17:58 -06:00
|
|
|
async fn page(session: Option<Session>) -> Html<String> {
|
|
|
|
base(|s| blog_base(s, |s| Self::default().render_to_buf(s)), session.as_ref())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)*
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
decl_static_pages! {
|
|
|
|
#[derive(PublicPage)]
|
|
|
|
#[page(static = "welcome")]
|
|
|
|
struct Index;
|
|
|
|
#[derive(PublicPage)]
|
|
|
|
#[page(static = "developing-hblang")]
|
|
|
|
struct DevelopingHblang;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Index {
|
|
|
|
async fn get_with_blog() -> Html<String> {
|
|
|
|
let mut buf = String::new();
|
|
|
|
blog_base(&mut buf, |s| Index.render_to_buf(s));
|
|
|
|
Html(buf)
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
#[derive(Deserialize, Default)]
|
|
|
|
struct Post {
|
|
|
|
author: String,
|
|
|
|
name: String,
|
|
|
|
#[serde(skip)]
|
|
|
|
timestamp: u64,
|
|
|
|
#[serde(skip)]
|
|
|
|
imports: usize,
|
|
|
|
#[serde(skip)]
|
|
|
|
runs: usize,
|
|
|
|
#[serde(skip)]
|
|
|
|
dependencies: usize,
|
|
|
|
code: String,
|
|
|
|
#[serde(skip)]
|
|
|
|
error: Option<&'static str>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Page for Post {
|
2024-10-10 08:48:08 -05:00
|
|
|
fn render_to_buf(self, session: &Session, buf: &mut String) {
|
2024-10-08 17:17:13 -05:00
|
|
|
let Self { name, code, error, .. } = self;
|
2024-10-10 08:48:08 -05:00
|
|
|
write_html! { (buf)
|
2024-10-14 06:25:38 -05:00
|
|
|
<form id="postForm" "hx-post"="/post" "hx-swap"="outerHTML">
|
2024-10-08 17:17:13 -05:00
|
|
|
if let Some(e) = error { <div class="error">e</div> }
|
|
|
|
<input name="author" type="text" value={session.name} hidden>
|
|
|
|
<input name="name" type="text" placeholder="name" value=name
|
|
|
|
required maxlength=MAX_POSTNAME_LENGTH>
|
2024-10-13 13:01:18 -05:00
|
|
|
<div id="code-editor">
|
2024-10-14 06:25:38 -05:00
|
|
|
<textarea id="code-edit" name="code" placeholder="code" rows=1
|
|
|
|
required>code</textarea>
|
2024-10-13 13:01:18 -05:00
|
|
|
<span id="code-size">MAX_CODE_LENGTH</span>
|
|
|
|
</div>
|
2024-10-08 17:17:13 -05:00
|
|
|
<input type="submit" value="submit">
|
2024-10-12 14:25:37 -05:00
|
|
|
<pre id="compiler-output"></pre>
|
2024-10-08 17:17:13 -05:00
|
|
|
</form>
|
2024-12-14 06:17:58 -06:00
|
|
|
|
|
|
|
<div id="dep-list">
|
|
|
|
<input placeholder="search impoted deps.." oninput="filterCodeDeps(this, event)">
|
|
|
|
<section id="deps">
|
|
|
|
"results show here..."
|
|
|
|
</section>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<div>
|
|
|
|
!{include_str!("static-pages/post.html")}
|
|
|
|
</div>
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-23 03:18:05 -06:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Run {
|
|
|
|
author: String,
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl Post {
|
2024-10-14 15:04:18 -05:00
|
|
|
pub fn from_row(r: &rusqlite::Row) -> rusqlite::Result<Self> {
|
|
|
|
Ok(Post {
|
|
|
|
author: r.get(0)?,
|
|
|
|
name: r.get(1)?,
|
|
|
|
timestamp: r.get(2)?,
|
|
|
|
code: r.get(3)?,
|
2024-11-22 17:06:25 -06:00
|
|
|
imports: r.get(4)?,
|
2024-11-23 03:18:05 -06:00
|
|
|
runs: r.get(5)?,
|
2024-10-14 15:04:18 -05:00
|
|
|
..Default::default()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-11-23 03:18:05 -06:00
|
|
|
async fn run(
|
|
|
|
session: Session,
|
|
|
|
axum::extract::Query(run): axum::extract::Query<Run>,
|
|
|
|
) -> StatusCode {
|
|
|
|
match db::with(|qes| qes.creata_run.insert((run.name, run.author, session.name))) {
|
|
|
|
Ok(_) => StatusCode::OK,
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("creating run record failed: {e}");
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
async fn post(
|
|
|
|
session: Session,
|
|
|
|
axum::Form(mut data): axum::Form<Self>,
|
|
|
|
) -> Result<Redirect, Html<String>> {
|
2024-10-14 15:04:18 -05:00
|
|
|
if data.name.len() > MAX_POSTNAME_LENGTH {
|
|
|
|
data.error = Some(formatcp!("name too long, max length is {MAX_POSTNAME_LENGTH}"));
|
|
|
|
return Err(data.render(&session));
|
|
|
|
}
|
|
|
|
|
|
|
|
if data.code.len() > MAX_CODE_LENGTH {
|
|
|
|
data.error = Some(formatcp!("code too long, max length is {MAX_CODE_LENGTH}"));
|
|
|
|
return Err(data.render(&session));
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
db::with(|db| {
|
|
|
|
if let Err(e) = db.create_post.insert((&data.name, &session.name, now(), &data.code)) {
|
|
|
|
if let rusqlite::Error::SqliteFailure(e, _) = e {
|
|
|
|
if e.code == rusqlite::ErrorCode::ConstraintViolation {
|
|
|
|
data.error = Some("this name is already used");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
data.error = data.error.or_else(|| {
|
2024-10-14 15:04:18 -05:00
|
|
|
log::error!("create post error: {e}");
|
2024-10-08 17:17:13 -05:00
|
|
|
Some("internal server error")
|
|
|
|
});
|
2024-10-14 06:25:38 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (author, name) in hblang::lexer::Lexer::uses(&data.code)
|
|
|
|
.filter_map(|v| v.split_once('/'))
|
|
|
|
.collect::<HashSet<_>>()
|
|
|
|
{
|
2024-10-14 15:04:18 -05:00
|
|
|
if db
|
|
|
|
.create_import
|
|
|
|
.insert((author, name, &session.name, &data.name))
|
|
|
|
.log("create import query")
|
|
|
|
.is_none()
|
|
|
|
{
|
2024-10-14 06:25:38 -05:00
|
|
|
data.error = Some("internal server error");
|
|
|
|
return;
|
|
|
|
};
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
|
|
|
});
|
2024-10-05 16:07:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
if data.error.is_some() {
|
2024-10-14 15:04:18 -05:00
|
|
|
Err(data.render(&session))
|
2024-10-08 17:17:13 -05:00
|
|
|
} else {
|
|
|
|
Ok(redirect("/profile"))
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl fmt::Display for Post {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
let Self { author, name, timestamp, imports, runs, dependencies, code, .. } = self;
|
2024-11-23 03:18:05 -06:00
|
|
|
write_html! { f <div class="preview" "data-author"=author "data-name"=name>
|
2024-10-10 01:35:17 -05:00
|
|
|
<div class="info">
|
2024-10-14 15:04:18 -05:00
|
|
|
<span>
|
|
|
|
<a "hx-get"={format_args!("/profile-view/{author}")} href="" "hx-target"="main"
|
|
|
|
"hx-push-url"={format_args!("/profile/{author}")}
|
|
|
|
"hx-swam"="innerHTML">author</a>
|
|
|
|
"/"
|
|
|
|
name
|
|
|
|
</span>
|
2024-10-10 01:35:17 -05:00
|
|
|
<span apply="timestamp">timestamp</span>
|
2024-11-23 03:18:05 -06:00
|
|
|
for (name, count) in [include_str!("icons/download.svg"), include_str!("icons/run.svg"), "deps"]
|
2024-11-22 17:06:25 -06:00
|
|
|
.iter()
|
2024-10-10 01:35:17 -05:00
|
|
|
.zip([imports, runs, dependencies])
|
|
|
|
.filter(|(_, &c)| c != 0)
|
|
|
|
{
|
2024-11-22 17:06:25 -06:00
|
|
|
<div class="stat">!name count</div>
|
2024-10-10 01:35:17 -05:00
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
</div>
|
2024-11-23 03:18:05 -06:00
|
|
|
<div class="code">
|
|
|
|
<nav>
|
|
|
|
<button onmousedown="runPost(this)">!{include_str!("icons/run.svg")}</button>
|
|
|
|
</nav>
|
|
|
|
<pre apply="fmt">code</pre>
|
|
|
|
</div>
|
|
|
|
<pre hidden id="compiler-output"></pre>
|
2024-10-08 17:17:13 -05:00
|
|
|
if *timestamp == 0 {
|
2024-10-14 06:25:38 -05:00
|
|
|
<button "hx-get"="/post" "hx-swap"="outerHTML"
|
2024-10-08 17:17:13 -05:00
|
|
|
"hx-target"="[preview]">"edit"</button>
|
|
|
|
}
|
|
|
|
</div> }
|
|
|
|
Ok(())
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-18 03:31:30 -06:00
|
|
|
#[derive(Deserialize, Default)]
|
|
|
|
struct PasswordChange {
|
|
|
|
old_password: String,
|
|
|
|
new_password: String,
|
|
|
|
#[serde(skip)]
|
|
|
|
error: Option<&'static str>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PasswordChange {
|
|
|
|
async fn post(
|
|
|
|
session: Session,
|
|
|
|
axum::Form(mut change): axum::Form<PasswordChange>,
|
|
|
|
) -> Html<String> {
|
|
|
|
db::with(|que| {
|
|
|
|
match que.authenticate.query_row((&session.name,), |r| r.get::<_, String>(1)) {
|
|
|
|
Ok(hash) if verify_password(&hash, &change.old_password).is_err() => {
|
|
|
|
change.error = Some("invalid credentials");
|
|
|
|
}
|
|
|
|
Ok(_) => {
|
|
|
|
let new_hashed = hash_password(&change.new_password);
|
|
|
|
match que
|
|
|
|
.change_passowrd
|
|
|
|
.execute((new_hashed, &session.name))
|
|
|
|
.log("execute update")
|
|
|
|
{
|
|
|
|
None => change.error = Some("intenal server error"),
|
|
|
|
Some(0) => change.error = Some("password is incorrect"),
|
|
|
|
Some(_) => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
|
|
|
change.error = Some("invalid credentials");
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("login queri failed: {e}");
|
|
|
|
change.error = Some("internal server error");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if change.error.is_some() {
|
|
|
|
change.render(&session)
|
|
|
|
} else {
|
|
|
|
PasswordChange::default().render(&session)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Page for PasswordChange {
|
|
|
|
fn render_to_buf(self, _: &Session, buf: &mut String) {
|
|
|
|
let Self { old_password, new_password, error } = self;
|
|
|
|
write_html! { (buf)
|
|
|
|
<form "hx-post"="/profile/password" "hx-swap"="outerHTML">
|
|
|
|
if let Some(e) = error { <div class="error">e</div> }
|
|
|
|
<input name="old_password" type="password" autocomplete="old-password"
|
|
|
|
placeholder="old password" value=old_password>
|
|
|
|
<input name="new_password" type="password" autocomplete="new-password" placeholder="new password"
|
|
|
|
value=new_password>
|
|
|
|
<input type="submit" value="submit">
|
|
|
|
</form>
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
#[derive(Default)]
|
2024-10-14 15:04:18 -05:00
|
|
|
struct Profile {
|
|
|
|
other: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Profile {
|
|
|
|
async fn get_other(session: Session, Path(name): Path<String>) -> Html<String> {
|
|
|
|
Profile { other: Some(name) }.render(&session)
|
|
|
|
}
|
|
|
|
|
2024-10-17 09:08:29 -05:00
|
|
|
async fn get_other_page(session: Session, Path(name): Path<String>) -> Html<String> {
|
|
|
|
base(|b| Profile { other: Some(name) }.render_to_buf(&session, b), Some(&session))
|
2024-10-14 15:04:18 -05:00
|
|
|
}
|
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
|
|
|
|
impl Page for Profile {
|
2024-10-10 08:48:08 -05:00
|
|
|
fn render_to_buf(self, session: &Session, buf: &mut String) {
|
2024-10-08 17:17:13 -05:00
|
|
|
db::with(|db| {
|
2024-11-18 03:31:30 -06:00
|
|
|
let name = self.other.as_ref().unwrap_or(&session.name);
|
2024-10-08 17:17:13 -05:00
|
|
|
let iter = db
|
|
|
|
.get_user_posts
|
2024-11-18 03:31:30 -06:00
|
|
|
.query_map((name,), Post::from_row)
|
2024-10-14 15:04:18 -05:00
|
|
|
.log("get user posts query")
|
2024-10-08 17:17:13 -05:00
|
|
|
.into_iter()
|
|
|
|
.flatten()
|
2024-10-14 15:04:18 -05:00
|
|
|
.filter_map(|p| p.log("user post row"));
|
2024-11-18 03:31:30 -06:00
|
|
|
write_html! { (*buf)
|
|
|
|
if name == &session.name {
|
|
|
|
|b|{PasswordChange::default().render_to_buf(session, b)}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
for post in iter {
|
|
|
|
!{post}
|
|
|
|
} else {
|
|
|
|
"no posts"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
2024-10-05 16:07:33 -05:00
|
|
|
|
2024-10-14 06:25:38 -05:00
|
|
|
fn hash_password(password: &str) -> String {
|
|
|
|
use argon2::PasswordHasher;
|
|
|
|
argon2::Argon2::default()
|
|
|
|
.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
|
|
|
|
.unwrap()
|
|
|
|
.to_string()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn verify_password(hash: &str, password: &str) -> Result<(), argon2::password_hash::Error> {
|
|
|
|
argon2::Argon2::default()
|
|
|
|
.verify_password(password.as_bytes(), &argon2::PasswordHash::new(hash)?)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Default, Debug)]
|
2024-10-08 17:17:13 -05:00
|
|
|
struct Login {
|
|
|
|
name: String,
|
|
|
|
password: String,
|
|
|
|
#[serde(skip)]
|
|
|
|
error: Option<&'static str>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PublicPage for Login {
|
2024-10-10 08:48:08 -05:00
|
|
|
fn render_to_buf(self, buf: &mut String) {
|
2024-11-18 03:31:30 -06:00
|
|
|
let Self { name, password, error } = self;
|
2024-10-10 08:48:08 -05:00
|
|
|
write_html! { (buf)
|
2024-10-14 06:25:38 -05:00
|
|
|
<form "hx-post"="/login" "hx-swap"="outerHTML">
|
2024-10-08 17:17:13 -05:00
|
|
|
if let Some(e) = error { <div class="error">e</div> }
|
|
|
|
<input name="name" type="text" autocomplete="name" placeholder="name" value=name
|
|
|
|
required maxlength=MAX_NAME_LENGTH>
|
2024-10-13 05:25:12 -05:00
|
|
|
<input name="password" type="password" autocomplete="current-password" placeholder="password"
|
2024-10-08 17:17:13 -05:00
|
|
|
value=password>
|
|
|
|
<input type="submit" value="submit">
|
|
|
|
</form>
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl Login {
|
|
|
|
async fn post(
|
|
|
|
axum::Form(mut data): axum::Form<Self>,
|
|
|
|
) -> Result<AppendHeaders<[(&'static str, String); 2]>, Html<String>> {
|
|
|
|
// TODO: hash password
|
|
|
|
let mut id = [0u8; 32];
|
2024-10-14 06:25:38 -05:00
|
|
|
db::with(|db| match db.authenticate.query_row((&data.name,), |r| r.get::<_, String>(1)) {
|
|
|
|
Ok(hash) => {
|
|
|
|
if verify_password(&hash, &data.password).is_err() {
|
2024-10-08 17:17:13 -05:00
|
|
|
data.error = Some("invalid credentials");
|
|
|
|
} else {
|
|
|
|
getrandom::getrandom(&mut id).unwrap();
|
2024-10-14 15:04:18 -05:00
|
|
|
if db
|
|
|
|
.login
|
|
|
|
.insert((id, &data.name, now() + SESSION_DURATION_SECS))
|
|
|
|
.log("create session query")
|
|
|
|
.is_none()
|
2024-10-08 17:17:13 -05:00
|
|
|
{
|
2024-10-14 15:04:18 -05:00
|
|
|
data.error = Some("internal server error");
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-10-14 06:25:38 -05:00
|
|
|
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
|
|
|
data.error = Some("invalid credentials");
|
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
Err(e) => {
|
2024-11-18 03:31:30 -06:00
|
|
|
log::error!("login queri failed: {e}");
|
2024-10-08 17:17:13 -05:00
|
|
|
data.error = Some("internal server error");
|
|
|
|
}
|
|
|
|
});
|
2024-10-05 16:07:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
if data.error.is_some() {
|
2024-10-14 15:04:18 -05:00
|
|
|
Err(data.render())
|
2024-10-08 17:17:13 -05:00
|
|
|
} else {
|
|
|
|
Ok(AppendHeaders([
|
|
|
|
("hx-location", "/feed".into()),
|
|
|
|
(
|
|
|
|
"set-cookie",
|
|
|
|
format!(
|
|
|
|
"id={}; SameSite=Strict; Secure; Max-Age={SESSION_DURATION_SECS}",
|
|
|
|
to_hex(&id)
|
|
|
|
),
|
|
|
|
),
|
|
|
|
]))
|
|
|
|
}
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
async fn delete(session: Session) -> Redirect {
|
2024-10-14 15:04:18 -05:00
|
|
|
_ = db::with(|q| q.logout.execute((session.id,)).log("delete session query"));
|
2024-10-08 17:17:13 -05:00
|
|
|
redirect("/login")
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
#[derive(Serialize, Deserialize, Default)]
|
|
|
|
struct Signup {
|
|
|
|
name: String,
|
|
|
|
new_password: String,
|
|
|
|
confirm_password: String,
|
2024-10-14 15:04:18 -05:00
|
|
|
#[serde(default)]
|
|
|
|
confirm_no_password: bool,
|
2024-10-08 17:17:13 -05:00
|
|
|
#[serde(skip)]
|
|
|
|
error: Option<&'static str>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PublicPage for Signup {
|
2024-10-10 08:48:08 -05:00
|
|
|
fn render_to_buf(self, buf: &mut String) {
|
2024-10-14 15:04:18 -05:00
|
|
|
let Signup { name, new_password, confirm_password, confirm_no_password, error } = self;
|
|
|
|
let vals = if confirm_no_password { "{\"confirm_no_password\":true}" } else { "{}" };
|
2024-10-10 08:48:08 -05:00
|
|
|
write_html! { (buf)
|
2024-10-14 15:04:18 -05:00
|
|
|
<form "hx-post"="/signup" "hx-swap"="outerHTML" "hx-vals"=vals>
|
2024-10-08 17:17:13 -05:00
|
|
|
if let Some(e) = error { <div class="error">e</div> }
|
|
|
|
<input name="name" type="text" autocomplete="name" placeholder="name" value=name
|
|
|
|
maxlength=MAX_NAME_LENGTH required>
|
|
|
|
<input name="new_password" type="password" autocomplete="new-password" placeholder="new password"
|
|
|
|
value=new_password>
|
|
|
|
<input name="confirm_password" type="password" autocomplete="confirm-password"
|
|
|
|
placeholder="confirm password" value=confirm_password>
|
|
|
|
<input type="submit" value="submit">
|
|
|
|
</form>
|
2024-10-05 16:07:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl Signup {
|
|
|
|
async fn post(axum::Form(mut data): axum::Form<Self>) -> Result<Redirect, Html<String>> {
|
2024-10-14 15:04:18 -05:00
|
|
|
if data.name.len() > MAX_NAME_LENGTH {
|
|
|
|
data.error = Some(formatcp!("name too long, max length is {MAX_NAME_LENGTH}"));
|
|
|
|
return Err(data.render());
|
|
|
|
}
|
|
|
|
|
|
|
|
if !data.confirm_no_password && data.new_password.is_empty() {
|
|
|
|
data.confirm_no_password = true;
|
|
|
|
data.error = Some("Are you sure you don't want to use a password? (then submit again)");
|
|
|
|
return Err(data.render());
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
db::with(|db| {
|
|
|
|
// TODO: hash passwords
|
2024-10-14 06:25:38 -05:00
|
|
|
match db.register.insert((&data.name, hash_password(&data.new_password))) {
|
2024-10-08 17:17:13 -05:00
|
|
|
Ok(_) => {}
|
|
|
|
Err(rusqlite::Error::SqliteFailure(e, _))
|
|
|
|
if e.code == rusqlite::ErrorCode::ConstraintViolation =>
|
|
|
|
{
|
|
|
|
data.error = Some("username already taken");
|
|
|
|
}
|
|
|
|
Err(e) => {
|
2024-10-14 15:04:18 -05:00
|
|
|
log::error!("create user query: {e}");
|
2024-10-08 17:17:13 -05:00
|
|
|
data.error = Some("internal server error");
|
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
if data.error.is_some() {
|
2024-10-14 15:04:18 -05:00
|
|
|
Err(data.render())
|
2024-10-08 17:17:13 -05:00
|
|
|
} else {
|
|
|
|
Ok(redirect("/login"))
|
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-14 06:17:58 -06:00
|
|
|
fn blog_base(s: &mut String, body: impl FnOnce(&mut String)) {
|
|
|
|
let nav_button = |f: &mut String, name: &str| {
|
|
|
|
write_html! {(f)
|
|
|
|
<button "hx-push-url"={format_args!("/blogs/{name}")}
|
|
|
|
"hx-get"={format_args!("/blogs/{name}-view")}
|
|
|
|
"hx-target"="main#blog"
|
|
|
|
"hx-swap"="innerHTML">name</button>
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
write_html! {(*s)
|
|
|
|
<nav><section>
|
|
|
|
<button "hx-push-url"="/" "hx-get"="/blogs/index-view"
|
|
|
|
"hx-target"="main#blog" "hx-swap"="innerHTML">"welcome"</button>
|
|
|
|
for name in &ALL_STATIC_PAGES[1..] {
|
|
|
|
|f|{nav_button(f, name)}
|
|
|
|
}
|
|
|
|
</section></nav>
|
|
|
|
<section id="post-form"></section>
|
|
|
|
<main id="blog">|f|{body(f)}</main>
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-17 09:08:29 -05:00
|
|
|
fn base(body: impl FnOnce(&mut String), session: Option<&Session>) -> Html<String> {
|
2024-10-10 08:48:08 -05:00
|
|
|
let username = session.map(|s| &s.name);
|
2024-10-08 17:17:13 -05:00
|
|
|
|
2024-10-14 15:04:18 -05:00
|
|
|
let nav_button = |f: &mut String, name: &str| {
|
|
|
|
write_html! {(f)
|
|
|
|
<button "hx-push-url"={format_args!("/{name}")}
|
|
|
|
"hx-get"={format_args!("/{name}-view")}
|
|
|
|
"hx-target"="main"
|
|
|
|
"hx-swap"="innerHTML">name</button>
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-10-10 08:48:08 -05:00
|
|
|
Html(html! {
|
|
|
|
"<!DOCTYPE html>"
|
2024-10-08 17:17:13 -05:00
|
|
|
<html lang="en">
|
|
|
|
<head>
|
2024-10-15 05:46:36 -05:00
|
|
|
<meta name="charset" content="UTF-8">
|
2024-12-14 06:17:58 -06:00
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
2024-11-22 17:59:58 -06:00
|
|
|
<meta name="description" content="code dependency hell socila media hblang">
|
2024-10-12 06:07:49 -05:00
|
|
|
<link rel="stylesheet" href="/index.css">
|
2024-11-22 17:59:58 -06:00
|
|
|
<title>"depell"</title>
|
2024-10-08 17:17:13 -05:00
|
|
|
</head>
|
2024-11-22 17:59:58 -06:00
|
|
|
<body hidden>
|
2024-10-08 17:17:13 -05:00
|
|
|
<nav>
|
|
|
|
<button "hx-push-url"="/" "hx-get"="/index-view" "hx-target"="main" "hx-swap"="innerHTML">"depell"</button>
|
|
|
|
<section>
|
|
|
|
if let Some(username) = username {
|
2024-11-18 06:08:46 -06:00
|
|
|
<button "hx-push-url"={format_args!("/profile/{username}")} "hx-get"="/profile-view" "hx-target"="main"
|
2024-10-08 17:17:13 -05:00
|
|
|
"hx-swap"="innerHTML">username</button>
|
2024-10-14 15:04:18 -05:00
|
|
|
|f|{nav_button(f, "feed"); nav_button(f, "post")}
|
2024-10-08 17:17:13 -05:00
|
|
|
<button "hx-delete"="/login">"logout"</button>
|
|
|
|
} else {
|
2024-10-14 15:04:18 -05:00
|
|
|
|f|{nav_button(f, "login"); nav_button(f, "signup")}
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
|
|
|
</section>
|
|
|
|
</nav>
|
|
|
|
<section id="post-form"></section>
|
2024-10-10 08:48:08 -05:00
|
|
|
<main>|f|{body(f)}</main>
|
2024-10-08 17:17:13 -05:00
|
|
|
</body>
|
2024-10-14 15:04:18 -05:00
|
|
|
<script src="https://unpkg.com/htmx.org@2.0.3/dist/htmx.min.js" integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq" crossorigin="anonymous"></script>
|
2024-10-13 05:25:12 -05:00
|
|
|
<script type="module" src="/index.js"></script>
|
2024-10-08 17:17:13 -05:00
|
|
|
</html>
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Session {
|
|
|
|
name: String,
|
|
|
|
id: [u8; 32],
|
|
|
|
}
|
|
|
|
|
|
|
|
#[axum::async_trait]
|
|
|
|
impl<S> axum::extract::FromRequestParts<S> for Session {
|
|
|
|
/// If the extractor fails it'll use this "rejection" type. A rejection is
|
|
|
|
/// a kind of error that can be converted into a response.
|
2024-10-10 01:35:17 -05:00
|
|
|
type Rejection = Redirect;
|
2024-10-08 17:17:13 -05:00
|
|
|
|
|
|
|
/// Perform the extraction.
|
|
|
|
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
|
2024-10-10 01:35:17 -05:00
|
|
|
let err = redirect("/login");
|
2024-10-08 17:17:13 -05:00
|
|
|
|
|
|
|
let value = parts
|
|
|
|
.headers
|
|
|
|
.get_all(COOKIE)
|
|
|
|
.into_iter()
|
|
|
|
.find_map(|c| c.to_str().ok()?.trim().strip_prefix("id="))
|
|
|
|
.map(|c| c.split_once(';').unwrap_or((c, "")).0)
|
2024-10-10 01:35:17 -05:00
|
|
|
.ok_or(err)?;
|
2024-10-08 17:17:13 -05:00
|
|
|
let mut id = [0u8; 32];
|
2024-10-10 01:35:17 -05:00
|
|
|
parse_hex(value, &mut id).ok_or(err)?;
|
2024-10-08 17:17:13 -05:00
|
|
|
|
|
|
|
let (name, expiration) = db::with(|db| {
|
|
|
|
db.get_session
|
2024-10-10 06:04:17 -05:00
|
|
|
.query_row((id,), |r| Ok((r.get::<_, String>(0)?, r.get::<_, u64>(1)?)))
|
2024-10-14 15:04:18 -05:00
|
|
|
.log("fetching session")
|
|
|
|
.ok_or(err)
|
2024-10-08 17:17:13 -05:00
|
|
|
})?;
|
|
|
|
|
|
|
|
if expiration < now() {
|
2024-10-10 01:35:17 -05:00
|
|
|
return Err(err);
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
Ok(Self { name, id })
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn now() -> u64 {
|
|
|
|
std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_secs()
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn parse_hex(hex: &str, dst: &mut [u8]) -> Option<()> {
|
|
|
|
fn hex_to_nibble(b: u8) -> Option<u8> {
|
|
|
|
Some(match b {
|
|
|
|
b'a'..=b'f' => b - b'a' + 10,
|
|
|
|
b'A'..=b'F' => b - b'A' + 10,
|
|
|
|
b'0'..=b'9' => b - b'0',
|
|
|
|
_ => return None,
|
|
|
|
})
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
if hex.len() != dst.len() * 2 {
|
|
|
|
return None;
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
for (d, p) in dst.iter_mut().zip(hex.as_bytes().chunks_exact(2)) {
|
|
|
|
*d = (hex_to_nibble(p[0])? << 4) | hex_to_nibble(p[1])?;
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
Some(())
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn to_hex(src: &[u8]) -> String {
|
|
|
|
use std::fmt::Write;
|
|
|
|
let mut buf = String::new();
|
|
|
|
for &b in src {
|
|
|
|
write!(buf, "{b:02x}").unwrap()
|
|
|
|
}
|
|
|
|
buf
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn main() {
|
2024-10-14 15:04:18 -05:00
|
|
|
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(amain());
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
mod db {
|
|
|
|
use std::cell::RefCell;
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
macro_rules! gen_queries {
|
|
|
|
($vis:vis struct $name:ident {
|
2024-10-14 06:25:38 -05:00
|
|
|
$($qname:ident: $code:expr,)*
|
2024-10-08 17:17:13 -05:00
|
|
|
}) => {
|
|
|
|
$vis struct $name<'a> {
|
|
|
|
$($vis $qname: rusqlite::Statement<'a>,)*
|
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl<'a> $name<'a> {
|
|
|
|
fn new(db: &'a rusqlite::Connection) -> Self {
|
|
|
|
Self {
|
|
|
|
$($qname: db.prepare($code).unwrap(),)*
|
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
}
|
2024-10-08 17:17:13 -05:00
|
|
|
};
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
gen_queries! {
|
|
|
|
pub struct Queries {
|
|
|
|
register: "INSERT INTO user (name, password_hash) VALUES(?, ?)",
|
2024-11-18 03:31:30 -06:00
|
|
|
change_passowrd: "UPDATE user SET password_hash = ? WHERE name = ?",
|
2024-10-14 06:25:38 -05:00
|
|
|
authenticate: "SELECT name, password_hash FROM user WHERE name = ?",
|
2024-10-08 17:17:13 -05:00
|
|
|
login: "INSERT OR REPLACE INTO session (id, username, expiration) VALUES(?, ?, ?)",
|
|
|
|
logout: "DELETE FROM session WHERE id = ?",
|
|
|
|
get_session: "SELECT username, expiration FROM session WHERE id = ?",
|
2024-11-23 04:14:03 -06:00
|
|
|
get_user_posts: "SELECT author, name, timestamp, code, (
|
|
|
|
WITH RECURSIVE roots(name, author, code) AS (
|
|
|
|
SELECT name, author, code FROM post WHERE name = outher.name AND author = outher.author
|
|
|
|
UNION
|
|
|
|
SELECT post.name, post.author, post.code FROM
|
|
|
|
post JOIN import ON post.name = import.from_name
|
|
|
|
AND post.author = import.from_author
|
|
|
|
JOIN roots ON import.to_name = roots.name
|
|
|
|
AND import.to_author = roots.author
|
|
|
|
) SELECT (count(*) - 1) FROM roots
|
|
|
|
) AS imports, (
|
|
|
|
WITH RECURSIVE roots(name, author, code) AS (
|
|
|
|
SELECT name, author, code FROM post WHERE name = outher.name AND author = outher.author
|
|
|
|
UNION
|
|
|
|
SELECT post.name, post.author, post.code FROM post
|
|
|
|
JOIN import ON post.name = import.from_name
|
|
|
|
AND post.author = import.from_author
|
|
|
|
JOIN roots ON import.to_name = roots.name
|
|
|
|
AND import.to_author = roots.author
|
|
|
|
) SELECT count(*) FROM roots
|
|
|
|
JOIN run ON roots.name = run.code_name
|
|
|
|
AND roots.author = run.code_author
|
|
|
|
) AS runs FROM post as outher WHERE author = ? ORDER BY timestamp DESC",
|
2024-11-22 17:06:25 -06:00
|
|
|
// TODO: we might want to cache the recursive queries
|
|
|
|
get_pots_before: "SELECT author, name, timestamp, code, (
|
|
|
|
WITH RECURSIVE roots(name, author, code) AS (
|
|
|
|
SELECT name, author, code FROM post WHERE name = outher.name AND author = outher.author
|
|
|
|
UNION
|
|
|
|
SELECT post.name, post.author, post.code FROM
|
|
|
|
post JOIN import ON post.name = import.from_name
|
|
|
|
AND post.author = import.from_author
|
|
|
|
JOIN roots ON import.to_name = roots.name
|
|
|
|
AND import.to_author = roots.author
|
|
|
|
) SELECT (count(*) - 1) FROM roots
|
2024-11-23 03:18:05 -06:00
|
|
|
) AS imports, (
|
|
|
|
WITH RECURSIVE roots(name, author, code) AS (
|
|
|
|
SELECT name, author, code FROM post WHERE name = outher.name AND author = outher.author
|
|
|
|
UNION
|
|
|
|
SELECT post.name, post.author, post.code FROM post
|
|
|
|
JOIN import ON post.name = import.from_name
|
|
|
|
AND post.author = import.from_author
|
|
|
|
JOIN roots ON import.to_name = roots.name
|
|
|
|
AND import.to_author = roots.author
|
|
|
|
) SELECT count(*) FROM roots
|
|
|
|
JOIN run ON roots.name = run.code_name
|
|
|
|
AND roots.author = run.code_author
|
|
|
|
) as runs FROM post AS outher WHERE timestamp < ?",
|
2024-10-08 17:17:13 -05:00
|
|
|
create_post: "INSERT INTO post (name, author, timestamp, code) VALUES(?, ?, ?, ?)",
|
2024-10-14 06:25:38 -05:00
|
|
|
fetch_deps: "
|
|
|
|
WITH RECURSIVE roots(name, author, code) AS (
|
|
|
|
SELECT name, author, code FROM post WHERE name = ? AND author = ?
|
2024-10-26 16:24:45 -05:00
|
|
|
UNION
|
2024-10-14 06:25:38 -05:00
|
|
|
SELECT post.name, post.author, post.code FROM
|
|
|
|
post JOIN import ON post.name = import.to_name
|
|
|
|
AND post.author = import.to_author
|
|
|
|
JOIN roots ON import.from_name = roots.name
|
|
|
|
AND import.from_author = roots.author
|
|
|
|
) SELECT * FROM roots;
|
|
|
|
",
|
|
|
|
create_import: "INSERT INTO import(to_author, to_name, from_author, from_name)
|
|
|
|
VALUES(?, ?, ?, ?)",
|
2024-11-23 03:18:05 -06:00
|
|
|
creata_run: "INSERT OR IGNORE INTO run(code_name, code_author, runner) VALUES(?, ?, ?)",
|
2024-10-08 17:17:13 -05:00
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
struct Db {
|
|
|
|
queries: Queries<'static>,
|
|
|
|
_db: Box<rusqlite::Connection>,
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl Db {
|
|
|
|
fn new() -> Self {
|
|
|
|
let db = Box::new(rusqlite::Connection::open("db.sqlite").unwrap());
|
|
|
|
Self {
|
|
|
|
queries: Queries::new(unsafe {
|
|
|
|
std::mem::transmute::<&rusqlite::Connection, &rusqlite::Connection>(&db)
|
|
|
|
}),
|
|
|
|
_db: db,
|
|
|
|
}
|
|
|
|
}
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
pub fn with<T>(with: impl FnOnce(&mut Queries) -> T) -> T {
|
|
|
|
thread_local! { static DB_CONN: RefCell<Db> = RefCell::new(Db::new()); }
|
|
|
|
DB_CONN.with_borrow_mut(|q| with(&mut q.queries))
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
pub fn init() {
|
2024-11-22 17:06:25 -06:00
|
|
|
const SCHEMA_VERSION: usize = 0;
|
|
|
|
const MIGRATIONS: &[&str] = &[include_str!("migrations/1.sql")];
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
let db = rusqlite::Connection::open("db.sqlite").unwrap();
|
|
|
|
db.execute_batch(include_str!("schema.sql")).unwrap();
|
2024-11-22 17:06:25 -06:00
|
|
|
|
|
|
|
let schema_version =
|
|
|
|
db.pragma_query_value(None, "user_version", |v| v.get::<_, usize>(0)).unwrap();
|
|
|
|
|
|
|
|
if schema_version != SCHEMA_VERSION {
|
|
|
|
for &mig in &MIGRATIONS[schema_version..] {
|
|
|
|
db.execute_batch(mig).expect(mig);
|
|
|
|
}
|
|
|
|
db.pragma_update(None, "user_version", SCHEMA_VERSION).unwrap();
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
Queries::new(&db);
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn redirect(to: &'static str) -> Redirect {
|
|
|
|
AppendHeaders([("hx-location", to)])
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-14 15:04:18 -05:00
|
|
|
trait PublicPage: Default {
|
|
|
|
fn render_to_buf(self, buf: &mut String);
|
|
|
|
|
|
|
|
fn render(self) -> Html<String> {
|
|
|
|
let mut str = String::new();
|
|
|
|
self.render_to_buf(&mut str);
|
|
|
|
Html(str)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get() -> Html<String> {
|
|
|
|
Self::default().render()
|
|
|
|
}
|
|
|
|
|
2024-10-17 09:08:29 -05:00
|
|
|
async fn page(session: Option<Session>) -> Html<String> {
|
|
|
|
base(|s| Self::default().render_to_buf(s), session.as_ref())
|
2024-10-14 15:04:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
trait Page: Default {
|
|
|
|
fn render_to_buf(self, session: &Session, buf: &mut String);
|
|
|
|
|
|
|
|
fn render(self, session: &Session) -> Html<String> {
|
|
|
|
let mut str = String::new();
|
|
|
|
self.render_to_buf(session, &mut str);
|
|
|
|
Html(str)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get(session: Session) -> Html<String> {
|
|
|
|
Self::default().render(&session)
|
|
|
|
}
|
|
|
|
|
2024-10-17 09:08:29 -05:00
|
|
|
async fn page(session: Option<Session>) -> Result<Html<String>, axum::response::Redirect> {
|
2024-10-14 15:04:18 -05:00
|
|
|
match session {
|
|
|
|
Some(session) => {
|
2024-10-17 09:08:29 -05:00
|
|
|
Ok(base(|f| Self::default().render_to_buf(&session, f), Some(&session)))
|
2024-10-14 15:04:18 -05:00
|
|
|
}
|
|
|
|
None => Err(axum::response::Redirect::permanent("/login")),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
trait ResultExt<O, E> {
|
|
|
|
fn log(self, prefix: impl Display) -> Option<O>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<O, E: Display> ResultExt<O, E> for Result<O, E> {
|
|
|
|
fn log(self, prefix: impl Display) -> Option<O> {
|
|
|
|
match self {
|
|
|
|
Ok(v) => Some(v),
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("{prefix}: {e}");
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
struct Logger;
|
2024-10-06 03:51:33 -05:00
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
impl log::Log for Logger {
|
|
|
|
fn enabled(&self, _: &log::Metadata) -> bool {
|
|
|
|
true
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn log(&self, record: &log::Record) {
|
|
|
|
if self.enabled(record.metadata()) {
|
2024-10-14 15:04:18 -05:00
|
|
|
eprintln!("{} - {}", record.module_path().unwrap_or("=="), record.args());
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 17:17:13 -05:00
|
|
|
fn flush(&self) {}
|
2024-10-06 03:51:33 -05:00
|
|
|
}
|