# Recipes

Source: https://keyringauth.com/docs/0.x/rust/recipes

## Introduction

Worked examples of common changes, in Rust. Each follows its [PHP recipe](https://keyringauth.com/docs/0.x/recipes), which explains the reasons, and these are translations: check them against your application before relying on them.

## Locations With stevebauman/location

stevebauman/location is a PHP package. In Rust, a locator of your own implements `LocatesIps` and asks a geolocation API, or reads a local MaxMind database:

```rust
use std::sync::Arc;
use laravel::http::Request;
use laravel::http::client;
use laravel_keyring::location::{Locating, LocatesIps, Location};
use serde_json::{Value, json};

#[derive(Debug)]
struct IpApi;

impl LocatesIps for IpApi {
    fn locate<'a>(&'a self, request: &'a Request) -> Locating<'a> {
        Box::pin(async move {
            let ip = request.ip().to_string();
            let response = client::get(format!("https://ipapi.example/json/{ip}"))
                .timeout(laravel::time::SignedDuration::from_secs(2))
                .await?;

            if !response.successful() {
                return Ok(None);
            }

            let found: Value = response.json()?;
            let mut location = Location::new();
            for (key, field) in [("country", "country_code"), ("region", "region"), ("city", "city")] {
                if let Some(value) = found.get(field).and_then(Value::as_str) {
                    location.insert(key.into(), json!(value));
                }
            }
            for key in ["latitude", "longitude"] {
                if let Some(value) = found.get(key).and_then(Value::as_f64) {
                    location.insert(key.into(), json!(value));
                }
            }

            Ok((!location.is_empty()).then_some(location))
        })
    }
}

config.section_mut::<laravel_keyring::KeyringConfig>().devices.locator = Some(Arc::new(IpApi));
```

`ipapi.example` stands for your provider. Keyring asks once per request, and an error is reported and leaves the location unknown, so give the request a short timeout. The address is `Request::ip()`, so [trust your proxies](https://keyringauth.com/docs/0.x/rust/security#trusted-proxies) first.

## Locations From Cloudflare

```rust
use std::sync::Arc;
use laravel_keyring::location::HeaderLocator;

config.section_mut::<laravel_keyring::KeyringConfig>().devices.locator = Some(Arc::new(HeaderLocator::cloudflare()));
```

> [!WARNING]
> Anyone can send these headers. Only use `HeaderLocator` when every request reaches your application through Cloudflare, and the origin can't be reached directly. The city, region and coordinates only come with the "Add visitor location headers" Managed Transform turned on.

## Emails With Maizzle

Build the templates with Maizzle as the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#emails-with-maizzle) does, into laravel-rust views, then render them from `notifications.mail_using` for the security notices, and the flow emails' methods for the rest:

```rust
use laravel::mail::Message;
use laravel_keyring::notifications::SecurityNotice;

config.section_mut::<laravel_keyring::KeyringConfig>().notifications.mail_using = Some(|notice: &SecurityNotice| {
    Message::new()
        .subject(notice.subject())
        .view(laravel::view::view("emails.keyring.notice", serde_json::json!({
            "intro": notice.intro(),
            "when": notice.when,
            "device": notice.device,
            "ip": notice.ip,
            "actionText": notice.action(),
            "actionUrl": notice.action().and(notice.url.clone()),
            "contact": notice.contact,
        })))
});
```

The view escapes what it prints, as Blade's `{{ }}` does. Check the view's syntax against laravel-rust's view docs.

## SMS Codes

A text message is a code factor of your own, as in [Writing a Code Factor](https://keyringauth.com/docs/0.x/rust/factors#writing-a-code-factor), with laravel-rust's SMS sender:

```rust
use laravel_keyring::KeyringServiceProvider;
use laravel_keyring::codes::{CodeFactor, Input, NewAuthenticator, Recipient, SendsCodes};
use laravel::validation::InvalidInput;

struct TextMessage;

impl SendsCodes<User> for TextMessage {
    async fn deliver(&self, _user: &User, to: &Recipient, code: &str) -> laravel::Result<()> {
        let number = to.secret.as_deref().unwrap_or_default();
        laravel::sms::to(number).send(format!("Your sign-in code is {code}")).await?;

        Ok(())
    }

    async fn new_authenticator(&self, _user: &User, input: &Input) -> laravel::Result<NewAuthenticator> {
        let phone = input.get("phone").and_then(|phone| phone.as_str()).unwrap_or_default().trim();

        if !phone.starts_with('+') || phone.len() > 32 {
            return Err(InvalidInput::new().with("phone", "Enter the number with its country code.").into());
        }

        Ok(NewAuthenticator { secret: Some(phone.to_owned()), ..NewAuthenticator::default() })
    }
}

KeyringServiceProvider::<Users>::new()
    .code_factor(CodeFactor::new("sms", "Text message", TextMessage).length(6).one_per_user());
```

The [PHP recipe](https://keyringauth.com/docs/0.x/recipes#sms-codes) explains what NIST says about codes sent by text, and why a code factor counts as possession. Add an `sms` line to your frontend's factor map, reusing the TOTP component.

## Social Login

See [Single Sign-On](https://keyringauth.com/docs/0.x/rust/sso): turn on `features.sso` and list the providers. To let people sign up with a provider, see [Signing Up With a Provider](https://keyringauth.com/docs/0.x/rust/sso#signing-up-with-a-provider).

## Usernames Instead of Email Addresses

Set `username` to the field your login form sends, and look users up by it in your provider's `find_for_login()`:

```rust
let keyring = config.section_mut::<laravel_keyring::KeyringConfig>();
keyring.username = "username".to_owned();
keyring.email = "email".to_owned();
```

Keep `email` on the address, which registration, resets and email changes read. Answer `CreatesNewUsers::taken()` and `ChangesEmails::taken()` yourself, since the default asks `find_for_login()`, which now looks up usernames: without it, every address looks free. To keep usernames' case, give the provider `normalize_usernames_using()`. See the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#usernames-instead-of-email-addresses).

## Links for Apps on Several Domains

Start emailed links at the tenant's domain with the provider's `link_root_using()`:

```rust
KeyringServiceProvider::<Users>::new().link_root_using(|| current_tenant_url());
```

`current_tenant_url()` is yours. It takes no request, so read the tenant from wherever your application keeps it for the request. Passkeys are bound to one relying party, so list every tenant origin in `webauthn.origins` under one parent domain, as the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#links-for-apps-on-several-domains) explains.

## Storing Less About Requests

`record_ips_using` decides what's kept of an address, in the log, the emails, the sessions and the devices. Rate limits always use the real one:

```rust
config.section_mut::<laravel_keyring::KeyringConfig>().record_ips_using = Some(|_request| None);
```

`None` keeps no address at all. See [What's Stored](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#whats-stored) for keeping part of one.

## Accounts an Admin Approves

Keep unapproved accounts out with `allow_sign_in_when()`, and keep new users signed out after registering with `sign_in_after_registering()`:

```rust
KeyringServiceProvider::<Users>::new()
    .allow_sign_in_when(|user: &User| user.approved_at.is_some())
    .sign_in_after_registering(false);
```

An account it turns away is answered as one that doesn't exist, and a signed-in session of theirs is signed out with every other. When an admin revokes approval, sign the account out too, with `Sessions::<Users>::sign_out_everywhere(&user, None)`. See the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#accounts-an-admin-approves).

## An App Whose Every Page Needs AAL2

Require a second factor of everyone with `RequireEnrollment`, and AAL2 on the signed-in pages with `RequireAssurance`:

```rust
use laravel_keyring::http::{RequireAssurance, RequireEnrollment};

laravel::Application::configure()
    .with_config(|config, _| {
        config.section_mut::<laravel_keyring::KeyringConfig>().enrollment_url = Some("/settings/security".to_owned());
    })
    .with_middleware(|middleware, _| {
        middleware.web(|web| {
            web.append(RequireEnrollment::<Users>::new());
        });
    })
    .with_routing(|routing, _| {
        routing.web(|route| {
            route.middleware(RequireAssurance::<Users>::aal2()).group(|route| {
                route.get("/dashboard", dashboard);
            });
        });
    });
```

Keep the enrollment page and the routes it calls out of `RequireAssurance`, since a user without a second factor can't reach AAL2. A browser impersonating someone gets a `403` on every `RequireAssurance` route, so keep pages support staff need outside it. See the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#an-app-whose-every-page-needs-aal2).
