# Recipes

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

## Introduction

Worked examples of common changes, in Go. 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. `models.User` stands for your user type.

## Locations With stevebauman/location

stevebauman/location is a PHP package. In Go, a locator of your own implements `keyring.LocatesIPs` and asks a geolocation API with Laravel Go's HTTP client, or reads a local MaxMind database:

```go
type IPAPI struct{}

type ipAPIAnswer struct {
    CountryCode string   `json:"country_code"`
    Region      string   `json:"region"`
    City        string   `json:"city"`
    Latitude    *float64 `json:"latitude"`
    Longitude   *float64 `json:"longitude"`
}

func (IPAPI) Locate(r *web.Request) (keyring.Location, error) {
    found, err := httpclient.Timeout(2*time.Second).GetJSON[ipAPIAnswer](r, "https://ipapi.example/json/"+r.IP())
    if err != nil {
        return nil, err
    }

    var location keyring.Location
    for _, field := range []keyring.MetaField{
        {Key: "country", Value: found.CountryCode},
        {Key: "region", Value: found.Region},
        {Key: "city", Value: found.City},
    } {
        if field.Value != "" {
            location = append(location, field)
        }
    }
    if found.Latitude != nil && found.Longitude != nil {
        location = append(location,
            keyring.MetaField{Key: "latitude", Value: *found.Latitude},
            keyring.MetaField{Key: "longitude", Value: *found.Longitude})
    }

    return location, nil
}

cfg.Devices.Locator = 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. An empty location is unknown too. The address is `r.IP()`, so [trust your proxies](https://keyringauth.com/docs/0.x/go/security#trusted-proxies) first.

## Locations From Cloudflare

```go
cfg.Devices.Locator = keyring.CloudflareLocator()
```

> [!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.

For another proxy, list its headers by field: `keyring.HeaderLocator{Headers: []keyring.LocationHeader{{Field: "country", Header: "X-Country-Code"}}}`.

## 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 Go views under `resources/views`, then send them from `Notifications.Mail` for the security notices, and `Notifications.AccountMail` for the emails a flow needs:

```go
cfg.Notifications.Mail = func(ctx context.Context, notice keyring.SecurityNotice) mail.Mailable {
    data := map[string]any{
        "intro":      notice.Intro(),
        "when":       notice.When,
        "device":     notice.Device,
        "ip":         notice.IP,
        "actionText": notice.Action(),
        "contact":    notice.Contact,
    }
    if notice.Action() != "" {
        data["actionUrl"] = notice.URL
    }

    return mail.Message{
        Subject: notice.Subject(),
        View:    "emails.keyring.notice",
        Data:    data,
    }
}
```

Laravel Go makes the plain-text part from the rendered view unless you set `Text` or `TextView`. Its views escape what they print, as Blade's `{{ }}` does. Check the template syntax against Laravel Go'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/go/factors#writing-a-code-factor), sent with Laravel Go's `sms` package:

```go
type TextMessage struct{}

func (TextMessage) Deliver(ctx context.Context, _ *models.User, to keyring.CodeRecipient, code string) error {
    if to.Secret == nil {
        return nil
    }

    return sms.To(*to.Secret).Send(ctx, "Your sign-in code is "+code)
}

func (TextMessage) NewAuthenticator(_ context.Context, _ *models.User, input map[string]any) (keyring.NewCodeAuthenticator, error) {
    phone, _ := input["phone"].(string)
    phone = strings.TrimSpace(phone)

    if !strings.HasPrefix(phone, "+") || len(phone) > 32 {
        return keyring.NewCodeAuthenticator{}, &web.InputError{Fields: validation.Errors{
            {Field: "phone", Messages: []string{"Enter the number with its country code."}},
        }}
    }

    return keyring.NewCodeAuthenticator{Secret: &phone}, nil
}

