laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::collections::HashMap;
use std::fmt;
use std::sync::{Mutex, MutexGuard, PoisonError};

use super::{Email, Error, Provider, Token, User};
use crate::context::{Context, Internals};
use crate::testing::{FakeGuard, FakeStack};

/// Replaces the providers in tests. [`redirect`](super::redirect) records the provider and sends
/// the user to `https://social.fake/{provider}/authorize`, and [`user`](super::user) returns the
/// user given to [`with`](SocialFake::with), without a session or credentials.
///
/// ```no_run
/// use laravel::auth::social::{self, Provider, User};
///
/// let social = social::fake()
///     .with(Provider::GITHUB, User::fake("1234").name("Taylor").verified_email("taylor@example.com"))
///     .with("gitlab", User::fake("42"))
///     .denied(Provider::GOOGLE);
///
/// // Visit the redirect and callback routes...
///
/// social.assert_redirected(Provider::GITHUB);
/// ```
///
/// The fake replaces only registered providers, so a name that no provider is registered under
/// still gets a `404`.
///
/// The fake stays active while you hold the handle. Every request and scope in the application
/// shares it, but other applications don't.
///
/// # Panics
///
/// Panics outside an application context.
#[track_caller]
pub fn fake() -> SocialFake {
    let context = Context::expect("laravel::auth::social::fake()");
    let fakes = Fakes::of(&context);

    SocialFake {
        recording: fakes.push(),
    }
}

/// An active social login fake, with assertions. [`fake()`] returns one.
#[must_use = "bind the social fake to a name, as in `let social = social::fake();`, because dropping it restores real logins, and `let _ = ..` drops it straight away"]
pub struct SocialFake {
    recording: FakeGuard<Recording>,
}

impl SocialFake {
    /// Logs in as this user with the provider. The user's `provider` becomes `provider`.
    pub fn with(self, provider: impl Into<Provider>, user: impl Into<User>) -> Self {
        let provider = provider.into();
        let mut user = user.into();
        user.provider = provider.clone();
        self.recording
            .outcomes()
            .insert(provider, Outcome::User(Box::new(user)));
        self
    }

    /// Makes [`user`](super::user) fail with [`Error::Denied`] for the provider, as when the user
    /// cancels the login.
    pub fn denied(self, provider: impl Into<Provider>) -> Self {
        self.recording.outcomes().insert(provider.into(), Outcome::Denied);
        self
    }

    /// Asserts that [`redirect`](super::redirect) sent the user to the provider.
    ///
    /// # Panics
    ///
    /// Panics when no redirect went to the provider.
    #[track_caller]
    pub fn assert_redirected(&self, provider: impl Into<Provider>) {
        let provider = provider.into();
        let redirects = self
            .recording
            .redirects
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();

        assert!(
            redirects.contains(&provider),
            "expected a redirect to `{provider}`, but the redirects went to {redirects:?}"
        );
    }
}

impl fmt::Debug for SocialFake {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SocialFake")
            .field("recording", &*self.recording)
            .finish()
    }
}

/// A test user for [`SocialFake::with`]. [`User::fake`] creates one.
#[derive(Debug, Clone)]
#[must_use]
pub struct FakeUser(User);

impl User {
    /// Creates a test user with this ID, for [`SocialFake::with`]. Its access token is
    /// `fake-token`. It has no name or email until [`FakeUser::name`],
    /// [`FakeUser::verified_email`], or [`FakeUser::unverified_email`] adds them, and its `raw`
    /// profile is `null` until [`FakeUser::raw`] sets it.
    pub fn fake(id: impl Into<String>) -> FakeUser {
        FakeUser(Self {
            provider: Provider::GOOGLE,
            id: id.into(),
            name: None,
            nickname: None,
            email: None,
            avatar: None,
            token: Token {
                access: "fake-token".to_owned(),
                refresh: None,
                expires_at: None,
                scopes: Vec::new(),
            },
            raw: serde_json::Value::Null,
        })
    }
}

impl FakeUser {
    /// Gives the test user a name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.0.name = Some(name.into());
        self
    }

    /// Gives the test user the provider's raw profile, such as a Google ID token's claims, for
    /// code that reads [`User::raw`].
    pub fn raw(mut self, raw: serde_json::Value) -> Self {
        self.0.raw = raw;
        self
    }

    /// Gives the test user an email address that the provider verified.
    pub fn verified_email(mut self, address: impl Into<String>) -> Self {
        self.0.email = Some(Email {
            address: address.into(),
            verified: true,
        });
        self
    }

    /// Gives the test user an email address that the provider didn't verify.
    pub fn unverified_email(mut self, address: impl Into<String>) -> Self {
        self.0.email = Some(Email {
            address: address.into(),
            verified: false,
        });
        self
    }
}

impl From<FakeUser> for User {
    fn from(user: FakeUser) -> Self {
        user.0
    }
}

/// The application's active fakes.
#[derive(Debug, Default)]
pub(crate) struct Fakes(FakeStack<Recording>);

impl std::ops::Deref for Fakes {
    type Target = FakeStack<Recording>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Fakes {
    pub(super) fn of(context: &Context) -> &Self {
        context.part()
    }
}

#[derive(Debug, Default)]
pub(crate) struct Recording {
    outcomes: Mutex<HashMap<Provider, Outcome>>,
    redirects: Mutex<Vec<Provider>>,
}

#[derive(Debug, Clone)]
enum Outcome {
    User(Box<User>),
    Denied,
}

impl Recording {
    pub(super) fn record_redirect(&self, provider: Provider) {
        self.redirects
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(provider);
    }

    pub(super) fn user(&self, provider: &Provider) -> Result<User, Error> {
        let outcome = self.outcomes().get(provider).cloned();

        match outcome {
            Some(Outcome::User(user)) => Ok(*user),
            Some(Outcome::Denied) => Err(Error::Denied),
            None => panic!(
                "`social::fake()` has no user for `{provider}`; add one with `.with(\"{provider}\", User::fake(\"1\"))`"
            ),
        }
    }

    fn outcomes(&self) -> MutexGuard<'_, HashMap<Provider, Outcome>> {
        self.outcomes.lock().unwrap_or_else(PoisonError::into_inner)
    }
}