[PERS SDK - v2.3.26](/sdk-reference/readme) / [Exports](/sdk-reference/modules) / AuthManager

# Class: AuthManager

Authentication Manager - Clean, high-level interface for authentication operations

Provides a simplified API for common authentication tasks while maintaining
access to the underlying API client for advanced use cases.

Supports the universal token endpoint (POST /auth/token):

- User authentication (default)
- Business authentication with role in JWT
- Admin/Tenant authentication


**`Example`**

```typescript
// Login with external JWT
const authResult = await sdk.auth.loginWithToken(firebaseJWT, 'user');

// Login as business (with role in JWT)
const bizResult = await sdk.auth.loginAsBusiness(jwt, { businessId: 'biz-123' });
console.log('Business:', bizResult.business?.displayName);

// Check authentication
if (await sdk.auth.isAuthenticated()) {
  const user = await sdk.auth.getCurrentUser();
  console.log('Welcome,', user.name);
}

// Logout
await sdk.auth.clearAuth();
```

## Table of contents

### Constructors

- [constructor](/sdk-reference/classes/authmanager#constructor)


### Methods

- [loginWithToken](/sdk-reference/classes/authmanager#loginwithtoken)
- [loginAsBusiness](/sdk-reference/classes/authmanager#loginasbusiness)
- [loginAsTenant](/sdk-reference/classes/authmanager#loginastenant)
- [getCurrentBusiness](/sdk-reference/classes/authmanager#getcurrentbusiness)
- [getCurrentAdmin](/sdk-reference/classes/authmanager#getcurrentadmin)
- [loginWithRawData](/sdk-reference/classes/authmanager#loginwithrawdata)
- [getCurrentUser](/sdk-reference/classes/authmanager#getcurrentuser)
- [isAuthenticated](/sdk-reference/classes/authmanager#isauthenticated)
- [refreshTokens](/sdk-reference/classes/authmanager#refreshtokens)
- [clearAuth](/sdk-reference/classes/authmanager#clearauth)
- [ensureValidToken](/sdk-reference/classes/authmanager#ensurevalidtoken)
- [hasValidAuth](/sdk-reference/classes/authmanager#hasvalidauth)


## Constructors

### constructor

• **new AuthManager**(`apiClient`, `events?`): [`AuthManager`](/sdk-reference/classes/authmanager)

#### Parameters

| Name | Type |
|  --- | --- |
| `apiClient` | [`PersApiClient`](/sdk-reference/classes/persapiclient) |
| `events?` | [`PersEventEmitter`](/sdk-reference/classes/perseventemitter) |


#### Returns

[`AuthManager`](/sdk-reference/classes/authmanager)

#### Defined in

[managers/auth-manager.ts:45](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L45)

## Methods

### loginWithToken

▸ **loginWithToken**(`jwtToken`, `userType?`): `Promise`<`SessionAuthContextResponseDTO`>

Login with JWT token

Authenticates a user or admin using an external JWT token (Firebase, Auth0, etc.).
Automatically stores authentication tokens for subsequent API calls.

#### Parameters

| Name | Type | Default value | Description |
|  --- | --- | --- | --- |
| `jwtToken` | `string` | `undefined` | JWT token to authenticate with |
| `userType` | `AccountOwnerType` | `AccountOwnerType.USER` | Type of user ('user' | 'admin'). Defaults to 'user' |


#### Returns

`Promise`<`SessionAuthContextResponseDTO`>

Promise resolving to authentication response with user/admin data and tokens

**`Example`**

```typescript
const authResult = await sdk.auth.loginWithToken(firebaseJWT);
console.log('User authenticated:', authResult.user.name);
```

**`Example`**

```typescript
const authResult = await sdk.auth.loginWithToken(adminJWT, 'admin');
console.log('Admin authenticated:', authResult.admin.email);
```

#### Defined in

[managers/auth-manager.ts:72](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L72)

### loginAsBusiness

▸ **loginAsBusiness**(`jwtToken`, `options?`): `Promise`<`SessionAuthContextResponseDTO`>

Login as business with JWT token

Authenticates a user in a business context. The returned JWT contains
the user's role (OWNER, ADMIN, EDITOR, VIEWER) within that business.

**Auto-Selection Behavior:**

- If user has a single business membership, it's auto-selected
- If user has multiple memberships and no businessId is provided,
throws `MULTIPLE_CONTEXT_SELECTION_REQUIRED` error with available options


#### Parameters

| Name | Type | Description |
|  --- | --- | --- |
| `jwtToken` | `string` | JWT token from auth provider (passkey, Firebase, etc.) |
| `options?` | [`BusinessAuthOptions`](/sdk-reference/interfaces/businessauthoptions) | Business authentication options (businessId for multi-business users) |


#### Returns

`Promise`<`SessionAuthContextResponseDTO`>

Promise resolving to authentication response with business context and role in JWT

**`Throws`**

Error with code `MULTIPLE_CONTEXT_SELECTION_REQUIRED` when businessId is needed

**`Example`**

```typescript
// Auto-selects the user's only business
const result = await sdk.auth.loginAsBusiness(jwt);
console.log('Business:', result.business?.displayName);
```

**`Example`**

```typescript
try {
  const result = await sdk.auth.loginAsBusiness(jwt);
} catch (error) {
  if (error.code === 'MULTIPLE_CONTEXT_SELECTION_REQUIRED') {
    // Show business selector UI
    const selectedId = await showBusinessSelector(error.availableOptions);
    const result = await sdk.auth.loginAsBusiness(jwt, { businessId: selectedId });
  }
}
```

**`Example`**

```typescript
const result = await sdk.auth.loginAsBusiness(jwt, { businessId: 'biz-123' });
console.log('Authenticated as:', result.business?.displayName);
```

#### Defined in

[managers/auth-manager.ts:131](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L131)

### loginAsTenant

▸ **loginAsTenant**(`jwtToken`, `options?`): `Promise`<`SessionAuthContextResponseDTO`>

Login as tenant admin with JWT token

Authenticates an admin in a tenant context.

**Auto-Selection Behavior:**

- If admin has access to a single tenant, it's auto-selected
- If admin has access to multiple tenants and no tenantId is provided,
throws `MULTIPLE_CONTEXT_SELECTION_REQUIRED` error with available options


#### Parameters

| Name | Type | Description |
|  --- | --- | --- |
| `jwtToken` | `string` | JWT token from auth provider (Firebase, etc.) |
| `options?` | [`TenantAuthOptions`](/sdk-reference/interfaces/tenantauthoptions) | Tenant authentication options (tenantId for multi-tenant admins) |


#### Returns

`Promise`<`SessionAuthContextResponseDTO`>

Promise resolving to authentication response with tenant context

**`Throws`**

Error with code `MULTIPLE_CONTEXT_SELECTION_REQUIRED` when tenantId is needed

**`Example`**

```typescript
// Auto-selects the admin's only tenant
const result = await sdk.auth.loginAsTenant(jwt);
console.log('Tenant:', result.admin?.tenantId);
```

**`Example`**

```typescript
try {
  const result = await sdk.auth.loginAsTenant(jwt);
} catch (error) {
  if (error.code === 'MULTIPLE_CONTEXT_SELECTION_REQUIRED') {
    // Show tenant selector UI
    const selectedId = await showTenantSelector(error.details.availableOptions);
    const result = await sdk.auth.loginAsTenant(jwt, { tenantId: selectedId });
  }
}
```

**`Example`**

```typescript
const result = await sdk.auth.loginAsTenant(jwt, { tenantId: 'tenant-123' });
console.log('Authenticated as admin for tenant:', result.admin?.tenantId);
```

#### Defined in

[managers/auth-manager.ts:186](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L186)

### getCurrentBusiness

▸ **getCurrentBusiness**(): `Promise`<`BusinessDTO`>

Get current business context

Retrieves the current business context if authenticated as business.
Requires prior business authentication via [loginAsBusiness](/sdk-reference/classes/authmanager#loginasbusiness).

#### Returns

`Promise`<`BusinessDTO`>

Promise resolving to current business data

**`Throws`**

When not authenticated as business

**`Example`**

```typescript
const business = await sdk.auth.getCurrentBusiness();
console.log('Current business:', business.displayName);
```

#### Defined in

[managers/auth-manager.ts:215](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L215)

### getCurrentAdmin

▸ **getCurrentAdmin**(): `Promise`<`AdminDTO`>

Get current admin context

Retrieves the current admin data if authenticated as tenant admin.
Requires prior tenant authentication via [loginAsTenant](/sdk-reference/classes/authmanager#loginastenant).

#### Returns

`Promise`<`AdminDTO`>

Promise resolving to current admin data

**`Throws`**

When not authenticated as tenant admin

**`Example`**

```typescript
const admin = await sdk.auth.getCurrentAdmin();
console.log('Current admin:', admin.email);
```

#### Defined in

[managers/auth-manager.ts:235](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L235)

### loginWithRawData

▸ **loginWithRawData**(`rawUserData`): `Promise`<`SessionAuthContextResponseDTO`>

Login with raw user data

Authenticates using raw user data instead of a JWT token. Useful for
direct integration without external authentication providers.

#### Parameters

| Name | Type | Description |
|  --- | --- | --- |
| `rawUserData` | [`RawUserData`](/sdk-reference/interfaces/rawuserdata) | Raw user data for authentication |


#### Returns

`Promise`<`SessionAuthContextResponseDTO`>

Promise resolving to authentication response

**`Example`**

```typescript
const authResult = await sdk.auth.loginWithRawData({
  email: 'user@example.com',
  name: 'John Doe',
  externalId: 'custom-user-id'
});
```

#### Defined in

[managers/auth-manager.ts:258](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L258)

### getCurrentUser

▸ **getCurrentUser**(): `Promise`<`UserDTO`>

Get current authenticated user

Retrieves the currently authenticated user's profile information.
Requires valid authentication tokens.

#### Returns

`Promise`<`UserDTO`>

Promise resolving to current user data

**`Throws`**

When user is not authenticated or tokens are invalid

**`Example`**

```typescript
try {
  const user = await sdk.auth.getCurrentUser();
  console.log('Current user:', user.name, user.email);
} catch (error) {
  console.log('User not authenticated');
}
```

#### Defined in

[managers/auth-manager.ts:291](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L291)

### isAuthenticated

▸ **isAuthenticated**(): `Promise`<`boolean`>

Check if user is authenticated

Performs an asynchronous check to verify if the user is currently authenticated
by attempting to fetch user data. More reliable than [hasValidAuth](/sdk-reference/classes/authmanager#hasvalidauth) but slower.

#### Returns

`Promise`<`boolean`>

Promise resolving to boolean indicating authentication status

**`Example`**

```typescript
if (await sdk.auth.isAuthenticated()) {
  // User is authenticated, proceed with authenticated operations
  const user = await sdk.auth.getCurrentUser();
} else {
  // Redirect to login
  redirectToLogin();
}
```

**`See`**

[hasValidAuth](/sdk-reference/classes/authmanager#hasvalidauth) for synchronous token validation

#### Defined in

[managers/auth-manager.ts:319](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L319)

### refreshTokens

▸ **refreshTokens**(`refreshToken?`): `Promise`<`SessionAuthResponseDTO`>

Refresh access token using stored refresh token

Obtains new access tokens using the stored refresh token. This is typically
called automatically by the SDK when tokens expire, but can be called manually
if needed.

#### Parameters

| Name | Type | Description |
|  --- | --- | --- |
| `refreshToken?` | `string` | Optional refresh token, uses stored token if not provided |


#### Returns

`Promise`<`SessionAuthResponseDTO`>

Promise resolving to new auth tokens

**`Example`**

```typescript
try {
  const newTokens = await sdk.auth.refreshTokens();
  console.log('Tokens refreshed successfully');
} catch (error) {
  console.log('Refresh failed, need to re-login');
  await sdk.auth.clearAuth();
}
```

#### Defined in

[managers/auth-manager.ts:349](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L349)

### clearAuth

▸ **clearAuth**(): `Promise`<`void`>

Clear stored authentication tokens

Removes all stored authentication tokens and clears the authentication state.
Use this for logout functionality.

#### Returns

`Promise`<`void`>

Promise that resolves when tokens are cleared

**`Example`**

```typescript
async function logout() {
  await sdk.auth.clearAuth();
  console.log('User logged out');
  // Redirect to login page
  window.location.href = '/login';
}
```

#### Defined in

[managers/auth-manager.ts:372](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L372)

### ensureValidToken

▸ **ensureValidToken**(): `Promise`<`void`>

Ensure authentication token is valid

Checks if the current token is expired or about to expire and automatically
refreshes it if needed. This is useful for ensuring valid authentication
before performing critical operations or when app resumes from background.

Uses a 120-second margin - tokens are refreshed if they expire within 2 minutes.

#### Returns

`Promise`<`void`>

Promise that resolves when token is validated/refreshed

**`Example`**

```typescript
AppState.addEventListener('change', async (state) => {
  if (state === 'active') {
    // Validate tokens when app returns from background
    await sdk.auth.ensureValidToken().catch(console.error);
  }
});
```

**`Example`**

```typescript
async function processPayment() {
  // Ensure token is valid before payment
  await sdk.auth.ensureValidToken();
  const result = await sdk.purchases.createPurchase(paymentData);
}
```

#### Defined in

[managers/auth-manager.ts:413](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L413)

### hasValidAuth

▸ **hasValidAuth**(): `Promise`<`boolean`>

Check if SDK has valid authentication

Performs a synchronous check of stored authentication tokens without making
an API call. Faster than [isAuthenticated](/sdk-reference/classes/authmanager#isauthenticated) but less reliable as it
doesn't verify tokens with the server.

#### Returns

`Promise`<`boolean`>

Boolean indicating if valid authentication exists

**`Example`**

```typescript
if (sdk.auth.hasValidAuth()) {
  // Tokens exist locally, but may still be expired
  console.log('Authentication tokens found');
} else {
  // No tokens found
  console.log('No authentication tokens');
}
```

**`See`**

[isAuthenticated](/sdk-reference/classes/authmanager#isauthenticated) for server-verified authentication check

#### Defined in

[managers/auth-manager.ts:439](https://github.com/eXplorins/PERS-sdks/blob/main/packages/pers-sdk/packages/pers-sdk/src/managers/auth-manager.ts#L439)