laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! The user provider for a model that derives `Authenticatable`.

use std::any::type_name;
use std::fmt;
use std::marker::PhantomData;
use std::panic::Location;
use std::sync::Arc;

use super::Changes;
use super::Model;
use super::query::{__query, key_is, query_of};
use super::save;
use super::write::key_of;
use crate::Result;
use crate::auth::__private::DerivedAuthenticatable;
use crate::auth::{Authenticatable, UserProvider};
use crate::container::Container;
use crate::db::{Builder, Source, col};
use crate::hash::PasswordHash;

/// The [`UserProvider`] for a model that derives [`Authenticatable`](trait@Authenticatable).
///
/// The session guard uses the model's queries to find users. Register the provider in
/// `with_auth`:
///
/// ```no_run
/// use laravel::auth::{Authenticatable, RememberToken};
/// use laravel::hash::PasswordHash;
/// use laravel::model::{self, model};
///
/// #[model]
/// #[derive(Authenticatable)]
/// pub struct User {
///     pub id: i64,
///     pub email: String,
///     #[serde(skip)]
///     pub password: PasswordHash,
///     #[serde(skip)]
///     pub remember_token: Option<RememberToken>,
/// }
///
/// laravel::Application::configure().with_auth(|auth, _| {
///     auth.session::<model::Users<User>>();
/// });
/// ```
///
/// The provider finds a logged-in user by the model's key. It finds a user who is logging in by
/// the `email` field, or by the field marked `#[auth(username)]`. A model with neither field
/// doesn't compile:
///
/// ```compile_fail,E0080
/// # use laravel::auth::{Authenticatable, RememberToken};
/// # use laravel::hash::PasswordHash;
/// # use laravel::model::{self, model};
/// #[model]
/// #[derive(Authenticatable)]
/// pub struct User {
///     pub id: i64,
///     pub username: String,
///     #[serde(skip)]
///     pub password: PasswordHash,
///     #[serde(skip)]
///     pub remember_token: Option<RememberToken>,
/// }
///
/// laravel::Application::configure().with_auth(|auth, _| {
///     auth.session::<model::Users<User>>();
/// });
/// ```
///
/// When the provider saves a new password or an email verification, it updates the model the same
/// way `update!` does. It runs the `updating` hook, sets `updated_at`, and dispatches
/// [`Updated`](super::Updated). When it saves a new remember token, it writes only the token's
/// column. It runs no hook, dispatches no event, and leaves `updated_at` unchanged.
///
/// The provider doesn't restrict which users may log in. To keep some users out, such as
/// suspended accounts, implement [`UserProvider`] for your own service using the model's queries.
pub struct Users<M>(PhantomData<fn() -> M>);

impl<M> fmt::Debug for Users<M> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Users<{}>", type_name::<M>())
    }
}

impl<M> UserProvider for Users<M>
where
    M: Model + Authenticatable<Id = <M as Model>::Key> + DerivedAuthenticatable,
{
    type User = M;

    async fn find(&self, id: &M::Key) -> Result<Option<M>> {
        __query::<M>().find(id.clone()).await
    }

    fn __id_column() -> &'static str {
        M::META.key.name()
    }

    async fn find_for_login(&self, login: &str) -> Result<Option<M>> {
        let field = const {
            match M::USERNAME {
                Some(field) => field,
                None => panic!(
                    "`model::Users` finds users by their username: add an `email` field, or mark the username field \
                     with `#[auth(username)]`"
                ),
            }
        };
        let Some(column) = M::META.columns.iter().find(|column| column.field == field) else {
            return Err(crate::error::fail(format!(
                "`{}`'s username field, `{field}`, isn't a column",
                M::META.name
            )));
        };

        __query::<M>()
            .filter(col(format!("{}.{}", M::META.table, column.name)).eq(login.to_owned()))
            .first()
            .await
    }

    async fn update_password(&self, user: &M, password: &PasswordHash) -> Result<()> {
        let mut updated = user.clone();
        updated.set_password(password.clone());

        save(&mut updated, key_of(user), user.clone(), Vec::new(), Location::caller()).await
    }

    async fn update_remember_token(&self, user: &M, token: &str) -> Result<()> {
        let mut updated = user.clone();
        updated.set_remember_token(token.to_owned());
        let values = Changes::between(user.clone(), updated).values();

        Builder::<()>::new(query_of(user).on, Source::from(M::META.table))
            .filter(key_is::<M>(key_of(user)))
            .update(values)
            .await?;
        Ok(())
    }

    async fn mark_email_as_verified(&self, user: &M) -> Result<()> {
        let Some(verify) = crate::auth::verify_of::<M>() else {
            return Err(crate::error::fail(format!(
                "`{}` doesn't derive `MustVerifyEmail`",
                type_name::<M>()
            )));
        };
        let mut updated = user.clone();
        verify(&mut updated);

        save(&mut updated, key_of(user), user.clone(), Vec::new(), Location::caller()).await
    }

    fn __resolve(_: Container) -> impl Future<Output = Result<Arc<Self>>> + Send {
        std::future::ready(Ok(Arc::new(Self(PhantomData))))
    }
}