laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use axum::body::Body;
use axum::extract::FromRequestParts;
use http::request::Parts;
use sha1::{Digest, Sha1};
use subtle::ConstantTimeEq;

use super::{Auth, MustVerifyEmail, Pages, Provider, Registry};
use crate::error::{Error, Result};
use crate::http::Request;
use crate::mail::{self, Address, Mailable, Message};
use crate::routing::signed::temporary_signed_route_to;
use crate::view::{data, view};

/// How long a verification link works.
const LIFETIME: Duration = Duration::from_secs(60 * 60);

/// The error for a verification link that was sent to another user, or to an address the
/// logged-in user no longer has. [`EmailVerification::verify`] fails with this error and a `403`.
///
/// You may render it to offer a new link, as you would for an
/// [`InvalidSignature`](crate::url::InvalidSignature):
///
/// ```no_run
/// use laravel::auth::InvalidVerificationLink;
///
/// laravel::Application::configure().with_errors(|errors, _| {
///     errors.render(|_: &InvalidVerificationLink, _request, status| {
///         Some((status, "This link isn't for your current email address. Please request a new one."))
///     });
/// });
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("This verification link is invalid.")]
pub struct InvalidVerificationLink;

/// Email verification for users of type `U`. It sends verification links and verifies email
/// addresses with them.
///
/// Take `EmailVerification` as a handler argument on routes in the `web` group, where the session
/// guard logs in users of type `U`:
///
/// ```no_run
/// # mod app {
/// # use laravel::auth::{Authenticatable, MustVerifyEmail};
/// # use laravel::hash::PasswordHash;
/// # use laravel::mail::Address;
/// # #[derive(Clone, Authenticatable, MustVerifyEmail)]
/// # pub struct User {
/// #     pub id: u64,
/// #     pub email: String,
/// #     pub email_verified_at: Option<laravel::time::Timestamp>,
/// #     pub password: Option<PasswordHash>,
/// #     pub remember_token: Option<laravel::auth::RememberToken>,
/// # }
/// # impl From<&User> for Address { fn from(user: &User) -> Self { Address::new(&user.email) } }
/// # }
/// # mod dashboard { pub async fn show() {} }
/// # use app::*;
/// use laravel::auth::{Authenticated, EmailVerification};
/// use laravel::prelude::*;
///
/// async fn resend(user: Authenticated<User>, verification: EmailVerification<User>) -> laravel::Result<Redirect> {
///     verification.send_link(&user).await?;
///
///     Ok(Redirect::back().with("status", "We've sent you a new verification link."))
/// }
///
/// #[laravel::auth::page(verify_email)]
/// async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {
///     verification.verify().await?;
///
///     Ok(Redirect::intended(dashboard::show, ()))
/// }
/// ```
///
/// A link is a temporary signed URL that works for 60 minutes, and only while the user still has
/// the email address it was sent to. Links aren't stored, so sending a new link doesn't invalidate
/// earlier ones.
pub struct EmailVerification<U: MustVerifyEmail> {
    auth: Auth<U>,
    provider: Arc<dyn Provider<U>>,
    request: Request,
    pages: Pages,
}

impl<U: MustVerifyEmail> fmt::Debug for EmailVerification<U> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EmailVerification").finish_non_exhaustive()
    }
}

impl<U: MustVerifyEmail, S: Send + Sync> FromRequestParts<S> for EmailVerification<U> {
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
        let services = super::services(&parts.extensions)?.clone();
        let registry = services.resolve::<Registry>().await?;
        let definition = registry.definition::<U>()?;

        Ok(Self {
            auth: Auth::of(parts).await?,
            provider: (definition.provider)(services).await?,
            request: Request::from_http(http::Request::from_parts(parts.clone(), Body::empty())),
            pages: registry.pages,
        })
    }
}

impl<U: MustVerifyEmail> EmailVerification<U> {
    /// Emails the user a link that verifies their email address. Does nothing for a user who has
    /// already verified their address.
    ///
    /// `send_link` queues a [`VerificationEmail`] with the user's [`url`](Self::url) to
    /// `mail::to(&user)`, so `&U` must convert into an [`Address`].
    ///
    /// # Errors
    ///
    /// Fails when [`url`](Self::url) fails, or when the email can't be rendered or queued.
    pub async fn send_link(&self, user: &U) -> Result<()>
    where
        for<'a> &'a U: Into<Address>,
    {
        if user.has_verified_email() {
            return Ok(());
        }

        mail::to(user).queue(VerificationEmail { url: self.url(user)? }).await
    }

