1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
|
mod account;
mod admin;
mod config;
mod login;
mod store;
use std::{future::IntoFuture, path::PathBuf, sync::Arc};
use axum::{
body::Body,
extract::FromRef,
http::{header::CONTENT_TYPE, StatusCode},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
};
use axum_extra::extract::CookieJar;
use cursive::reexports::ahash::HashSet;
use eyre::Context;
use maud::{html, PreEscaped};
use tap::Pipe;
use tokio::{net::TcpListener, select};
use crate::server::store::Store;
use self::config::Config;
pub async fn serve() -> eyre::Result<()> {
let config_path = std::env::args()
.skip(2)
.next()
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap().join("dissociate.toml"));
let config = Config::load(&config_path)?;
let store = Store::load(config.data).await?;
println!("admin listening on {:?}", config.admin_socket);
let admin_serve = admin::serve(&config.admin_socket, config.web_base.clone(), store.clone())?;
let listener = TcpListener::bind(config.web_socket).await?;
let app = Router::new()
.pipe(login::bind)
.pipe(account::bind)
.with_state(ApiState {
store,
cookie_domain: CookieDomain(config.cookie_domain),
handoffs: Handoffs(Arc::new(config.handoffs)),
})
.fallback(get(|| async {
render_html(
html!(title { "not found" }),
html! {
h1 { "404 not found" }
p {"sowwy :("}
},
)
}));
println!("web listening on {:?}", config.web_socket);
let web_serve = axum::serve(listener, app).into_future();
select! {
res = admin_serve => res.wrap_err("in admin"),
res = web_serve => res.wrap_err("in web"),
}
}
#[derive(Clone, FromRef)]
struct ApiState {
pub store: Store,
pub cookie_domain: CookieDomain,
pub handoffs: Handoffs,
}
#[derive(Clone)]
struct CookieDomain(Option<String>);
#[derive(Clone)]
struct Handoffs(Arc<HashSet<String>>);
fn render_html(head: PreEscaped<impl AsRef<str>>, body: PreEscaped<impl AsRef<str>>) -> Response {
let html = html! {
(PreEscaped("<!doctype html>"))
html {
head {(head)}
body {(body)}
}
}
.into_string();
Response::builder()
.header(CONTENT_TYPE, "text/html; charset=utf-8")
.body(Body::new(html))
.unwrap()
}
trait MakeErrorMessage<T> {
fn error_message(self, status: StatusCode, message: impl ToString) -> Result<T, Response>;
}
impl<T, E: ToString> MakeErrorMessage<T> for Result<T, E> {
fn error_message(self, status: StatusCode, message: impl ToString) -> Result<T, Response> {
self.map_err(|err| {
render_html(
html!(title { "error" }),
html! {
h1 { (status.canonical_reason().unwrap_or_else(|| status.as_str())) }
pre { (err.to_string()) ": " (message.to_string()) }
},
)
})
}
}
impl<T> MakeErrorMessage<T> for Option<T> {
fn error_message(self, status: StatusCode, message: impl ToString) -> Result<T, Response> {
self.ok_or_else(|| {
render_html(
html!(title { "error" }),
html! {
h1 { (status.canonical_reason().unwrap_or_else(|| status.as_str())) }
pre { (message.to_string()) }
},
)
})
}
}
trait MakeError<T> {
fn make_error(self) -> Result<T, Response>;
}
impl<T> MakeError<T> for std::io::Result<T> {
fn make_error(self) -> Result<T, Response> {
self.error_message(StatusCode::INTERNAL_SERVER_ERROR, "internal io error")
}
}
trait Nevermind<T> {
fn prompt_login(self) -> Result<T, Response>;
fn prompt_logout(self) -> Result<T, Response>;
}
impl<T> Nevermind<T> for Option<T> {
fn prompt_login(self) -> Result<T, Response> {
self.ok_or_else(|| Redirect::to("/login").into_response())
}
fn prompt_logout(self) -> Result<T, Response> {
self.ok_or_else(|| Redirect::to("/login").into_response())
}
}
async fn account_auth(jar: &CookieJar, store: &Store) -> Option<String> {
let cookie = jar.get("dissociate-token")?;
let token = cookie.value();
let (name, _) = store.check_token(token).await?;
Some(name)
}
|