Setup and authentication WIP
- Add page for creating intial admin user - Add JWT for authentication of logged-in users - Add tracing - Some improvements to error handling
This commit is contained in:
parent
54350e3919
commit
95362c8a99
|
|
@ -1,2 +1,3 @@
|
||||||
[env]
|
[env]
|
||||||
LOCALITY_STATIC_FILE_PATH = { value = "static", relative = true }
|
LOCALITY_STATIC_FILE_PATH = { value = "static", relative = true }
|
||||||
|
LOCALITY_HMAC_SECRET = "Not-secret testing secret"
|
||||||
12
Cargo.toml
12
Cargo.toml
|
|
@ -10,9 +10,19 @@ tokio = { version = "1", features = ["rt-multi-thread"]}
|
||||||
axum = { version = "0.7", default_features = false, features = ["http1", "form", "tokio"] }
|
axum = { version = "0.7", default_features = false, features = ["http1", "form", "tokio"] }
|
||||||
askama = "0.12"
|
askama = "0.12"
|
||||||
askama_axum = "0.4"
|
askama_axum = "0.4"
|
||||||
tower-http = { version = "0.5", features = ["fs"] }
|
tower-http = { version = "0.5", features = ["fs", "trace"] }
|
||||||
deadpool-postgres = { version = "0.12", features = ["rt_tokio_1"] }
|
deadpool-postgres = { version = "0.12", features = ["rt_tokio_1"] }
|
||||||
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
|
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
argon2 = { version = "0.5", features = ["password-hash", "std"] }
|
argon2 = { version = "0.5", features = ["password-hash", "std"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
base64 = "0.21"
|
||||||
|
hmac = "0.12"
|
||||||
|
sha2 = "0.10"
|
||||||
|
digest = "0.10"
|
||||||
|
chrono = { version = "0.4.34", features = ["serde"] }
|
||||||
|
axum-extra = { version = "0.9", features = ["cookie"] }
|
||||||
|
http = "1.0"
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", default_features = false, features = ["std", "fmt", "ansi"] }
|
||||||
|
|
|
||||||
82
src/admin.rs
82
src/admin.rs
|
|
@ -1,6 +1,9 @@
|
||||||
use {
|
use {
|
||||||
crate::{
|
crate::{
|
||||||
authentication::{authenticate_user, Password},
|
authentication::{
|
||||||
|
authenticate_user_with_jwt, authenticate_user_with_password, check_if_user_is_admin,
|
||||||
|
create_jwt_for_user, AuthenticatedAdminUser, ParsedJwt, Password,
|
||||||
|
},
|
||||||
db::Database,
|
db::Database,
|
||||||
error::Error,
|
error::Error,
|
||||||
},
|
},
|
||||||
|
|
@ -8,16 +11,25 @@ use {
|
||||||
askama_axum::{IntoResponse, Response},
|
askama_axum::{IntoResponse, Response},
|
||||||
axum::{
|
axum::{
|
||||||
extract::State,
|
extract::State,
|
||||||
|
response::Redirect,
|
||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
Form, Router,
|
Form, Router,
|
||||||
},
|
},
|
||||||
|
axum_extra::extract::{
|
||||||
|
cookie::{Cookie, SameSite},
|
||||||
|
CookieJar,
|
||||||
|
},
|
||||||
serde::Deserialize,
|
serde::Deserialize,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn routes() -> Router<Database> {
|
pub fn routes() -> Router<Database> {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/", get(root))
|
.route("/", get(root))
|
||||||
.route("/create_initial_admin_user", post(create_first_admin_user))
|
.route("/create_first_admin_user", get(get_create_first_admin_user))
|
||||||
|
.route(
|
||||||
|
"/create_first_admin_user",
|
||||||
|
post(post_create_first_admin_user),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
|
|
@ -30,27 +42,60 @@ struct FirstLoginTemplate {}
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
#[template(path = "admin/index.html")]
|
#[template(path = "admin/index.html")]
|
||||||
struct IndexTemplate {}
|
struct IndexTemplate<'a> {
|
||||||
|
admin_user_name: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
async fn root(State(db): State<Database>) -> Result<Response, Error> {
|
async fn check_jwt(db: &Database, cookie_jar: &CookieJar) -> Result<AuthenticatedAdminUser, Error> {
|
||||||
|
match authenticate_user_with_jwt(
|
||||||
|
db,
|
||||||
|
cookie_jar
|
||||||
|
.get("jwt")
|
||||||
|
.map(|cookie| cookie.value_trimmed())
|
||||||
|
.ok_or(Error::Forbidden)?,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
ParsedJwt::Valid(user) => check_if_user_is_admin(db, &user)
|
||||||
|
.await?
|
||||||
|
.ok_or(Error::Forbidden),
|
||||||
|
ParsedJwt::InvalidSignature => Err(Error::Forbidden),
|
||||||
|
ParsedJwt::UserNotFound => Err(Error::Forbidden),
|
||||||
|
ParsedJwt::Expired(user) => Err(Error::JwtExpired(user)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
|
async fn root(cookie_jar: CookieJar, State(db): State<Database>) -> Result<Response, Error> {
|
||||||
Ok(if !db.has_admin_users().await? {
|
Ok(if !db.has_admin_users().await? {
|
||||||
CreateFirstUserTemplate {}.into_response()
|
Redirect::temporary("admin/create_first_admin_user").into_response()
|
||||||
} else {
|
} else {
|
||||||
IndexTemplate {}.into_response()
|
let admin_user = check_jwt(&db, &cookie_jar).await?;
|
||||||
|
IndexTemplate {
|
||||||
|
admin_user_name: &admin_user.real_name,
|
||||||
|
}
|
||||||
|
.into_response()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[tracing::instrument]
|
||||||
|
async fn get_create_first_admin_user() -> CreateFirstUserTemplate {
|
||||||
|
CreateFirstUserTemplate {}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug)]
|
||||||
struct CreateFirstUserParameters {
|
struct CreateFirstUserParameters {
|
||||||
real_name: String,
|
real_name: String,
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_first_admin_user(
|
#[tracing::instrument]
|
||||||
|
async fn post_create_first_admin_user(
|
||||||
|
cookie_jar: CookieJar,
|
||||||
State(db): State<Database>,
|
State(db): State<Database>,
|
||||||
Form(params): Form<CreateFirstUserParameters>,
|
Form(params): Form<CreateFirstUserParameters>,
|
||||||
) -> Result<FirstLoginTemplate, Error> {
|
) -> Result<(CookieJar, FirstLoginTemplate), Error> {
|
||||||
let user = db
|
let user = db
|
||||||
.create_first_admin_user(
|
.create_first_admin_user(
|
||||||
¶ms.real_name,
|
¶ms.real_name,
|
||||||
|
|
@ -58,12 +103,15 @@ async fn create_first_admin_user(
|
||||||
&Password::new(¶ms.password)?.into(),
|
&Password::new(¶ms.password)?.into(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
if let Some(_user) = authenticate_user(&db, user, ¶ms.password).await? {
|
let user = authenticate_user_with_password(&db, user, ¶ms.password)
|
||||||
// Store cookie and display configuration page
|
.await?
|
||||||
todo!();
|
.ok_or(Error::Unexpected(
|
||||||
} else {
|
"Could not authenticate newly-created user.".to_string(),
|
||||||
// Report failure
|
))?;
|
||||||
todo!();
|
Ok((
|
||||||
}
|
cookie_jar.add(
|
||||||
Ok(FirstLoginTemplate {})
|
Cookie::build(("jwt", create_jwt_for_user(&user)?)).same_site(SameSite::Strict),
|
||||||
|
),
|
||||||
|
FirstLoginTemplate {},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,176 @@
|
||||||
|
use {
|
||||||
|
base64::engine::{general_purpose::STANDARD as base64_encoder, Engine as _},
|
||||||
|
chrono::{DateTime, Duration, Utc},
|
||||||
|
hmac::{Hmac, Mac},
|
||||||
|
serde::{Deserialize, Serialize},
|
||||||
|
sha2::Sha256,
|
||||||
|
tracing::{error, warn},
|
||||||
|
};
|
||||||
|
|
||||||
|
use {
|
||||||
|
super::AuthenticatedUser,
|
||||||
|
crate::config::get_config,
|
||||||
|
crate::db::{Database, User, UserId},
|
||||||
|
};
|
||||||
|
|
||||||
|
const COOKIE_EXPIRY_TIME: Duration = Duration::weeks(1);
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Error {
|
||||||
|
BadJwt,
|
||||||
|
|
||||||
|
#[allow(clippy::enum_variant_names)]
|
||||||
|
DatabaseError,
|
||||||
|
|
||||||
|
#[allow(clippy::enum_variant_names)]
|
||||||
|
HmacError,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Error {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
match self {
|
||||||
|
Error::BadJwt => "BadJwt",
|
||||||
|
Error::DatabaseError => "DatabaseError",
|
||||||
|
Error::HmacError => "HmacError",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for Error {}
|
||||||
|
|
||||||
|
impl From<serde_json::Error> for Error {
|
||||||
|
fn from(value: serde_json::Error) -> Self {
|
||||||
|
warn!(details = value.to_string(), "JWT contained invalid JSON");
|
||||||
|
Error::BadJwt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<base64::DecodeError> for Error {
|
||||||
|
fn from(value: base64::DecodeError) -> Self {
|
||||||
|
warn!(details = value.to_string(), "JWT contained invalid BASE64");
|
||||||
|
Error::BadJwt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::string::FromUtf8Error> for Error {
|
||||||
|
fn from(value: std::string::FromUtf8Error) -> Self {
|
||||||
|
warn!(details = value.to_string(), "JWT contained invalid UTF-8");
|
||||||
|
Error::BadJwt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<crate::db::Error> for Error {
|
||||||
|
fn from(value: crate::db::Error) -> Self {
|
||||||
|
error!(details = value.to_string(), "Database error");
|
||||||
|
Error::DatabaseError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<digest::MacError> for Error {
|
||||||
|
fn from(_value: digest::MacError) -> Self {
|
||||||
|
error!("Bug in JWT HMAC code.");
|
||||||
|
Error::HmacError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
/// Result type for [authenticate_user_with_jwt()].
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ParsedJwt {
|
||||||
|
/// JWT is a valid JWT, here is the [AuthenticatedUser].
|
||||||
|
Valid(AuthenticatedUser),
|
||||||
|
/// JWT was valid but is expired
|
||||||
|
Expired(User),
|
||||||
|
/// JWT signature does not match contents
|
||||||
|
InvalidSignature,
|
||||||
|
/// JWT is valid, but the user id is not in the database
|
||||||
|
UserNotFound,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Header<'a> {
|
||||||
|
#[serde(rename = "alg")]
|
||||||
|
algorithm: &'a str,
|
||||||
|
#[serde(rename = "typ")]
|
||||||
|
token_type: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Payload {
|
||||||
|
#[serde(rename = "sub")]
|
||||||
|
user_id: UserId,
|
||||||
|
|
||||||
|
#[serde(rename = "exp")]
|
||||||
|
expiry: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mac() -> Hmac<Sha256> {
|
||||||
|
Hmac::new_from_slice(&get_config().unwrap().hmac_secret)
|
||||||
|
.expect("HMAC can take key of any size.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Given an [AuthenticatedUser], create a JWT for use as a cookie to
|
||||||
|
/// keep that user logged in.
|
||||||
|
#[tracing::instrument]
|
||||||
|
pub fn create_jwt_for_user(user: &AuthenticatedUser) -> Result<String> {
|
||||||
|
let header = base64_encoder.encode(
|
||||||
|
serde_json::to_string(&Header {
|
||||||
|
algorithm: "HS256",
|
||||||
|
token_type: "JWT",
|
||||||
|
})?
|
||||||
|
.as_bytes(),
|
||||||
|
);
|
||||||
|
let payload = base64_encoder.encode(
|
||||||
|
serde_json::to_string(&Payload {
|
||||||
|
user_id: user.get_id(),
|
||||||
|
expiry: Utc::now() + COOKIE_EXPIRY_TIME,
|
||||||
|
})?
|
||||||
|
.as_bytes(),
|
||||||
|
);
|
||||||
|
let mut mac = mac();
|
||||||
|
mac.update(format!("{}.{}", header, payload).as_bytes());
|
||||||
|
let signature = base64_encoder.encode(mac.finalize().into_bytes());
|
||||||
|
Ok(format!("{}.{}.{}", header, payload, signature))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Given JWT string created by [create_jwt_for_user()], check if the
|
||||||
|
/// JWT is valid and return an [AuthenticatedUser] if it is.
|
||||||
|
#[tracing::instrument]
|
||||||
|
pub async fn authenticate_user_with_jwt(db: &Database, jwt: &str) -> Result<ParsedJwt> {
|
||||||
|
if let [header, payload, signature] = jwt.split('.').collect::<Vec<_>>().as_slice() {
|
||||||
|
let mut mac = mac();
|
||||||
|
mac.update(format!("{}.{}", header, payload).as_bytes());
|
||||||
|
if mac.verify_slice(signature.as_bytes()).is_err() {
|
||||||
|
Ok(ParsedJwt::InvalidSignature)
|
||||||
|
} else {
|
||||||
|
let header_json = String::from_utf8(base64_encoder.decode(header)?)?;
|
||||||
|
let header: Header = serde_json::from_str(&header_json)?;
|
||||||
|
if header.algorithm != "HS256" || header.token_type != "JWT" {
|
||||||
|
warn!("JWT does not have expected algorithm or type.");
|
||||||
|
Err(Error::BadJwt)
|
||||||
|
} else {
|
||||||
|
let payload: Payload =
|
||||||
|
serde_json::from_str(&String::from_utf8(base64_encoder.decode(payload)?)?)?;
|
||||||
|
Ok(dbg!(
|
||||||
|
if let Some(user) = db.get_user_with_id(payload.user_id).await? {
|
||||||
|
if payload.expiry < Utc::now() {
|
||||||
|
ParsedJwt::Valid(AuthenticatedUser(user))
|
||||||
|
} else {
|
||||||
|
ParsedJwt::Expired(user)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ParsedJwt::UserNotFound
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warn!("Invalid JWT");
|
||||||
|
Err(Error::BadJwt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,10 @@ use {
|
||||||
std::ops::Deref,
|
std::ops::Deref,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
mod jwt;
|
||||||
|
|
||||||
|
pub use jwt::{authenticate_user_with_jwt, create_jwt_for_user, Error as JwtError, ParsedJwt};
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum AuthenticationError {
|
pub enum AuthenticationError {
|
||||||
#[error("Could not get password hash from database: {}", .0.to_string())]
|
#[error("Could not get password hash from database: {}", .0.to_string())]
|
||||||
|
|
@ -18,29 +22,25 @@ pub enum AuthenticationError {
|
||||||
HashError(#[from] argon2::password_hash::Error),
|
HashError(#[from] argon2::password_hash::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AuthenticatedUser {
|
pub struct AuthenticatedUser(db::User);
|
||||||
user: db::User,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for AuthenticatedUser {
|
impl Deref for AuthenticatedUser {
|
||||||
type Target = db::User;
|
type Target = db::User;
|
||||||
|
|
||||||
fn deref(&self) -> &db::User {
|
fn deref(&self) -> &db::User {
|
||||||
&self.user
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct AuthenticatedAdminUser {
|
pub struct AuthenticatedAdminUser(db::User);
|
||||||
user: db::User,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for AuthenticatedAdminUser {
|
impl Deref for AuthenticatedAdminUser {
|
||||||
type Target = db::User;
|
type Target = db::User;
|
||||||
|
|
||||||
fn deref(&self) -> &db::User {
|
fn deref(&self) -> &db::User {
|
||||||
&self.user
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -81,15 +81,26 @@ impl From<Password> for db::PasswordHash {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn authenticate_user(
|
pub async fn authenticate_user_with_password(
|
||||||
db: &Database,
|
db: &Database,
|
||||||
user: db::User,
|
user: db::User,
|
||||||
supplied_password: &str,
|
supplied_password: &str,
|
||||||
) -> Result<Option<AuthenticatedUser>, AuthenticationError> {
|
) -> Result<Option<AuthenticatedUser>, AuthenticationError> {
|
||||||
let password: Password = db.get_password_for_user(&user).await?.into();
|
let password: Password = db.get_password_for_user(&user).await?.into();
|
||||||
Ok(if password.check(supplied_password)? {
|
Ok(if password.check(supplied_password)? {
|
||||||
Some(AuthenticatedUser { user })
|
Some(AuthenticatedUser(user))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn check_if_user_is_admin(
|
||||||
|
db: &Database,
|
||||||
|
user: &AuthenticatedUser,
|
||||||
|
) -> Result<Option<AuthenticatedAdminUser>, db::Error> {
|
||||||
|
if db.is_user_admin(user).await? {
|
||||||
|
Ok(Some(AuthenticatedAdminUser(user.0.clone())))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -11,6 +11,7 @@ pub enum Error {
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub database_url: String,
|
pub database_url: String,
|
||||||
pub static_file_path: String,
|
pub static_file_path: String,
|
||||||
|
pub hmac_secret: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_config_string(variable: &str) -> Result<String, Error> {
|
fn get_config_string(variable: &str) -> Result<String, Error> {
|
||||||
|
|
@ -22,5 +23,6 @@ pub fn get_config() -> Result<Config, Error> {
|
||||||
Ok(Config {
|
Ok(Config {
|
||||||
database_url: get_config_string("DATABASE_URL")?,
|
database_url: get_config_string("DATABASE_URL")?,
|
||||||
static_file_path: get_config_string("STATIC_FILE_PATH")?,
|
static_file_path: get_config_string("STATIC_FILE_PATH")?,
|
||||||
|
hmac_secret: get_config_string("HMAC_SECRET")?.into_bytes(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
142
src/db/mod.rs
142
src/db/mod.rs
|
|
@ -7,30 +7,83 @@ mod migrations;
|
||||||
|
|
||||||
use {
|
use {
|
||||||
deadpool_postgres::{CreatePoolError, Pool, Runtime},
|
deadpool_postgres::{CreatePoolError, Pool, Runtime},
|
||||||
|
serde::{Deserialize, Serialize},
|
||||||
|
std::ops::Deref,
|
||||||
tokio_postgres::NoTls,
|
tokio_postgres::NoTls,
|
||||||
std::ops::Deref
|
tracing::error,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Errors that may occur during module initialization
|
/// Errors that may occur during module initialization
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(Debug)]
|
||||||
pub enum InitialisationError {
|
pub enum InitialisationError {
|
||||||
#[error("Could not initialize DB connection pool: {}", .0.to_string())]
|
ConnectionPoolError(CreatePoolError),
|
||||||
ConnectionPoolError(#[from] CreatePoolError),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for InitialisationError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
InitialisationError::ConnectionPoolError(e) => {
|
||||||
|
write!(f, "Could not initialise DB connection pool: {}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for InitialisationError {}
|
||||||
|
|
||||||
|
impl From<CreatePoolError> for InitialisationError {
|
||||||
|
fn from(value: CreatePoolError) -> Self {
|
||||||
|
InitialisationError::ConnectionPoolError(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type InitialisationResult<T> = std::result::Result<T, InitialisationError>;
|
||||||
|
|
||||||
/// Errors that may occur during normal app operation
|
/// Errors that may occur during normal app operation
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
#[error("{}", .0.to_string())]
|
Pool(deadpool_postgres::PoolError),
|
||||||
Pool(#[from] deadpool_postgres::PoolError),
|
Postgres(tokio_postgres::Error),
|
||||||
|
NotAllowed,
|
||||||
#[error("{}", .0.to_string())]
|
|
||||||
Postgres(#[from] tokio_postgres::Error),
|
|
||||||
|
|
||||||
#[error("Not allowed.")]
|
|
||||||
NotAllowed
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Error {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Error::Pool(e) => e.fmt(f),
|
||||||
|
Error::Postgres(e) => e.fmt(f),
|
||||||
|
Error::NotAllowed => write!(f, "Not Allowed"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for Error {}
|
||||||
|
|
||||||
|
impl From<deadpool_postgres::PoolError> for Error {
|
||||||
|
fn from(value: deadpool_postgres::PoolError) -> Self {
|
||||||
|
error!(
|
||||||
|
details = value.to_string(),
|
||||||
|
"Error with deadpool_postgress connection pool"
|
||||||
|
);
|
||||||
|
Self::Pool(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<tokio_postgres::Error> for Error {
|
||||||
|
fn from(value: tokio_postgres::Error) -> Self {
|
||||||
|
error!(
|
||||||
|
details = value
|
||||||
|
.as_db_error()
|
||||||
|
.and_then(|db_error| db_error.detail())
|
||||||
|
.unwrap_or(&value.to_string()),
|
||||||
|
"PostgreSQL error"
|
||||||
|
);
|
||||||
|
Error::Postgres(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
/// Object that manages the database.
|
/// Object that manages the database.
|
||||||
///
|
///
|
||||||
/// All database access happens through this struct.
|
/// All database access happens through this struct.
|
||||||
|
|
@ -39,15 +92,22 @@ pub struct Database {
|
||||||
connection_pool: Pool,
|
connection_pool: Pool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
pub struct UserId(i32);
|
pub struct UserId(i32);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
id: UserId,
|
id: UserId,
|
||||||
pub real_name: String,
|
pub real_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
pub fn get_id(&self) -> UserId {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct PasswordHash(pub String);
|
pub struct PasswordHash(pub String);
|
||||||
|
|
||||||
impl Deref for PasswordHash {
|
impl Deref for PasswordHash {
|
||||||
|
|
@ -60,7 +120,7 @@ impl Deref for PasswordHash {
|
||||||
|
|
||||||
impl Database {
|
impl Database {
|
||||||
/// Create a connection pool and return the [Database].
|
/// Create a connection pool and return the [Database].
|
||||||
pub fn new(connection_url: &str) -> Result<Database, InitialisationError> {
|
pub fn new(connection_url: &str) -> InitialisationResult<Database> {
|
||||||
let mut config = deadpool_postgres::Config::new();
|
let mut config = deadpool_postgres::Config::new();
|
||||||
config.url = Some(connection_url.to_string());
|
config.url = Some(connection_url.to_string());
|
||||||
let pg_pool = config.create_pool(Some(Runtime::Tokio1), NoTls)?;
|
let pg_pool = config.create_pool(Some(Runtime::Tokio1), NoTls)?;
|
||||||
|
|
@ -71,15 +131,16 @@ impl Database {
|
||||||
|
|
||||||
/// Run migrations as needed to ensure the database schema version
|
/// Run migrations as needed to ensure the database schema version
|
||||||
/// match the one used by the current version of the application.
|
/// match the one used by the current version of the application.
|
||||||
pub async fn migrate_to_current_version(&self) -> Result<(), Error> {
|
pub async fn migrate_to_current_version(&self) -> Result<()> {
|
||||||
migrations::migrate_to_current_version(self).await
|
migrations::migrate_to_current_version(self).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_client(&self) -> Result<deadpool_postgres::Client, Error> {
|
async fn get_client(&self) -> Result<deadpool_postgres::Client> {
|
||||||
Ok(self.connection_pool.get().await?)
|
Ok(self.connection_pool.get().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn has_admin_users(&self) -> Result<bool, Error> {
|
#[tracing::instrument]
|
||||||
|
pub async fn has_admin_users(&self) -> Result<bool> {
|
||||||
let client = self.get_client().await?;
|
let client = self.get_client().await?;
|
||||||
Ok(client
|
Ok(client
|
||||||
.query_one("SELECT EXISTS(SELECT 1 FROM admin_users);", &[])
|
.query_one("SELECT EXISTS(SELECT 1 FROM admin_users);", &[])
|
||||||
|
|
@ -87,19 +148,20 @@ impl Database {
|
||||||
.get(0))
|
.get(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
pub async fn create_user(
|
pub async fn create_user(
|
||||||
&self,
|
&self,
|
||||||
real_name: &str,
|
real_name: &str,
|
||||||
email: &str,
|
email: &str,
|
||||||
password: &PasswordHash,
|
password: &PasswordHash,
|
||||||
) -> Result<User, Error> {
|
) -> Result<User> {
|
||||||
let client = self.get_client().await?;
|
let client = self.get_client().await?;
|
||||||
let id = client
|
let id = client
|
||||||
.query_one(
|
.query_one(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO users
|
INSERT INTO users
|
||||||
(real_name, email, password)
|
(real_name, email, password)
|
||||||
VALUES $1, $1, $3, $4
|
VALUES ($1, $2, $3)
|
||||||
RETURNING id;"#,
|
RETURNING id;"#,
|
||||||
&[&real_name, &email, &password.0],
|
&[&real_name, &email, &password.0],
|
||||||
)
|
)
|
||||||
|
|
@ -111,34 +173,56 @@ impl Database {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_password_for_user(&self, user: &User) -> Result<PasswordHash, Error> {
|
#[tracing::instrument]
|
||||||
|
pub async fn get_password_for_user(&self, user: &User) -> Result<PasswordHash> {
|
||||||
let client = self.get_client().await?;
|
let client = self.get_client().await?;
|
||||||
let row = client
|
let row = client
|
||||||
.query_one(
|
.query_one("SELECT password FROM users WHERE id = $1;", &[&user.id.0])
|
||||||
"SELECT password FROM users WHERE id = $1;",
|
|
||||||
&[&user.id.0],
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
Ok(PasswordHash(row.get(0)))
|
Ok(PasswordHash(row.get(0)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
pub async fn create_first_admin_user(
|
pub async fn create_first_admin_user(
|
||||||
&self,
|
&self,
|
||||||
real_name: &str,
|
real_name: &str,
|
||||||
email: &str,
|
email: &str,
|
||||||
password: &PasswordHash,
|
password: &PasswordHash,
|
||||||
) -> Result<User, Error> {
|
) -> Result<User> {
|
||||||
if self.has_admin_users().await? {
|
if self.has_admin_users().await? {
|
||||||
return Err(Error::NotAllowed)
|
return Err(Error::NotAllowed);
|
||||||
}
|
}
|
||||||
let user = self.create_user(real_name, email, password).await?;
|
let user = self.create_user(real_name, email, password).await?;
|
||||||
let client = self.get_client().await?;
|
let client = self.get_client().await?;
|
||||||
client
|
client
|
||||||
.execute("INSERT INTO admin_users (id) VALUES $1", &[&user.id.0])
|
.execute("INSERT INTO admin_users (id) VALUES ($1)", &[&user.id.0])
|
||||||
.await?;
|
.await?;
|
||||||
Ok(User {
|
Ok(User {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
real_name: user.real_name,
|
real_name: user.real_name,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
|
pub async fn is_user_admin(&self, user: &User) -> Result<bool> {
|
||||||
|
Ok(self
|
||||||
|
.get_client()
|
||||||
|
.await?
|
||||||
|
.query_opt("SELECT 1 FROM admin_users WHERE id = $1;", &[&user.id.0])
|
||||||
|
.await?
|
||||||
|
.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
|
pub async fn get_user_with_id(&self, user_id: UserId) -> Result<Option<User>> {
|
||||||
|
Ok(self
|
||||||
|
.get_client()
|
||||||
|
.await?
|
||||||
|
.query_opt("SELECT real_name FROM users WHERE id = $1;", &[&user_id.0])
|
||||||
|
.await?
|
||||||
|
.map(|row| User {
|
||||||
|
id: user_id,
|
||||||
|
real_name: row.get(0),
|
||||||
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
54
src/error.rs
54
src/error.rs
|
|
@ -1,34 +1,66 @@
|
||||||
use {
|
use {
|
||||||
crate::{authentication, db},
|
crate::{authentication, db},
|
||||||
|
askama::Template,
|
||||||
askama_axum::{IntoResponse, Response},
|
askama_axum::{IntoResponse, Response},
|
||||||
|
http::status::StatusCode,
|
||||||
|
tracing::{error, warn},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[allow(clippy::enum_variant_names)]
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
#[error("Database Error: {}", 0.to_string())]
|
#[error("Database Error: {}", 0.to_string())]
|
||||||
DatabaseError(#[from] db::Error),
|
DatabaseError(#[from] db::Error),
|
||||||
|
|
||||||
#[error("Authentication error")]
|
#[error("Authentication error")]
|
||||||
AuthenticationError(#[from] authentication::AuthenticationError)
|
AuthenticationError(#[from] authentication::AuthenticationError),
|
||||||
|
|
||||||
|
#[error("Unexpected error: {}", .0)]
|
||||||
|
Unexpected(String),
|
||||||
|
|
||||||
|
#[error("Forbidden")]
|
||||||
|
Forbidden,
|
||||||
|
|
||||||
|
#[error("JWT Expired")]
|
||||||
|
JwtExpired(db::User),
|
||||||
|
|
||||||
|
#[error("JWT Error")]
|
||||||
|
JwtError(#[from] authentication::JwtError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[template(path = "error.html")]
|
||||||
|
struct ErrorTemplate<'a> {
|
||||||
|
title: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for Error {
|
impl IntoResponse for Error {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
match self {
|
match self {
|
||||||
Error::DatabaseError(db::Error::Pool(pool_error)) => {
|
Error::DatabaseError(_) => {
|
||||||
eprintln!("Database connection pool error: {}", pool_error);
|
error!("Uncaught database error producing HTTP 500.");
|
||||||
todo!()
|
(
|
||||||
}
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
Error::DatabaseError(db::Error::Postgres(postgres_error)) => {
|
ErrorTemplate { title: "Error" },
|
||||||
eprintln!("Database error: {}", postgres_error);
|
)
|
||||||
todo!()
|
.into_response()
|
||||||
}
|
|
||||||
Error::DatabaseError(db::Error::NotAllowed) => {
|
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
Error::AuthenticationError(_) => {
|
Error::AuthenticationError(_) => {
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
|
Error::Unexpected(_) => {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
Error::Forbidden => {
|
||||||
|
(StatusCode::UNAUTHORIZED, "User not authorized.").into_response()
|
||||||
|
}
|
||||||
|
Error::JwtExpired(_) => {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
Error::JwtError(jwt_error) => {
|
||||||
|
warn!(detail = jwt_error.to_string(), "Checking JWT");
|
||||||
|
(StatusCode::UNAUTHORIZED, ErrorTemplate { title: "Error" }).into_response()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
20
src/main.rs
20
src/main.rs
|
|
@ -1,8 +1,12 @@
|
||||||
use {thiserror::Error, tower_http::services::ServeDir};
|
use {
|
||||||
|
thiserror::Error,
|
||||||
|
tower_http::{services::ServeDir, trace::TraceLayer},
|
||||||
|
tracing::Level,
|
||||||
|
};
|
||||||
|
|
||||||
mod admin;
|
mod admin;
|
||||||
mod authentication;
|
|
||||||
mod app;
|
mod app;
|
||||||
|
mod authentication;
|
||||||
mod config;
|
mod config;
|
||||||
mod db;
|
mod db;
|
||||||
mod error;
|
mod error;
|
||||||
|
|
@ -20,6 +24,9 @@ pub enum Error {
|
||||||
|
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
IOError(#[from] std::io::Error),
|
IOError(#[from] std::io::Error),
|
||||||
|
|
||||||
|
#[error("{0}")]
|
||||||
|
TracingError(#[from] tracing::subscriber::SetGlobalDefaultError),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|
@ -36,6 +43,12 @@ fn main() {
|
||||||
async fn locality_main() -> Result<(), Error> {
|
async fn locality_main() -> Result<(), Error> {
|
||||||
let config = get_config()?;
|
let config = get_config()?;
|
||||||
|
|
||||||
|
let subscriber = tracing_subscriber::FmtSubscriber::builder()
|
||||||
|
.pretty()
|
||||||
|
.with_max_level(Level::DEBUG)
|
||||||
|
.finish();
|
||||||
|
tracing::subscriber::set_global_default(subscriber)?;
|
||||||
|
|
||||||
let db_pool = Database::new(&config.database_url)?;
|
let db_pool = Database::new(&config.database_url)?;
|
||||||
|
|
||||||
db_pool.migrate_to_current_version().await.unwrap();
|
db_pool.migrate_to_current_version().await.unwrap();
|
||||||
|
|
@ -43,7 +56,8 @@ async fn locality_main() -> Result<(), Error> {
|
||||||
let app = app::routes()
|
let app = app::routes()
|
||||||
.nest("/admin", admin::routes())
|
.nest("/admin", admin::routes())
|
||||||
.with_state(db_pool)
|
.with_state(db_pool)
|
||||||
.nest_service("/static", ServeDir::new(&config.static_file_path));
|
.nest_service("/static", ServeDir::new(&config.static_file_path))
|
||||||
|
.layer(TraceLayer::new_for_http());
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
|
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
|
||||||
axum::serve(listener, app).await?;
|
axum::serve(listener, app).await?;
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h1>Please create an administrator account:</h1>
|
<h1>Please create an administrator account:</h1>
|
||||||
<form action="/create-initial-admin-user" method="post">>
|
<form action="create_first_admin_user" method="post">>
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
<label for="real_name">Name:</label>
|
<label for="real_name">Name:</label>
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
{% block title %}Locality Administration{% endblock %}
|
{% block title %}Locality Administration{% endblock %}
|
||||||
|
|
||||||
{% block content %}admin{% endblock %}
|
{% block content %}{{admin_user_name}}{% endblock %}
|
||||||
|
|
|
||||||
|
|
@ -5,15 +5,15 @@
|
||||||
<meta name="viewport" content="width=device-width" />
|
<meta name="viewport" content="width=device-width" />
|
||||||
<title>{% block title %}{{title}} - Locality{% endblock %}</title>
|
<title>{% block title %}{{title}} - Locality{% endblock %}</title>
|
||||||
|
|
||||||
<link rel="icon" type="image/png" sizes="32x32" href="static/favicon-32.png">
|
<link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32.png">
|
||||||
<link rel="icon" type="image/png" sizes="16x16" href="static/favicon-16.png">
|
<link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16.png">
|
||||||
<!-- For Google and Android -->
|
<!-- For Google and Android -->
|
||||||
<link rel="icon" type="image/png" sizes="48x48" href="static/favicon-48.png">
|
<link rel="icon" type="image/png" sizes="48x48" href="/static/favicon-48.png">
|
||||||
<link rel="icon" type="image/png" sizes="192x192" href="static/favicon-192.png">
|
<link rel="icon" type="image/png" sizes="192x192" href="/static/favicon-192.png">
|
||||||
<!-- For iPad -->
|
<!-- For iPad -->
|
||||||
<link rel="apple-touch-icon" type="image/png" sizes="167x167" href="static/favicon-167.png">
|
<link rel="apple-touch-icon" type="image/png" sizes="167x167" href="/static/favicon-167.png">
|
||||||
<!-- For iPhone -->
|
<!-- For iPhone -->
|
||||||
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="static/favicon-180.png">
|
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="/static/favicon-180.png">
|
||||||
|
|
||||||
{% block head %}{% endblock %}
|
{% block head %}{% endblock %}
|
||||||
</head>
|
</head>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}Something went wrong. Please try again later.{% endblock %}
|
||||||
Loading…
Reference in New Issue