or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mddatabase.mdfunctions.mdindex.mdrealtime.mdstorage.md

authentication.mddocs/

0

# Authentication

1

2

Complete user management system with email/password authentication, OAuth providers, magic links, and session management. Handles user registration, login, logout, password reset, and profile management with automatic token refresh.

3

4

## Capabilities

5

6

### Session Management

7

8

Manage user sessions with automatic token refresh and persistence across browser sessions.

9

10

```typescript { .api }

11

/**

12

* Returns the session, refreshing it if necessary

13

* @returns Promise resolving to session data or error

14

*/

15

getSession(): Promise<{

16

data: { session: Session | null };

17

error: AuthError | null;

18

}>;

19

20

/**

21

* Gets the current user details if there is an existing session

22

* @param jwt - Optional JWT token to use instead of the session token

23

* @returns Promise resolving to user data or error

24

*/

25

getUser(jwt?: string): Promise<{

26

data: { user: User | null };

27

error: AuthError | null;

28

}>;

29

30

/**

31

* Updates user data for a logged in user

32

* @param attributes - User attributes to update

33

* @returns Promise resolving to updated user data or error

34

*/

35

updateUser(attributes: UserAttributes): Promise<{

36

data: { user: User | null };

37

error: AuthError | null;

38

}>;

39

40

/**

41

* Sets the session data from a refresh_token and returns current Session and Error

42

* @param refresh_token - A valid refresh token that was returned on login

43

* @returns Promise resolving to session data or error

44

*/

45

setSession(refresh_token: string): Promise<{

46

data: { session: Session | null };

47

error: AuthError | null;

48

}>;

49

50

/**

51

* Refresh the access token of the user session

52

* @returns Promise resolving to refreshed session or error

53

*/

54

refreshSession(): Promise<{

55

data: { session: Session | null };

56

error: AuthError | null;

57

}>;

58

59

interface Session {

60

access_token: string;

61

refresh_token: string;

62

expires_in: number;

63

expires_at?: number;

64

token_type: string;

65

user: User;

66

}

67

68

interface User {

69

id: string;

70

aud: string;

71

role?: string;

72

email?: string;

73

email_confirmed_at?: string;

74

phone?: string;

75

phone_confirmed_at?: string;

76

confirmation_sent_at?: string;

77

confirmed_at?: string;

78

recovery_sent_at?: string;

79

last_sign_in_at?: string;

80

app_metadata: Record<string, any>;

81

user_metadata: Record<string, any>;

82

identities?: Identity[];

83

created_at: string;

84

updated_at?: string;

85

}

86

87

interface UserAttributes {

88

email?: string;

89

phone?: string;

90

password?: string;

91

data?: Record<string, any>;

92

}

93

```

94

95

**Usage Examples:**

96

97

```typescript

98

// Get current session

99

const { data: { session }, error } = await supabase.auth.getSession();

100

if (session) {

101

console.log('User is logged in:', session.user);

102

}

103

104

// Get current user

105

const { data: { user }, error } = await supabase.auth.getUser();

106

if (user) {

107

console.log('Current user:', user.email);

108

}

109

110

// Update user profile

111

const { data, error } = await supabase.auth.updateUser({

112

data: { display_name: 'New Display Name' }

113

});

114

115

// Refresh session manually

116

const { data, error } = await supabase.auth.refreshSession();

117

```

118

119

### Email/Password Authentication

120

121

Traditional email and password authentication with user registration and login.

122

123

```typescript { .api }

124

/**

125

* Creates a new user with email and password

126

* @param credentials - User registration credentials

127

* @returns Promise resolving to auth response

128

*/

129

signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;

130

131

/**

132

* Log in an existing user with email and password

133

* @param credentials - User login credentials

134

* @returns Promise resolving to auth response

135

*/

136

signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthResponse>;

137

138

/**

139

* Log in an existing user via a third-party provider

140

* @param credentials - OAuth provider credentials

141

* @returns Promise resolving to auth response with redirect URL

142

*/

143

signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<{

144

data: { url: string; provider: Provider };

145

error: AuthError | null;

146

}>;

147

148

/**

149

* Signs out the current user, if there is a logged in user

150

* @param options - Sign out options

151

* @returns Promise resolving to error if any

152

*/

153

signOut(options?: { scope?: 'global' | 'local' | 'others' }): Promise<{

154

error: AuthError | null;

155

}>;

156

157

interface SignUpWithPasswordCredentials {

158

email: string;

159

password: string;

160

options?: {

161

/** A custom data object to store the user's metadata */

162

data?: Record<string, any>;

163

/** The redirect URL embedded in the email link */

164

emailRedirectTo?: string;

165

/** Verification token received when the user completes the captcha on the site */

166

captchaToken?: string;

167

};

168

}

169

170

interface SignInWithPasswordCredentials {

171

email: string;

172

password: string;

173

options?: {

174

/** Verification token received when the user completes the captcha on the site */

175

captchaToken?: string;

176

};

177

}

178

179

interface SignInWithOAuthCredentials {

180

provider: Provider;

181

options?: {

182

/** A URL to send the user to after they are confirmed */

183

redirectTo?: string;

184

/** A space-separated list of scopes granted to the OAuth application */

185

scopes?: string;

186

/** An object of query params */

187

queryParams?: Record<string, string>;

188

/** If set to false, no redirect will happen after auth */

189

skipBrowserRedirect?: boolean;

190

};

191

}

192

193

interface AuthResponse {

194

data: {

195

user: User | null;

196

session: Session | null;

197

};

198

error: AuthError | null;

199

}

200

201

type Provider =

202

| 'apple'

203

| 'azure'

204

| 'bitbucket'

205

| 'discord'

206

| 'facebook'

207

| 'figma'

208

| 'github'

209

| 'gitlab'

210

| 'google'

211

| 'keycloak'

212

| 'linkedin'

213

| 'notion'

214

| 'slack'

215

| 'spotify'

216

| 'twitch'

217

| 'twitter'

218

| 'workos'

219

| 'zoom';

220

```

221

222

**Usage Examples:**

223

224

```typescript

225

// Sign up new user

226

const { data, error } = await supabase.auth.signUp({

227

email: 'user@example.com',

228

password: 'password123',

229

options: {

230

data: {

231

display_name: 'John Doe',

232

age: 30

233

}

234

}

235

});

236

237

// Sign in existing user

238

const { data, error } = await supabase.auth.signInWithPassword({

239

email: 'user@example.com',

240

password: 'password123'

241

});

242

243

// OAuth sign in

244

const { data, error } = await supabase.auth.signInWithOAuth({

245

provider: 'google',

246

options: {

247

redirectTo: 'https://myapp.com/dashboard'

248

}

249

});

250

251

// Sign out

252

const { error } = await supabase.auth.signOut();

253

```

254

255

### Magic Link and OTP Authentication

256

257

Passwordless authentication using email magic links or one-time passwords.

258

259

```typescript { .api }

260

/**

261

* Sends a magic link login email to the specified email address

262

* @param credentials - Magic link credentials

263

* @returns Promise resolving to auth response

264

*/

265

signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<{

266

data: {};

267

error: AuthError | null;

268

}>;

269

270

/**

271

* Log in a user using a one-time password (OTP)

272

* @param credentials - OTP verification credentials

273

* @returns Promise resolving to auth response

274

*/

275

verifyOtp(credentials: VerifyOtpParams): Promise<AuthResponse>;

276

277

/**

278

* Sends a reauthentication OTP to the user's email or phone number

279

* @param credentials - Reauthentication credentials

280

* @returns Promise resolving to success or error

281

*/

282

reauthenticate(): Promise<{

283

data: {};

284

error: AuthError | null;

285

}>;

286

287

interface SignInWithPasswordlessCredentials {

288

email?: string;

289

phone?: string;

290

options?: {

291

/** A custom data object to store additional metadata */

292

data?: Record<string, any>;

293

/** The redirect URL embedded in the email link */

294

emailRedirectTo?: string;

295

/** If set to false, this method will not create a new user */

296

shouldCreateUser?: boolean;

297

/** Verification token received when the user completes the captcha */

298

captchaToken?: string;

299

/** Channel for sending the OTP */

300

channel?: 'sms' | 'whatsapp';

301

};

302

}

303

304

interface VerifyOtpParams {

305

email?: string;

306

phone?: string;

307

token: string;

308

type: 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'sms' | 'phone_change';

309

options?: {

310

/** The redirect URL embedded in the email link */

311

redirectTo?: string;

312

/** Verification token received when the user completes the captcha */

313

captchaToken?: string;

314

};

315

}

316

```

317

318

**Usage Examples:**

319

320

```typescript

321

// Send magic link

322

const { data, error } = await supabase.auth.signInWithOtp({

323

email: 'user@example.com',

324

options: {

325

emailRedirectTo: 'https://myapp.com/welcome'

326

}

327

});

328

329

// Send SMS OTP

330

const { data, error } = await supabase.auth.signInWithOtp({

331

phone: '+1234567890',

332

options: {

333

channel: 'sms'

334

}

335

});

336

337

// Verify OTP

338

const { data, error } = await supabase.auth.verifyOtp({

339

email: 'user@example.com',

340

token: '123456',

341

type: 'magiclink'

342

});

343

344

// Verify phone OTP

345

const { data, error } = await supabase.auth.verifyOtp({

346

phone: '+1234567890',

347

token: '123456',

348

type: 'sms'

349

});

350

```

351

352

### Password Recovery

353

354

Password reset functionality for users who have forgotten their password.

355

356

```typescript { .api }

357

/**

358

* Sends a password reset request to an email address

359

* @param credentials - Password reset credentials

360

* @returns Promise resolving to success or error

361

*/

362

resetPasswordForEmail(email: string, options?: {

363

/** The redirect URL embedded in the email link */

364

redirectTo?: string;

365

/** Verification token received when the user completes the captcha */

366

captchaToken?: string;

367

}): Promise<{

368

data: {};

369

error: AuthError | null;

370

}>;

371

```

372

373

**Usage Examples:**

374

375

```typescript

376

// Request password reset

377

const { data, error } = await supabase.auth.resetPasswordForEmail(

378

'user@example.com',

379

{

380

redirectTo: 'https://myapp.com/reset-password'

381

}

382

);

383

384

// After user clicks the reset link, they can update their password

385

const { data, error } = await supabase.auth.updateUser({

386

password: 'new-password'

387

});

388

```

389

390

### Event Handling

391

392

Listen for authentication state changes to update your application UI accordingly.

393

394

```typescript { .api }

395

/**

396

* Receive a notification every time an auth event happens

397

* @param callback - Callback function to handle auth state changes

398

* @returns Subscription object with unsubscribe method

399

*/

400

onAuthStateChange(

401

callback: (event: AuthChangeEvent, session: Session | null) => void

402

): {

403

data: { subscription: Subscription };

404

};

405

406

type AuthChangeEvent =

407

| 'INITIAL_SESSION'

408

| 'SIGNED_IN'

409

| 'SIGNED_OUT'

410

| 'TOKEN_REFRESHED'

411

| 'USER_UPDATED'

412

| 'PASSWORD_RECOVERY';

413

414

interface Subscription {

415

id: string;

416

callback: (event: AuthChangeEvent, session: Session | null) => void;

417

unsubscribe: () => void;

418

}

419

```

420

421

**Usage Examples:**

422

423

```typescript

424

// Listen for auth changes

425

const { data: { subscription } } = supabase.auth.onAuthStateChange(

426

(event, session) => {

427

console.log('Auth event:', event);

428

429

if (event === 'SIGNED_IN') {

430

console.log('User signed in:', session?.user);

431

// Redirect to dashboard

432

} else if (event === 'SIGNED_OUT') {

433

console.log('User signed out');

434

// Redirect to login

435

} else if (event === 'TOKEN_REFRESHED') {

436

console.log('Token refreshed');

437

// Update stored session

438

}

439

}

440

);

441

442

// Unsubscribe when component unmounts

443

subscription.unsubscribe();

444

```

445

446

## Error Handling

447

448

```typescript { .api }

449

class AuthError extends Error {

450

message: string;

451

status?: number;

452

}

453

454

interface AuthErrorCodes {

455

signup_disabled: 'Email signups are disabled';

456

invalid_credentials: 'Invalid login credentials';

457

email_not_confirmed: 'Email not confirmed';

458

phone_not_confirmed: 'Phone not confirmed';

459

weak_password: 'Password is too weak';

460

over_email_send_rate_limit: 'Too many emails sent';

461

captcha_failed: 'Captcha failed';

462

same_password: 'New password should be different';

463

invalid_email: 'Invalid email address';

464

email_address_not_authorized: 'Email address not authorized';

465

}

466

```

467

468

**Usage Examples:**

469

470

```typescript

471

const { data, error } = await supabase.auth.signInWithPassword({

472

email: 'user@example.com',

473

password: 'wrong-password'

474

});

475

476

if (error) {

477

switch (error.message) {

478

case 'Invalid login credentials':

479

console.error('Wrong email or password');

480

break;

481

case 'Email not confirmed':

482

console.error('Please check your email and click the confirmation link');

483

break;

484

default:

485

console.error('Authentication error:', error.message);

486

}

487

}

488

```

489

490

## Third-Party Authentication Setup

491

492

```typescript

493

// Configure OAuth providers in your Supabase dashboard, then use:

494

495

// Google OAuth

496

const { data, error } = await supabase.auth.signInWithOAuth({

497

provider: 'google',

498

options: {

499

scopes: 'email profile',

500

redirectTo: `${window.location.origin}/dashboard`

501

}

502

});

503

504

// GitHub OAuth

505

const { data, error } = await supabase.auth.signInWithOAuth({

506

provider: 'github',

507

options: {

508

scopes: 'user:email',

509

redirectTo: `${window.location.origin}/dashboard`

510

}

511

});

512

513

// Apple OAuth (requires additional setup)

514

const { data, error } = await supabase.auth.signInWithOAuth({

515

provider: 'apple',

516

options: {

517

redirectTo: `${window.location.origin}/dashboard`

518

}

519

});

520

```