# Magic links and email codes
Source: https://sovaria.in/docs/magic-links

Passwordless sign-in for existing users: one email carries a sign-in link and a 6-digit code, so people can sign in on the device that has the email or type the code on another.

A magic link signs a user in without a password. Each request sends **one email** with two ways in: a **link** that opens your app already signed in, and a **6-digit code** for when the email is read on a different device (a laptop) from the one signing in (a phone).

Magic links work for **people who already have an account** in the project. They never create one: if no account matches the address, nothing is sent, and the request still answers `{"status": "sent"}` so nobody can learn which addresses are registered. Create accounts first with [sign-up](https://sovaria.in/docs/email-and-password) or [Social sign-in](https://sovaria.in/docs/social-sign-in), or add people yourself with **Invite user** on the console’s **Users** page, which can email them a magic link straight away.

## Turn on magic links

1. **Enable the provider** — In the console, open **Users › Sign in / Providers** and turn on **Magic link**. While it is off, sending a link answers `403`.
2. **Set where links land** — Under **Users › URL configuration**, set your **Site URL** (for example `https://app.example.com`) and add any other address a link may open as a **Redirect URL**, including app links such as `myapp://auth-callback`.
3. **Send from your own domain (recommended)** — Sovaria sends auth email for you, but production apps should use their own provider so mail comes from your domain and isn't shared with others ([Email relays (SMTP)](https://sovaria.in/docs/integration-email-providers)).

## Send the email

Ask for a link with the user's email. `redirectTo` is where the link opens; it must be your Site URL, a path under it, or one of your Redirect URLs. Anything else is ignored and the link opens your Site URL.

JavaScript:
```js
await sovaria.auth.sendMagicLink('ada@example.com', {
  redirectTo: 'https://app.example.com/welcome',
})
```

Dart:
```dart
await sovaria.auth.sendMagicLink('ada@example.com',
    redirectTo: 'com.example.app://auth-callback');
```

Swift:
```swift
try await sovaria.auth.sendMagicLink("ada@example.com",
                                     redirectTo: "com.example.app://auth-callback")
```

Kotlin:
```kotlin
sovaria.auth.sendMagicLink("ada@example.com", redirectTo = "com.example.app://auth-callback")
```

Python:
```python
await sovaria.send_magic_link("ada@example.com", redirect_to="https://app.example.com/welcome")
```

cURL:
```bash
curl -X POST "https://<project-ref>.sovarias.in/api/v1/auth/magic-link/send" \
  -H "apikey: $SOVARIA_ANON_KEY" -H "Content-Type: application/json" \
  -d '{"email": "ada@example.com", "redirect_to": "https://app.example.com/welcome",
       "org_id": "<org-id>", "project_id": "<project-id>"}'
```

> **Same answer for every address:** The response is always `{"status": "sent"}`, whether or not the address has an account, whether the account is disabled, and even if delivery failed. Show the same message to everyone: “If an account exists for that address, we’ve sent a sign-in link.”

## Sign in with the link

The link opens your `redirectTo` with `?token=…&type=magiclink` added. Hand the URL to the SDK on that page: it exchanges the token for a session and signs the user in.

JavaScript:
```js
// On the page the link opens (for example /welcome)
const result = await sovaria.auth.handleEmailLink()   // reads window.location
if (result?.type === 'magiclink') {
  router.replace('/dashboard')                         // signed in
}
```

Dart:
```dart
// app_links delivers the URL the email opened
AppLinks().uriLinkStream.listen((uri) => sovaria.auth.handleDeepLink(uri));
```

Swift:
```swift
.onOpenURL { url in
  guard let token = URLComponents(url: url, resolvingAgainstBaseURL: false)?
    .queryItems?.first(where: { $0.name == "token" })?.value else { return }
  Task { _ = try await sovaria.auth.verifyMagicLink(token) }
}
```

Kotlin:
```kotlin
override fun onNewIntent(intent: Intent) {
  super.onNewIntent(intent)
  val token = intent.data?.getQueryParameter("token") ?: return
  lifecycleScope.launch { sovaria.auth.verifyMagicLink(token) }
}
```

Python:
```python
session = await sovaria.verify_magic_link(token)   # token from the ?token= query parameter
```

> **Links work on another device — and what that means:** A magic link opened on a different device or browser than the one that asked for it still signs in (that is on purpose: people read mail on their phone). The trade-off is that a link someone else asked for — for **their** account — also signs in whoever opens it, so an attacker could send you a link to their own account (login CSRF). Sovaria limits this: every link works **once** (a second use, even at the same moment, is refused), expires after 15 minutes by default (at most 60), and in the browser `handleEmailLink()` refuses a link for a different account than the one already signed in (`error: 'ACCOUNT_SWITCH_REFUSED'`, its session is ended at once) unless you pass `{ allowAccountSwitch: true }` after asking. Apps that start links with PKCE (mobile, `redirectTo` an app scheme) are bound to that app: a link without that app's verifier is refused (`PKCE_NOT_EXPECTED`). Show the signed-in email after any link sign-in so people notice an account they didn't expect.

### Links that open a mobile app

A link that opens an app (a custom scheme such as `myapp://`, or a registered universal or app link) could be caught by another app on the same phone. Sovaria therefore binds those links to the app that asked for them with **PKCE**: the request carries a `code_challenge`, and only the app holding the matching `code_verifier` can complete the sign-in. The SDKs do this for you whenever `redirectTo` is an app link. Calling the HTTP API yourself, send `code_challenge` (S256) when sending and `code_verifier` when verifying, or you get `400 PKCE_REQUIRED`. See [Sign-in for mobile apps](https://sovaria.in/docs/mobile-auth).

## Sign in with the code

The same email shows a 6-digit code. Offer a code field next to “Check your email” so people can type it where they are signing in. Spaces are ignored.

JavaScript:
```js
await sovaria.auth.verifyEmailCode('ada@example.com', '482913')
```

Dart:
```dart
await sovaria.auth.verifyEmailCode(email: 'ada@example.com', code: '482913');
```

Swift:
```swift
try await sovaria.auth.verifyEmailCode(email: "ada@example.com", code: "482913")
```

Kotlin:
```kotlin
sovaria.auth.verifyEmailCode("ada@example.com", "482913")
```

cURL:
```bash
curl -X POST "https://<project-ref>.sovarias.in/api/v1/auth/magic-link/verify-code" \
  -H "apikey: $SOVARIA_ANON_KEY" -H "Content-Type: application/json" \
  -d '{"email": "ada@example.com", "code": "482913", "org_id": "<org-id>", "project_id": "<project-id>"}'
```

## What happens when it succeeds

- The user gets a normal session: an access token and a refresh token, kept and refreshed by the SDK like any other sign-in ([Sessions and tokens](https://sovaria.in/docs/sessions-and-tokens)).
- Their email address is marked **confirmed**, because only the inbox owner could have used the link or code.
- If the user has two-factor authentication, the response is an MFA challenge instead of a session: ask for their code and call `verifyMfa(code)` within 5 minutes ([Multi-factor authentication](https://sovaria.in/docs/mfa)). If the project requires MFA and they have none, sign-in is refused with `403`.
- The link and the code are tied together: using either one uses up both.

## Expiry and limits

| Rule | Default | Where to change it |
|---|---|---|
| Link and code expire after | 15 minutes | Fixed |
| Wrong codes allowed before the code stops working | 5 | Users › Rate limits › Email code attempts |
| Links per address per hour | 3 | Users › Rate limits › Magic links per address |
| Requests per IP address per hour | 5 | Users › Rate limits › Magic links per IP |
| Auth emails per project per hour | 500 | Users › Rate limits › Emails sent |

Going over a limit answers `429` with a message you can show. With **CAPTCHA** on (**Users › Attack protection**), send the token from your widget with the request; the Dart, Swift and Kotlin SDKs take it as `captchaToken`.

## Customize the email

The email uses the `magic_link` template. On plans with custom templates you can change its subject and body under **Users › Email**, using `{{ magic_link_url }}`, `{{ otp_code }}`, `{{ project_name }}`, `{{ email }}` and `{{ ttl_minutes }}` ([Auth emails](https://sovaria.in/docs/auth-emails)).

## Test it

- Add a test user with **Invite user** on the **Users** page, using an inbox you can read, then request a link from your app.
- To see every message your project sends while testing, point **custom SMTP** at a testing inbox service such as Mailtrap.
- Nothing arrives? Check that the address belongs to a user in **this** project (each project has its own users), that Magic link is on, and that you are under the hourly limits ([Troubleshooting authentication](https://sovaria.in/docs/troubleshooting-auth)).
