# Email and password
Source: https://sovaria.in/docs/email-and-password

Sign users up, confirm their email, sign them in, and let them reset a forgotten password.

## Sign up

JavaScript:
```js
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')

const result = await sovaria.auth.signUp('ada@example.com', 'Correct-Horse-9!', 'Ada')
if (result.email_verification_required) {
  showMessage('Check your inbox to confirm your email.')
} // otherwise the user is signed in
```

Python:
```python
async with create_client("https://<project-ref>.sovarias.in", "<anon-key>") as sovaria:
    await sovaria.sign_up("ada@example.com", "Correct-Horse-9!", "Ada")
```

cURL:
```bash
curl https://<project-ref>.sovarias.in/api/v1/auth/register \
  -H 'Content-Type: application/json' \
  -d '{"email":"ada@example.com","password":"Correct-Horse-9!","name":"Ada","data":{"plan":"trial"}}'
# creates the user; then sign in (below) to get a session
```

- Sign-ups must be allowed for the project (**Sign in / Providers → Allow new users to sign up**); otherwise the API answers `403`.
- Default password rules: at least 8 characters with an uppercase letter, a digit and a symbol. Change them under **Security & JWT**. A weak password returns `422` with the rule it broke.
- `signUp` creates the user and signs them in. `register` only creates the user. Without a name, the part of the email before the `@` is used.
- An address that already has an account: sign-up answers exactly like a new one (same `201`, same fields, same time), creates nothing and starts no session, so nobody can use your sign-up form to find out who has an account. The owner of the address gets an email saying someone tried to sign up, with a sign-in link and a one-time password-reset link (at most one an hour). `signUp` then signs in with the password given, which only succeeds if it is that account's own password; otherwise it fails like any wrong password. With email confirmation on, the answer also says `email_verification_required: true`, as for a new account.

supabase-js-style calls work too, and never throw: the error comes back in `error`. `options.data` is saved as the user's `user_metadata` when the account is created, also while the email waits to be confirmed (over HTTP: `data` in the sign-up body).

JavaScript:
```js
const { data, error } = await sovaria.auth.signUp({
  email: 'ada@example.com',
  password: 'Correct-Horse-9!',
  options: { data: { full_name: 'Ada Lovelace' } },   // full_name / name also becomes the display name
})
if (error) showError(error.message)
else if (!data.session) showMessage('Check your inbox to confirm your email.')
```

Python:
```python
res = await sovaria.auth.sign_up({
    "email": "ada@example.com", "password": "Correct-Horse-9!",
    "options": {"data": {"full_name": "Ada Lovelace"}},
})
print(res.user.id, res.session is not None)   # raises SovariaError on failure, like supabase-py
```

Swift:
```swift
try await sovaria.auth.signUp(email: "ada@example.com", password: "Correct-Horse-9!", data: ["full_name": "Ada Lovelace"])
```

Kotlin:
```kotlin
sovaria.auth.signUp("ada@example.com", "Correct-Horse-9!", data = mapOf("full_name" to "Ada Lovelace"))
```

Dart:
```dart
await sovaria.auth.signUp(email: 'ada@example.com', password: 'Correct-Horse-9!', data: {'full_name': 'Ada Lovelace'});
```

## Confirm the email address

When email verification is on, the user receives a confirmation email. The link opens your **Site URL** with `?token=…&type=signup`. Call `handleEmailLink()` on that page:

JavaScript:
```js
const result = await sovaria.auth.handleEmailLink()   // reads window.location
if (result?.type === 'signup') showMessage('Email confirmed — you can sign in now.')
```

**Someone else may have registered the address first.** Confirming from the account's own session (the SDK sends it when the user is signed in, for example an anonymous user who just added their email) only confirms it. Confirming from anywhere else — another device, the mail app's browser, no session — also confirms it and signs nobody out, but the account is marked: the inbox owner's first sign-in that proves the inbox (a magic link or email code, a password reset, or Google/GitHub/SSO with a verified email) ends everything set before the address was proven — the password, phone, two-factor methods, passkeys, linked identities and sessions — so a person who registered someone else's address can't keep a way in.

