Add first version of server
Signed-off-by: Marcel Müller <neikos@neikos.email>
This commit is contained in:
parent
373541c5ef
commit
b17f9fa545
7 changed files with 2160 additions and 14 deletions
|
|
@ -1,3 +1,255 @@
|
|||
fn main() {
|
||||
println!("Hello, world!");
|
||||
use axum::Form;
|
||||
use axum::Router;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Html;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::Redirect;
|
||||
use axum::routing::get;
|
||||
use axum::routing::post;
|
||||
use axum_login::AuthManagerLayerBuilder;
|
||||
use axum_login::AuthUser;
|
||||
use axum_login::AuthnBackend;
|
||||
use axum_login::login_required;
|
||||
use displaydoc::Display;
|
||||
use password_auth::generate_hash;
|
||||
use password_auth::verify_password;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::SqlitePool;
|
||||
use sqlx::prelude::FromRow;
|
||||
use thiserror::Error;
|
||||
use tokio::task;
|
||||
use tokio::task::AbortHandle;
|
||||
use tower_sessions::ExpiredDeletion;
|
||||
use tower_sessions::SessionManagerLayer;
|
||||
use tower_sessions_sqlx_store::SqliteStore;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
run().await
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
|
||||
struct User {
|
||||
id: i64,
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
impl AuthUser for User {
|
||||
type Id = i64;
|
||||
|
||||
fn id(&self) -> Self::Id {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn session_auth_hash(&self) -> &[u8] {
|
||||
self.password.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Backend {
|
||||
db: SqlitePool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct Credentials {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, Display)]
|
||||
pub enum AuthBackendError {
|
||||
/// An error occurred while interacting with the database
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
|
||||
/// A tokio task could not be joined
|
||||
TaskJoin(#[from] task::JoinError),
|
||||
}
|
||||
|
||||
impl AuthnBackend for Backend {
|
||||
type User = User;
|
||||
type Credentials = Credentials;
|
||||
type Error = AuthBackendError;
|
||||
|
||||
async fn authenticate(
|
||||
&self,
|
||||
creds: Self::Credentials,
|
||||
) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user: Option<Self::User> = sqlx::query_as("SELECT * FROM users WHERE username = ?")
|
||||
.bind(creds.username)
|
||||
.fetch_optional(&self.db)
|
||||
.await?;
|
||||
|
||||
task::spawn_blocking(move || {
|
||||
Ok(user.filter(|user| verify_password(&creds.password, &user.password).is_ok()))
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn get_user(
|
||||
&self,
|
||||
user_id: &axum_login::UserId<Self>,
|
||||
) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user = sqlx::query_as("SELECT * FROM users WHERE id = ?")
|
||||
.bind(user_id)
|
||||
.fetch_optional(&self.db)
|
||||
.await?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct AppState {
|
||||
pub db: SqlitePool,
|
||||
}
|
||||
|
||||
async fn run() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
let db = SqlitePool::connect("sqlite://database.db").await?;
|
||||
sqlx::migrate!().run(&db).await?;
|
||||
let session_store = SqliteStore::new(db.clone());
|
||||
session_store.migrate().await?;
|
||||
|
||||
let deletion_task = task::spawn(
|
||||
session_store
|
||||
.clone()
|
||||
.continuously_delete_expired(tokio::time::Duration::from_secs(60)),
|
||||
);
|
||||
|
||||
let session_layer = SessionManagerLayer::new(session_store).with_expiry(
|
||||
tower_sessions::Expiry::OnInactivity(tower_sessions::cookie::time::Duration::days(7)),
|
||||
);
|
||||
|
||||
let backend = Backend { db: db.clone() };
|
||||
let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
|
||||
|
||||
let app = Router::new()
|
||||
.route("/protected", get(show_protected))
|
||||
.route_layer(login_required!(Backend, login_url = "/login"))
|
||||
.route("/login", get(show_login))
|
||||
.route("/login", post(do_login))
|
||||
.route("/register", get(show_register))
|
||||
.route("/register", post(do_register))
|
||||
.layer(auth_layer)
|
||||
.with_state(AppState { db });
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
axum::serve(listener, app.into_make_service())
|
||||
.with_graceful_shutdown(shutdown_signal(deletion_task.abort_handle()))
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal(handle: AbortHandle) {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("Failed to install Ctrl+C handler");
|
||||
};
|
||||
|
||||
let terminate = async {
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("Failed to install terminate signal handler")
|
||||
.recv()
|
||||
.await;
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {}
|
||||
_ = terminate => {}
|
||||
};
|
||||
|
||||
handle.abort();
|
||||
}
|
||||
|
||||
async fn show_protected() -> Html<String> {
|
||||
format!(
|
||||
r##"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
Yay, you did it!
|
||||
</body>
|
||||
</html>
|
||||
"##
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
async fn show_login() -> Html<String> {
|
||||
format!(
|
||||
r##"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<form action="/login" method="POST">
|
||||
<input type="text" name="username"/>
|
||||
<input type="password" name="password"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
"##
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
async fn show_register() -> Html<String> {
|
||||
format!(
|
||||
r##"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<form action="/register" method="POST">
|
||||
<input type="text" name="username"/>
|
||||
<input type="password" name="password"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
"##
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
type AuthSession = axum_login::AuthSession<Backend>;
|
||||
|
||||
async fn do_register(
|
||||
app_state: State<AppState>,
|
||||
Form(creds): Form<Credentials>,
|
||||
) -> Result<impl IntoResponse, Html<String>> {
|
||||
sqlx::query("INSERT INTO users (username, password) VALUES (?, ?)")
|
||||
.bind(creds.username)
|
||||
.bind(generate_hash(creds.password))
|
||||
.execute(&app_state.db)
|
||||
.await
|
||||
.map_err(|err| Html(err.to_string()))?;
|
||||
|
||||
Ok(Redirect::to("/login").into_response())
|
||||
}
|
||||
|
||||
async fn do_login(
|
||||
mut auth_session: AuthSession,
|
||||
Form(creds): Form<Credentials>,
|
||||
) -> impl IntoResponse {
|
||||
let user = match auth_session.authenticate(creds.clone()).await {
|
||||
Ok(Some(user)) => user,
|
||||
Ok(None) => return StatusCode::UNAUTHORIZED.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
|
||||
if auth_session.login(&user).await.is_err() {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||
}
|
||||
|
||||
Redirect::to("/protected").into_response()
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue