wip: fix auth example
This commit is contained in:
@@ -25,3 +25,4 @@ sea-orm = { version = "0.12.10", features = [
|
||||
axum-login = "0.15.3"
|
||||
async-trait = "0.1.80"
|
||||
password-auth = "1.0.0"
|
||||
thiserror = "1.0.61"
|
||||
|
||||
@@ -3,8 +3,10 @@ use axum_login::{AuthUser, AuthnBackend, UserId};
|
||||
use password_auth::verify_password;
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, ModelTrait, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use tokio::task;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct UserDatabase {
|
||||
connection: DatabaseConnection,
|
||||
}
|
||||
@@ -51,6 +53,16 @@ impl AuthUser for User {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<entity::user::Model> for User {
|
||||
fn from(value: entity::user::Model) -> Self {
|
||||
User {
|
||||
id: value.id,
|
||||
username: value.username,
|
||||
password: "".to_owned(), // TODO: password field.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This allows us to extract the authentication fields from forms. We use this
|
||||
// to authenticate requests with the backend.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -60,10 +72,32 @@ pub struct Credentials {
|
||||
pub next: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub struct NotFoundError {
|
||||
pub details: String,
|
||||
}
|
||||
|
||||
impl NotFoundError {
|
||||
pub fn new(details: &str) -> Self {
|
||||
NotFoundError {
|
||||
details: details.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NotFoundError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Not Found... Error: {}", self.details)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
DbErr(#[from] sea_orm::DbErr),
|
||||
|
||||
#[error("Not Found: {0}")]
|
||||
NotFound(#[from] NotFoundError),
|
||||
|
||||
#[error(transparent)]
|
||||
TaskJoin(#[from] task::JoinError),
|
||||
@@ -95,14 +129,19 @@ impl AuthnBackend for UserDatabase {
|
||||
}
|
||||
|
||||
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user = entity::User::find_by_id(*user_id)
|
||||
let user_found = entity::User::find_by_id(*user_id)
|
||||
.one(&self.connection)
|
||||
.await?;
|
||||
Ok(user)
|
||||
if let Some(user) = user_found {
|
||||
let rear_user: User = user.into();
|
||||
Ok(Some(rear_user))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We use a type alias for convenience.
|
||||
//
|
||||
// Note that we've supplied our concrete backend here.
|
||||
pub type AuthSession = axum_login::AuthSession<Backend>;
|
||||
pub type AuthSession = axum_login::AuthSession<UserDatabase>;
|
||||
|
||||
Reference in New Issue
Block a user