rear_auth buildup from sqlite example
This commit is contained in:
27
rear_auth/Cargo.toml
Normal file
27
rear_auth/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "rear_auth"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
default-run = "rear_auth"
|
||||
|
||||
[lib]
|
||||
name = "rear_auth"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
entity = { path = "../entity" }
|
||||
rear = { path = "../rear" }
|
||||
anyhow = "1.0.75"
|
||||
axum = "0.7"
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
tokio = { version = "1.32.0", features = ["full"] }
|
||||
log = "0.4.20"
|
||||
serde_json = "1.0.108"
|
||||
sea-orm = { version = "0.12.10", features = [
|
||||
"runtime-tokio-native-tls",
|
||||
"sqlx-postgres",
|
||||
] }
|
||||
axum-login = "0.15.3"
|
||||
async-trait = "0.1.80"
|
||||
password-auth = "1.0.0"
|
||||
1
rear_auth/src/lib.rs
Normal file
1
rear_auth/src/lib.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod users;
|
||||
3
rear_auth/src/main.rs
Normal file
3
rear_auth/src/main.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod users;
|
||||
|
||||
pub fn main() {}
|
||||
108
rear_auth/src/users.rs
Normal file
108
rear_auth/src/users.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use async_trait::async_trait;
|
||||
use axum_login::{AuthUser, AuthnBackend, UserId};
|
||||
use password_auth::verify_password;
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, ModelTrait, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::task;
|
||||
|
||||
struct UserDatabase {
|
||||
connection: DatabaseConnection,
|
||||
}
|
||||
|
||||
impl UserDatabase {
|
||||
pub fn new(connection: DatabaseConnection) -> Self {
|
||||
UserDatabase {
|
||||
connection: connection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct User {
|
||||
id: i64,
|
||||
pub username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
// Here we've implemented `Debug` manually to avoid accidentally logging the
|
||||
// password hash.
|
||||
impl std::fmt::Debug for User {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("User")
|
||||
.field("id", &self.id)
|
||||
.field("username", &self.username)
|
||||
.field("password", &"[redacted]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthUser for User {
|
||||
type Id = i64;
|
||||
|
||||
fn id(&self) -> Self::Id {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn session_auth_hash(&self) -> &[u8] {
|
||||
self.password.as_bytes() // We use the password hash as the auth
|
||||
// hash--what this means
|
||||
// is when the user changes their password the
|
||||
// auth session becomes invalid.
|
||||
}
|
||||
}
|
||||
|
||||
// This allows us to extract the authentication fields from forms. We use this
|
||||
// to authenticate requests with the backend.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Credentials {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub next: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
TaskJoin(#[from] task::JoinError),
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AuthnBackend for UserDatabase {
|
||||
type User = User;
|
||||
type Credentials = Credentials;
|
||||
type Error = Error;
|
||||
|
||||
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?;
|
||||
|
||||
// Verifying the password is blocking and potentially slow, so we'll do so via
|
||||
// `spawn_blocking`.
|
||||
task::spawn_blocking(|| {
|
||||
// We're using password-based authentication--this works by comparing our form
|
||||
// input with an argon2 password hash.
|
||||
Ok(user.filter(|user| verify_password(creds.password, &user.password).is_ok()))
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user = entity::User::find_by_id(*user_id)
|
||||
.one(&self.connection)
|
||||
.await?;
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
||||
// We use a type alias for convenience.
|
||||
//
|
||||
// Note that we've supplied our concrete backend here.
|
||||
pub type AuthSession = axum_login::AuthSession<Backend>;
|
||||
Reference in New Issue
Block a user