npm package: @mirats/mirats-auth
Description: Mamauth SDK for authentication and user management
Author: Mirats Group
Latest version: 2.0.7

# Mamauth SDK

A TypeScript SDK for integrating Mamauth authentication and user management into your applications.

**Package:** `@mirats/mirats-auth`  
**Version:** `2.0.7`

## Installation

```bash
npm install @mirats/mirats-auth@2.0.7
# or
yarn add @mirats/mirats-auth@2.0.7
# or
pnpm add @mirats/mirats-auth@2.0.7
```

## Dependencies

The SDK requires the following peer dependencies:
- `crypto-js` - For URL encryption/decryption
- `jwt-decode` - For JWT token decoding

## Configuration

The SDK automatically detects the Mamauth origin URL. You can override it by:

1. **Environment Variable** (Client-side):
   ```javascript
   process.env.NEXT_PUBLIC_MAMAUTH_ORIGIN = 'https://your-custom-domain.com'
   ```

2. **Global Variable** (Client-side):
   ```javascript
   window.__MAMAUTH_ORIGIN__ = 'https://your-custom-domain.com'
   ```

3. **Environment Variable** (Server-side):
   ```javascript
   process.env.MAMAUTH_ORIGIN = 'https://your-custom-domain.com'
   ```

Default: `https://accounts.miratsgroup.com`

## Usage

### Import the SDK

```typescript
import {
  signIn,
  signUp,
  getAuth,
  isLoggedIn,
  logOut,
  getCookie,
  setCookie,
  deleteCookie,
  // ... other functions
} from '@mirats/mirats-auth';
```

### Authentication Functions

#### Sign In

Redirects user to the login page with optional redirect URL:

```typescript
// Sign in with default redirect
await signIn();

// Sign in with custom redirect URL
await signIn('https://myservice.example.com');
```

#### Sign In With Service

Sign in and automatically check service access:

```typescript
await signInWithService('https://myservice.example.com');
```

#### Sign Up

Redirects user to the registration page:

```typescript
await signUp();
```

#### Forgot Password

Redirects user to the forgot password page:

```typescript
await forgotPassword();
```

#### Get Authentication Status

Get the current user's authentication status and user data with service access:

```typescript
const auth = await getAuth();
if (auth) {
  console.log('User is authenticated:', auth.currentUser);
  console.log('Token:', auth.token);
  console.log('Session ID:', auth.sessionId);
  console.log('Service Access:', auth.currentUser.access);
  
  // Access user personal information (available in v2.0.7+)
  console.log('Date of Birth:', auth.currentUser.DOB);
  console.log('Gender:', auth.currentUser.gender);
  console.log('Phone:', auth.currentUser.phone_country_code, auth.currentUser.phone);
  console.log('Country:', auth.currentUser.country);
  console.log('Default Language:', auth.currentUser.defaultLanguage);
} else {
  console.log('User is not authenticated');
}
```

**Response Type:**
```typescript
interface AuthResponse {
  token: string;
  sessionId: string;
  session?: SessionInfo;
  currentUser: {
    _id: string;
    email: string;
    firstName: string;
    lastName: string;
    fullName: string;
    accountStatus: string;
    avatar?: string;
    access?: ServiceAccess[]; // Service access data
    
    // Personal Information
    DOB?: string | Date;
    gender?: string;
    pronouns?: string;
    phone?: string;
    phone_country_code?: string;
    secondaryEmail?: string;
    
    // Location Information
    country?: string;
    country_code?: string;
    countryMetadata?: any;
    
    // Preferences
    defaultLanguage?: string;
    
    // Additional Information
    addresses?: {
      workAddress?: string;
      homeAddress?: string;
    };
    about?: {
      introduction?: string;
      sports?: string;
      music?: string;
      books?: string;
    };
    workAndEducationDetails?: {
      work?: {
        companyName?: string;
        designation?: string;
        startDate?: Date | string;
        endDate?: Date | string;
        currentlyWorking?: boolean;
        description?: string;
      };
      education?: {
        collegeName?: string;
        degree?: string;
        startDate?: Date | string;
        endDate?: Date | string;
        currentlyStudying?: boolean;
        description?: string;
      };
    };
  };
}
```

