@mirats/mirats-auth
v2.0.6
Published
Mamauth SDK for authentication and user management
Readme
Mamauth SDK
A TypeScript SDK for integrating Mamauth authentication and user management into your applications.
Package: @mirats/mirats-auth
Version: 2.0.7
Installation
npm install @mirats/[email protected]
# or
yarn add @mirats/[email protected]
# or
pnpm add @mirats/[email protected]Dependencies
The SDK requires the following peer dependencies:
crypto-js- For URL encryption/decryptionjwt-decode- For JWT token decoding
Configuration
The SDK automatically detects the Mamauth origin URL. You can override it by:
Environment Variable (Client-side):
process.env.NEXT_PUBLIC_MAMAUTH_ORIGIN = 'https://your-custom-domain.com'Global Variable (Client-side):
window.__MAMAUTH_ORIGIN__ = 'https://your-custom-domain.com'Environment Variable (Server-side):
process.env.MAMAUTH_ORIGIN = 'https://your-custom-domain.com'
Default: https://accounts.miratsgroup.com
Usage
Import the SDK
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:
// 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:
await signInWithService('https://myservice.example.com');Sign Up
Redirects user to the registration page:
await signUp();Forgot Password
Redirects user to the forgot password page:
await forgotPassword();Get Authentication Status
Get the current user's authentication status and user data with service access:
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:
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:
const { user, loading } = isLoggedIn();
if (user) {
console.log('User is logged in');
}Log Out
Log out the current user and clear cookies:
await logOut();Cookie Management
The SDK now uses token and GAS-SE cookies (primary) with frontendCookie as fallback for backward compatibility.
Get Cookie
const token = getCookie('token');Get Token (Helper)
const token = getToken(); // Gets token from 'token' cookie or 'frontendCookie' fallbackGet Session ID (Helper)
const sessionId = getSessionId(); // Gets session ID from 'GAS-SE' cookieSet Cookie
setCookie('token', 'your-token-value'); // 5 days expiration (default)Delete Cookie
deleteCookie('token');Clear All Auth Cookies (Helper)
clearAllAuthCookies(); // Clears token, GAS-SE, and frontendCookieUser Management
Get GAS ID
Get a user's GAS ID by email:
const result = await getGasId('[email protected]');
if (result) {
console.log('GAS ID:', result.gasId);
}Get Multiple GAS IDs
Get GAS IDs for multiple users (max 10):
const results = await getGasIds([
'[email protected]',
'[email protected]',
]);
// Returns: [{ email: '[email protected]', gasId: '...' }, ...]Invitations
Generate Invite Link
const link = inviteLink(
'[email protected]',
'user-id',
'John', // firstName (optional)
'Doe', // lastName (optional)
30 // days until expiration (default: 30)
);Send User Invite
const result = await sendUserInvite({
name: 'John Doe',
email: '[email protected]',
id: 'user-id',
organizationName: 'My Organization',
invitedBy: 'inviter-id',
days: 30, // optional
});
if (result.success) {
console.log('Invite sent successfully');
}Send Multiple Invites
const results = await sendUserInvites([
{
name: 'John Doe',
email: '[email protected]',
id: 'user-id-1',
organizationName: 'My Organization',
invitedBy: 'inviter-id',
},
{
name: 'Jane Smith',
email: '[email protected]',
id: 'user-id-2',
organizationName: 'My Organization',
invitedBy: 'inviter-id',
},
]);
// Returns only successful invitesService Management
Create Service
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:
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
const encrypted = encryptURL('https://example.com');Decrypt URL
const decrypted = decryptURL(encryptedUrl);Validate Email
if (isValidEmail('[email protected]')) {
console.log('Valid email');
}Add Days to Date
const futureDate = addDays(7); // 7 days from nowUser 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 genderpronouns- Preferred pronounsphone- Phone numberphone_country_code- Country code for phone (e.g., '+91')secondaryEmail- Secondary email address
Location Information
country- Country namecountry_code- ISO country codecountryMetadata- Additional country metadata (flag, emoji, etc.)
Preferences
defaultLanguage- User's default language preference
Additional Information
addresses- Work and home addressesabout- Personal interests (introduction, sports, music, books)workAndEducationDetails- Work experience and education history
Example Usage
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 viawindow.MAMAUTH_PUBLIC_API_URL)
Override Public API URL
You can override the public API base URL by setting a global variable:
// 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:
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 genderpronouns- Preferred pronounsphone- Phone numberphone_country_code- Country code for phone (e.g., '+91')secondaryEmail- Secondary email address
Location Information
country- Country namecountry_code- ISO country codecountryMetadata- Additional country metadata (flag, emoji, etc.)
Preferences
defaultLanguage- User's default language preference
Additional Information
addresses- Work and home addressesabout- Personal interests (introduction, sports, music, books)workAndEducationDetails- Work experience and education history
Example Usage
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-jsandjwt-decodelibraries- Access to
window,document, andfetchAPIs
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
