-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
app.rs
100 lines (82 loc) 路 2.99 KB
/
app.rs
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
use axum_login::{
login_required,
tower_sessions::{ExpiredDeletion, Expiry, SessionManagerLayer},
AuthManagerLayerBuilder,
};
use axum_messages::MessagesManagerLayer;
use sqlx::SqlitePool;
use time::Duration;
use tokio::{signal, task::AbortHandle};
use tower_sessions::cookie::Key;
use tower_sessions_sqlx_store::SqliteStore;
use crate::{
users::Backend,
web::{auth, protected},
};
pub struct App {
db: SqlitePool,
}
impl App {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
let db = SqlitePool::connect(":memory:").await?;
sqlx::migrate!().run(&db).await?;
Ok(Self { db })
}
pub async fn serve(self) -> Result<(), Box<dyn std::error::Error>> {
// Session layer.
//
// This uses `tower-sessions` to establish a layer that will provide the session
// as a request extension.
let session_store = SqliteStore::new(self.db.clone());
session_store.migrate().await?;
let deletion_task = tokio::task::spawn(
session_store
.clone()
.continuously_delete_expired(tokio::time::Duration::from_secs(60)),
);
// Generate a cryptographic key to sign the session cookie.
let key = Key::generate();
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::days(1)))
.with_signed(key);
// Auth service.
//
// This combines the session layer with our backend to establish the auth
// service which will provide the auth session as a request extension.
let backend = Backend::new(self.db);
let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
let app = protected::router()
.route_layer(login_required!(Backend, login_url = "/login"))
.merge(auth::router())
.layer(MessagesManagerLayer)
.layer(auth_layer);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
// Ensure we use a shutdown signal to abort the deletion task.
axum::serve(listener, app.into_make_service())
.with_graceful_shutdown(shutdown_signal(deletion_task.abort_handle()))
.await?;
deletion_task.await??;
Ok(())
}
}
async fn shutdown_signal(deletion_task_abort_handle: AbortHandle) {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => { deletion_task_abort_handle.abort() },
_ = terminate => { deletion_task_abort_handle.abort() },
}
}