#### Check if Logged In

Quick check if user has a valid token:

```typescript
const { user, loading } = isLoggedIn();
if (user) {
  console.log('User is logged in');
}
```

#### Log Out

Log out the current user and clear cookies:

```typescript
await logOut();
```

### Cookie Management

The SDK now uses `token` and `GAS-SE` cookies (primary) with `frontendCookie` as fallback for backward compatibility.

#### Get Cookie

```typescript
const token = getCookie('token');
```

#### Get Token (Helper)

```typescript
const token = getToken(); // Gets token from 'token' cookie or 'frontendCookie' fallback
```

#### Get Session ID (Helper)

```typescript
const sessionId = getSessionId(); // Gets session ID from 'GAS-SE' cookie
```

#### Set Cookie

```typescript
setCookie('token', 'your-token-value'); // 5 days expiration (default)
```

#### Delete Cookie

```typescript
deleteCookie('token');
```

#### Clear All Auth Cookies (Helper)

```typescript
clearAllAuthCookies(); // Clears token, GAS-SE, and frontendCookie
```

### User Management

#### Get GAS ID

Get a user's GAS ID by email:

```typescript
const result = await getGasId('user@example.com');
if (result) {
  console.log('GAS ID:', result.gasId);
}
```

#### Get Multiple GAS IDs

Get GAS IDs for multiple users (max 10):

```typescript
const results = await getGasIds([
  'user1@example.com',
  'user2@example.com',
]);
// Returns: [{ email: 'user1@example.com', gasId: '...' }, ...]
```

### Invitations

#### Generate Invite Link

```typescript
const link = inviteLink(
  'user@example.com',
  'user-id',
  'John', // firstName (optional)
  'Doe',  // lastName (optional)
  30      // days until expiration (default: 30)
);
```

#### Send User Invite

```typescript
const result = await sendUserInvite({
  name: 'John Doe',
  email: 'user@example.com',
  id: 'user-id',
  organizationName: 'My Organization',
  invitedBy: 'inviter-id',
  days: 30, // optional
});

if (result.success) {
  console.log('Invite sent successfully');
}
```

#### Send Multiple Invites

```typescript
const results = await sendUserInvites([
  {
    name: 'John Doe',
    email: 'john@example.com',
    id: 'user-id-1',
    organizationName: 'My Organization',
    invitedBy: 'inviter-id',
  },
  {
    name: 'Jane Smith',
    email: 'jane@example.com',
    id: 'user-id-2',
    organizationName: 'My Organization',
    invitedBy: 'inviter-id',
  },
]);
// Returns only successful invites
```

### Service Management

#### Create Service

```typescript
await createService({
  name: 'My Service',
  subdomain: 'myservice',
  type: 'private',
  url: 'https://myservice.example.com',
});
```

#### Check Service Access

Check if the current user has access to a service:

```typescript
const hasAccess = await checkServiceAccess('https://myservice.example.com');
if (hasAccess) {
  console.log('User has access');
} else {
  console.log('User does not have access');
}
```

### Utility Functions

#### Encrypt URL

```typescript
const encrypted = encryptURL('https://example.com');
```

#### Decrypt URL

```typescript
const decrypted = decryptURL(encryptedUrl);
```

#### Validate Email

```typescript
if (isValidEmail('user@example.com')) {
  console.log('Valid email');
}
```

#### Add Days to Date

```typescript
const futureDate = addDays(7); // 7 days from now
```

## User Data Fields

The `currentUser` object includes comprehensive user information (available in v2.0.7+):

### Basic Information
- `_id`, `email`, `firstName`, `lastName`, `fullName`, `accountStatus`, `avatar`

### Personal Information
- `DOB` - Date of birth (string or Date)
- `gender` - User's gender
- `pronouns` - Preferred pronouns
- `phone` - Phone number
- `phone_country_code` - Country code for phone (e.g., '+91')
- `secondaryEmail` - Secondary email address

### Location Information
- `country` - Country name
- `country_code` - ISO country code
- `countryMetadata` - Additional country metadata (flag, emoji, etc.)