    /// Returns the link that verifies the user's email address, for an email of your own. The
    /// link opens the handler marked
    /// [`#[laravel::auth::page(verify_email)]`](macro@super::page) and works for 60 minutes. It
    /// fills the route's `{id}` and `{hash}` parameters with the user's ID and a hash of their
    /// email address.
    ///
    /// # Errors
    ///
    /// Fails when no handler is marked `#[laravel::auth::page(verify_email)]`, when there's no
    /// `APP_KEY` to sign the link with, or when the user's ID can't be serialized.
    pub fn url(&self, user: &U) -> Result<String> {
        let page = self.pages.verify_email.ok_or_else(|| {
            crate::error::fail(
                "verification links need a page to open: mark the handler that verifies emails \
                 `#[laravel::auth::page(verify_email)]`",
            )
        })?;

        temporary_signed_route_to(
            page.handler,
            LIFETIME,
            [
                ("id", super::id_string(&user.auth_id())?),
                ("hash", hash(user.email_for_verification())),
            ],
        )
    }

    /// Verifies the logged-in user's email address with the link that the request opened, and
    /// returns the user. A user who already verified their email gets the same result, so opening
    /// a link twice works.
    ///
    /// `verify` checks that the link is signed and hasn't expired, and that it was sent to the
    /// logged-in user at their current address. It then records the verification with the
    /// provider's [`mark_email_as_verified`](super::UserProvider::mark_email_as_verified).
    ///
    /// # Errors
    ///
    /// A guest gets the response that [`Authenticate`](super::Authenticate) gives one, so the
    /// guest returns to the link after logging in. A link that was changed, never signed, or has
    /// expired fails with a `403` [`InvalidSignature`](crate::url::InvalidSignature). A link for
    /// another user, or for an address the user no longer has, fails with a `403`
    /// [`InvalidVerificationLink`]. Also fails when the provider fails.
    pub async fn verify(&self) -> Result<U> {
        let Some(user) = self.auth.user().await? else {
            return Err(super::unauthenticated());
        };
        self.request
            .validate_signature(&[])
            .map_err(|invalid| Error::new(403, invalid))?;

        let id = super::id_string(&user.auth_id())?;
        let hash = hash(user.email_for_verification());
        let matches = |name, expected: &str| {
            let given = self.request.route(name).unwrap_or_default();
            bool::from(given.as_bytes().ct_eq(expected.as_bytes()))
        };
        if !(matches("id", &id) & matches("hash", &hash)) {
            return Err(Error::new(403, InvalidVerificationLink));
        }
        if user.has_verified_email() {
            return Ok(user);
        }

        self.provider.mark_email_as_verified(&user).await?;
        self.provider
            .find(&user.auth_id())
            .await?
            .ok_or_else(super::unauthenticated)
    }
}

/// The email that [`EmailVerification::send_link`] queues. It shows a button that opens `url`,
/// and says how long the link works.
///
/// Its view is `laravel::auth.verify-email`. To change it, copy the framework's
/// `resources/views/auth/verify-email.html` to
/// `resources/views/vendor/laravel/auth/verify-email.html` and edit the copy.
#[derive(Debug, Clone)]
pub struct VerificationEmail {
    /// The link that verifies the address, from [`EmailVerification::url`].
    pub url: String,
}

impl Mailable for VerificationEmail {
    fn build(&self) -> Result<Message> {
        let minutes = LIFETIME.as_secs() / 60;

        Ok(Message::new()
            .subject("Verify your email address")
            .view(view("laravel::auth.verify-email", data! { url => self.url, minutes })))
    }
}

/// The `{hash}` in a verification link: the SHA-1 of the email address, in hex. The link's
/// signature already prevents forgery, so the hash only ties the link to the address.
fn hash(email: &str) -> String {
    hex::encode(Sha1::digest(email.as_bytes()))
}