## Sign in

JavaScript:
```js
const session = await sovaria.auth.signIn('ada@example.com', 'Correct-Horse-9!')
if (session.mfa_required) {
  // ask for the 6-digit code from their authenticator app
  await sovaria.auth.verifyMfa(code)
}
const me = await sovaria.auth.me()
```

Python:
```python
await sovaria.sign_in("ada@example.com", "Correct-Horse-9!")
me = await sovaria.get_me()
```

cURL:
```bash
curl https://<project-ref>.sovarias.in/api/v1/auth/project/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"ada@example.com","password":"Correct-Horse-9!"}'
# → {"access_token": "...", "refresh_token": "...", "expires_in": ...}
```

Or, as in supabase-js (`data.mfa_required` means call `verifyMfa(code)` next):

JavaScript:
```js
const { data, error } = await sovaria.auth.signInWithPassword({ email, password })
if (error) showError(error.message)          // e.g. wrong password: error.statusCode === 401
else setUser(data.user)                       // { id, email, user_metadata, app_metadata, is_anonymous, … }
```

Python:
```python
res = await sovaria.auth.sign_in_with_password({"email": email, "password": password})
print(res.user.email, res.session.access_token)
```

Wrong credentials return `401` with a generic message. Repeated failures are rate-limited per IP and per email.

## The user and their metadata

`getUser()` (`GET /api/v1/auth/me`) reads the signed-in user from the server, with their `user_metadata`, `app_metadata` and `is_anonymous`. `updateUser()` (`PATCH /api/v1/auth/me`) changes what the user may change about themselves: `data` is merged into `user_metadata` (a `null` value removes a key), a new `email` is confirmed by a link first, and a new `password` needs the current one (or a `nonce` from a recent sign-in). An anonymous user who adds an email becomes a permanent one. `app_metadata` is for your admins only ([Users and app roles](https://sovaria.in/docs/users-and-roles)).

JavaScript:
```js
const { data: { user } } = await sovaria.auth.getUser()       // null when nobody is signed in
const { error } = await sovaria.auth.updateUser({ data: { theme: 'dark' } })
await sovaria.auth.updateUser({ password: newPassword, currentPassword })
```

Python:
```python
user = (await sovaria.auth.get_user()).user
await sovaria.auth.update_user({"data": {"theme": "dark"}})
```

Swift:
```swift
let user = try await sovaria.auth.updateUser(data: ["theme": "dark"])
```

Kotlin:
```kotlin
val user = sovaria.auth.updateUser(data = mapOf("theme" to "dark"))
```

Dart:
```dart
final user = await sovaria.auth.updateUser(data: {'theme': 'dark'});
```

cURL:
```bash
curl -X PATCH https://<project-ref>.sovarias.in/api/v1/auth/me \
  -H "Authorization: Bearer $USER_TOKEN" -H 'Content-Type: application/json' \
  -d '{"data": {"theme": "dark"}}'
```

## Reset a forgotten password

1. **Request the email**
```js
await sovaria.auth.resetPasswordForEmail('ada@example.com', { redirectTo: 'https://app.example.com/reset' })
```
2. **Handle the link** — The link opens `redirectTo` (or your Site URL) with `?token=…&type=recovery`. `handleEmailLink()` returns the token so you can show a "new password" form.
3. **Set the new password**
```js
const link = await sovaria.auth.handleEmailLink()
if (link?.type === 'recovery') {
  await sovaria.auth.confirmPasswordReset(link.token, newPassword)
}
```

> **Note:** The reset email is only sent if the account exists, but the API answers the same way either way. Reset links expire after 15 minutes and work once. After a reset, the user is signed out everywhere and gets a "password changed" email.