### Preferences
- `defaultLanguage` - User's default language preference

### Additional Information
- `addresses` - Work and home addresses
- `about` - Personal interests (introduction, sports, music, books)
- `workAndEducationDetails` - Work experience and education history

### Example Usage

```typescript
const auth = await getAuth();
if (auth?.currentUser) {
  const user = auth.currentUser;
  
  // Personal info
  console.log('Name:', user.fullName);
  console.log('DOB:', user.DOB);
  console.log('Gender:', user.gender);
  console.log('Phone:', user.phone_country_code, user.phone);
  
  // Location
  console.log('Country:', user.country);
  
  // Preferences
  console.log('Language:', user.defaultLanguage);
  
  // Additional info
  if (user.addresses) {
    console.log('Work Address:', user.addresses.workAddress);
    console.log('Home Address:', user.addresses.homeAddress);
  }
}
```

## Cookie Names

The SDK uses the following cookie names:
- `token` - JWT authentication token (primary)
- `GAS-SE` - Session ID in format: `${random}-${mongoId}` (primary)
- `frontendCookie` - Legacy cookie name (fallback for backward compatibility)

## API Endpoints

The SDK communicates with the following endpoints:
- Base URL: `https://accounts.miratsgroup.com` (or your configured origin)
- Accounts API: `${baseURL}/accounts`
- Public Package APIs: `https://accounts-public-apis.miratsgroup.com` (or override via `window.MAMAUTH_PUBLIC_API_URL`)

### Override Public API URL

You can override the public API base URL by setting a global variable:

```typescript
// In your application initialization
(window as any).MAMAUTH_PUBLIC_API_URL = 'https://your-custom-api.com';
```

## Error Handling

All functions that make API calls will throw errors or return `null`/`false` on failure. Always check the return values:

```typescript
try {
  const auth = await getAuth();
  if (!auth) {
    // User not authenticated
    await signIn();
  }
} catch (error) {
  console.error('Authentication error:', error);
}
```

## User Data Fields

The `currentUser` object includes comprehensive user information:

### Basic Information
- `_id`, `email`, `firstName`, `lastName`, `fullName`, `accountStatus`, `avatar`

### Personal Information
- `DOB` - Date of birth (string or Date)
- `gender` - User's gender
- `pronouns` - Preferred pronouns
- `phone` - Phone number
- `phone_country_code` - Country code for phone (e.g., '+91')
- `secondaryEmail` - Secondary email address

### Location Information
- `country` - Country name
- `country_code` - ISO country code
- `countryMetadata` - Additional country metadata (flag, emoji, etc.)

### Preferences
- `defaultLanguage` - User's default language preference

### Additional Information
- `addresses` - Work and home addresses
- `about` - Personal interests (introduction, sports, music, books)
- `workAndEducationDetails` - Work experience and education history

### Example Usage

```typescript
const auth = await getAuth();
if (auth?.currentUser) {
  const user = auth.currentUser;
  
  // Personal info
  console.log('Name:', user.fullName);
  console.log('DOB:', user.DOB);
  console.log('Gender:', user.gender);
  console.log('Phone:', user.phone_country_code, user.phone);
  
  // Location
  console.log('Country:', user.country);
  
  // Preferences
  console.log('Language:', user.defaultLanguage);
}
```

## TypeScript Support

The SDK is written in TypeScript and includes type definitions. All exported functions and interfaces are fully typed.

## Browser Compatibility

The SDK requires:
- Modern browsers with ES6+ support
- `crypto-js` and `jwt-decode` libraries
- Access to `window`, `document`, and `fetch` APIs

## Security Notes

- The secret key used for encryption/decryption is embedded in the SDK. For production use, ensure your backend uses the same secret key.
- Tokens are stored in cookies with appropriate expiration times.
- Always use HTTPS in production to protect tokens in transit.
- The SDK now validates sessions server-side for enhanced security.
- Service access is checked at authentication time to prevent unauthorized access.
- Session validation includes optional IP and device fingerprinting checks (configurable on backend).

## License

MIT