k := keyring.New[models.User]().AddCodeFactor(keyring.CodeFactor[models.User]{
    Key:         "sms",
    DefaultName: "Text message",
    Sender:      TextMessage{},
    Length:      6,
    OnePerUser:  true,
})
```

The number is kept encrypted, as a sign-in method's secret is. 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. Codes an enrollment sends are limited per account only, and whoever is signed in chooses the number, so with a paid sender limit by number and IP address in `Deliver` too. 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/go/sso): turn on `Factors.SingleSignOn` and list the providers in `SSO.Providers`. To let people sign up with a provider, see [Signing Up With a Provider](https://keyringauth.com/docs/0.x/go/sso#signing-up-with-a-provider).

## Usernames Instead of Email Addresses

Set `Username` to the field your login form sends. Without `FindUsersWith`, Keyring looks users up with `auth.ModelUsers` on that column. With your own `auth.Users`, look them up by it in `FindForLogin`:

```go
cfg.Username = "username"
cfg.Email = "email"
```

Keep `Email` on the address, which registration, resets and email changes read. Keyring looks for taken addresses in that column of the user model's table, so registration and email changes still find them. An action that implements `TakenAddresses` answers instead. Keyring trims the spaces around a typed username and lowercases it before looking it up, as the PHP package's default does, and there's no `normalizeUsernamesUsing()` yet, so store usernames in lower case. 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 `Config.LinkRoot`:

```go
cfg.LinkRoot = func(ctx context.Context) string {
    return currentTenantURL(ctx)
}
```

`currentTenantURL` is yours. It's given the request's context, so read the tenant from wherever your application keeps it for the request, never from the `Host` header. 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

Not available yet: there's no `recordIpsUsing()`, so the log, the emails, the sessions and the devices keep `r.IP()`. See [What's Stored](https://keyringauth.com/docs/0.x/go/security-log-and-emails#whats-stored).

## Accounts an Admin Approves

Keep unapproved accounts out with `AllowSignInWhen`:

```go
k := keyring.New[models.User]().
    AllowSignInWhen(func(ctx context.Context, user *models.User) bool {
        return user.ApprovedAt != nil
    })
```

It's asked on every signed-in request, so answer from the user you're given rather than with a query. An account it turns away is answered as one that doesn't exist, by every way in. A browser already signed in is signed out on its next request, which also ends every other session the account has, with their "remember me" cookies and trusted devices. A new user registered where registration hides who has an account isn't signed in until they've verified their address, and this keeps them out after that too. See the [PHP recipe](https://keyringauth.com/docs/0.x/recipes#accounts-an-admin-approves).

When an admin revokes approval, sign the account out too, with `go run . keyring:sign-out` and the user's ID. There's no public way yet to do it from your own code, as the PHP package's `Sessions::signOutEverywhere()` does. See [For Administrators](https://keyringauth.com/docs/0.x/go/devices-and-sessions#for-administrators).

## An App Whose Every Page Needs AAL2

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

```go
laravel.Options{
    Packages: []laravel.Package{
        keyring.New[models.User](func(cfg *keyring.Config) {
            cfg.EnrollmentURL = "/settings/security"
        }),
    },
    Middleware: func(m *laravel.Middleware, _ *config.Config) {
        m.Web.Append(keyring.RequireEnrollment[models.User]{})
    },
    Routes: laravel.Routes{
        Web: func(route *routing.Router, _ *config.Config) {
            route.Middleware(keyring.RequireAssurance[models.User]{}).Group(func(route *routing.Router) {
                route.Get("/dashboard", dashboard)
            })
        },
    },
}
```

`RequireEnrollment` lets guests, Keyring's own routes and `EnrollmentURL`'s page through. Keep the enrollment page and the routes it calls out of `RequireAssurance`, since a user without a second factor can't reach AAL2. Laravel Go doesn't tell a middleware what else a route runs, so where a route has both, give `RequireEnrollment` the same options as its `RequireAssurance`. 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).
