@zcatalyst/auth
v0.0.3
Published
JavaScript SDK for Catalyst Authentication - Node.js and Browser Support
Maintainers
Readme
@zcatalyst/auth
JavaScript SDK for Catalyst Authentication - Node.js and Browser Support
Overview
The @zcatalyst/auth package provides JavaScript/TypeScript methods for Catalyst authentication and user-management APIs. It has Node.js and browser entry points.
Operation Scope
Both the Node and browser entry points export the same class name (UserManagement). The Node entry point exposes the admin-augmented surface in addition to the user surface; the browser entry point exposes only the user surface.
| Operation | UserManagement method | Available in |
|---|---|---|
| Get the currently signed-in user | getCurrentUser() | Node + Browser (user) |
| Reset password for the current user | resetPassword() | Node + Browser (user) |
| List every user in the project | getAllUsers() | Node only (admin) |
| Get a specific user's details | getUserDetails(id) | Node only (admin) |
| Delete a user | deleteUser(id) | Node only (admin) |
| Register a new user | registerUser(payload) | Node only (admin) |
| List orgs the user belongs to | getAllOrgs() | Node only (admin) |
| Add a user to an org | addUserToOrg(payload) | Node only (admin) |
| Inspect a pending signup validation request | getSignupValidationRequest(id) | Node only (admin) |
| Mint a custom token for a user | generateCustomToken(payload) | Node only (admin) |
| Enable / disable a user | updateUserStatus(id, status) | Node only (admin) |
| Update a user's profile fields | updateUserDetails(id, payload) | Node only (admin) |
Prerequisites
Before using this SDK, ensure you have:
- A Catalyst project set up
- Your Project ID (unique identifier) and Project Key from Project Settings
- Catalyst CLI installed (for Node.js development)
- At least one authentication type configured in your project
Installation
To install this package, simply type add or install @zcatalyst/auth using your favorite package manager:
npm install @zcatalyst/authyarn add @zcatalyst/authpnpm add @zcatalyst/auth
Getting Started
Import
The Catalyst SDK is modularized by Components.
To handle authentication, you only need to import the zcAuth function:
Environment-Specific Imports
For explicit environment targeting:
Node.js Environment:
// CommonJS
const { zcAuth, UserManagement } = require("@zcatalyst/auth/node");
// ES6+
import { zcAuth, UserManagement } from "@zcatalyst/auth/node";Browser Environment:
// CommonJS
const { zcAuth, UserManagement } = require("@zcatalyst/auth/web");
// ES6+
import { zcAuth, UserManagement } from "@zcatalyst/auth/web";Package Root Import
// CommonJS
const { zcAuth } = require("@zcatalyst/auth");// ES6+
import { zcAuth } from "@zcatalyst/auth";Usage
Node.js Environment (Server-Side)
For server-side authentication in Catalyst functions, initialize the SDK with Catalyst request headers or a custom credential:
import { zcAuth } from "@zcatalyst/auth/node";
// Initialize with Catalyst request headers
const app = await zcAuth.init(req);Initialize with Scope:
import { zcAuth } from "@zcatalyst/auth/node";
await zcAuth.init(req, {
type: 'advancedio',
appName: 'my-app',
scope: 'admin'
});Browser Environment (Client-Side)
For client-side authentication, use the browser-specific methods to implement sign-in flows:
import { zcAuth } from "@zcatalyst/auth/web";
// Embedded Authentication - Sign in with iframe
await zcAuth.signIn('element-id', {
redirectUrl: 'https://your-app.com/dashboard',
cssUrl: 'https://your-app.com/custom-login.css' // Optional: Custom styling
});
// Check if user is authenticated
const isAuthenticated = await zcAuth.isUserAuthenticated();
if (isAuthenticated) {
console.log('User is logged in');
}
// Sign out user
await zcAuth.signOut('/login');Hosted Authentication:
Redirect users to Catalyst's hosted authentication page:
import { zcAuth } from "@zcatalyst/auth/web";
// Redirect to hosted sign-in page
await zcAuth.hostedSignIn('https://your-app.com/dashboard');Environment Support
Use the entry point that matches your runtime:
| Environment | Available Methods | Context |
|------------|------------------|----------|
| Node.js | init(), getApp() | Server-side functions and backend code |
| Browser | signIn(), signOut(), isUserAuthenticated(), hostedSignIn(), signUp() | Client-side web applications |
Async/await
We recommend using await operator to wait for the promise returned by authentication operations:
try {
await zcAuth.signIn('login-container');
} catch (error) {
console.error('Authentication failed:', error);
} finally {
// Cleanup or redirect logic
}Error Handling
The SDK throws error objects with information such as message, statusCode, and name when available:
try {
await zcAuth.signIn('login-container');
} catch (error) {
console.error({
message: error.message, // Error description
statusCode: error.statusCode, // HTTP status code
name: error.name // Error type
});
}Error Types:
CatalystAuthenticationError: Authentication-specific errorsCatalystUserManagementError: User management operation errors
Method Details
Authentication (zcAuth)
The zcAuth object is the main interface for authentication operations. Methods available depend on the execution environment.
Environment Detection: Import from
@zcatalyst/auth/nodefor server-side or@zcatalyst/auth/webfor client-side to explicitly target an environment.
Node.js Methods
These methods are available when running in a Node.js environment (server-side functions, backend services).
Initialize the Catalyst SDK with your project credentials. This is required before accessing any Catalyst components.
Parameters:
options(object): Project configurationprojectId(string): Your Catalyst Project IDprojectKey(string): Your Project Secret Keyenvironment(string, optional):'development'or'production'
config(object, optional): Additional configurationtype(string): Authentication type ('auto', etc.)appName(string): Your application namescope(string):'user'or'admin'(default:'admin')
Returns: Promise
Example:
import { zcAuth } from "@zcatalyst/auth/node";
await zcAuth.init({
headers: req.headers
}, {
type: 'advancedio',
appName: 'my-app',
scope: 'admin'
});Retrieves an app instance by name.
Parameters:
name(string): The name of the app
Returns: Promise
Example:
const app = await zcAuth.getApp('your_app_name');Browser Methods
These methods are available when running in a browser environment (client-side web applications, SPAs).
Note: For embedded authentication, you must specify a DOM element ID where the authentication iframe will be loaded.
Initiates Embedded Authentication by displaying an authentication iframe in the specified DOM element.
Parameters:
id(string): DOM element ID where the login iframe will be loaded (e.g.,'login-container')config(object, optional): Sign-in configurationredirectUrl(string): URL to redirect after successful authenticationserviceUrl(string): Alternative service URL for authenticationcssUrl(string): Custom CSS URL for styling the login iframesignInProvidersOnly(boolean): Show only social login providers (hide email/password)forgotPasswordId(string): DOM element ID for forgot password iframeforgotPasswordCssUrl(string): Custom CSS URL for forgot password page
Returns: Promise
HTML Setup:
<!-- Create a container for the authentication iframe -->
<div id="login-container"></div>Example:
import { zcAuth } from "@zcatalyst/auth/web";
await zcAuth.signIn('login-container', {
redirectUrl: 'https://your-app.com/callback',
serviceUrl: 'https://your-app.com/service'
});Redirects users to Catalyst's Hosted Authentication page for sign-in.
Parameters:
redirectUrl(string, optional): URL to redirect to after authentication (defaults to'/')
Returns: Promise
Example:
import { zcAuth } from "@zcatalyst/auth/web";
await zcAuth.hostedSignIn('/index.html'); // redirect urlConfigures the browser auth protocol to use JWT and stores a callback function.
Parameters:
callbackFn(function): Callback function stored for JWT fetch handling
Returns: void
Example:
import { zcAuth } from "@zcatalyst/auth/web";
zcAuth.signinWithJwt(() => {
console.log('JWT authentication configured');
});Registers a new user to your application. Catalyst will send an email invite to the user containing a URL to set up their password.
Parameters:
body(object): User signup detailsemail_id(string, required): User's email addresslast_name(string, required): User's last namefirst_name(string, optional): User's first nameplatform_type(string, optional): Platform type (defaults to'web')redirect_url(string, optional): Redirect URL after signup completion
Returns: Promise
Notes:
- User receives an email invitation to complete the signup process
- After setting their password, users are redirected to the specified URL
- Requires Public Signup to be enabled in your project
Example:
import { zcAuth } from "@zcatalyst/auth/web";
await zcAuth.signUp({
email_id: '[email protected]',
first_name: 'John',
last_name: 'Doe',
platform_type: 'web',
redirect_url: 'https://your-app.com/welcome'
});Signs out the currently authenticated user and redirects to the specified URL.
Parameters:
redirectURL(string, optional): URL to redirect after sign out (defaults to '/')
Returns: Promise
Example:
import { zcAuth } from "@zcatalyst/auth/web";
await zcAuth.signOut('/login');Checks if a user is currently authenticated.
Parameters:
org_id(string, optional): Organization ID to check authentication for
Returns: Promise - Returns user data if authenticated, false otherwise
Example:
import { zcAuth } from "@zcatalyst/auth/web";
const isAuthenticated = await zcAuth.isUserAuthenticated();
if (isAuthenticated) {
console.log('User is authenticated', isAuthenticated);
}
// Check with organization ID
const isAuthenticatedInOrg = await zcAuth.isUserAuthenticated('org-id');Retrieves the details of the currently authenticated user.
Parameters:
org_id(string, optional): Organization ID to get user details for
Returns: Promise<Record<string, unknown>>
Example:
import { zcAuth } from "@zcatalyst/auth/web";
const userDetails = await zcAuth.getProjectUserDetails();
console.log(userDetails);
// With organization ID
const userDetailsInOrg = await zcAuth.getProjectUserDetails('org-id');Changes the password for the currently authenticated user.
Parameters:
oldPassword(string): Current passwordnewPassword(string): New password
Returns: Promise
Example:
import { zcAuth } from "@zcatalyst/auth/web";
await zcAuth.changePassword('oldPassword123', 'newPassword456');
console.log('Password changed successfully');User Management
The User Management feature enables you to manage application users, configure roles, and control access permissions. This SDK provides methods to add, update, delete, and retrieve user information.
Import User Management:
Node.js Environment:
import { UserManagement, USER_STATUS } from "@zcatalyst/auth/node";Browser Environment:
import { UserManagement } from "@zcatalyst/auth/web";Note:
USER_STATUSis only available from the node entry point (@zcatalyst/auth/node).
Key Capabilities:
- Add and manage end-users
- Enable/disable user accounts
- Assign and manage user roles
- Generate custom authentication tokens
- Send password reset emails
Common Methods (Available in Both Environments)
Retrieves the details of the currently authenticated user.
Returns: Promise
User Object Properties:
user_id: Unique user identifieremail_id: User's email addressfirst_name,last_name: User's namerole_id: Assigned role IDstatus: Account status ('enabled'or'disabled')created_time: Account creation timestamp
Example:
const userManagement = new UserManagement();
const user = await userManagement.getCurrentUser();
console.log(user.email_id);Sends a password reset request for the specified email.
Parameters:
email(string): User's email addressresetConfig(object): Configuration objectplatform_type(string, required): Platform type (e.g., 'web')
Returns: Promise
Example:
const message = await userManagement.resetPassword(
"[email protected]",
{ platform_type: "web" }
);
console.log(message);Admin Methods (Node.js Only)
These methods provide administrative control over users and are only available in Node.js (server-side) with Admin scope. They allow you to programmatically manage users, roles, and permissions.
Requirements:
- Node.js environment
- Admin scope initialization
- Appropriate role permissions configured
Usage:
import { UserManagement } from "@zcatalyst/auth/node";
const userManagement = new UserManagement();Note: These methods perform operations that require elevated privileges. Ensure proper authentication and authorization before exposing these in your APIs.
Retrieves all users in your Catalyst project or a specific organization.
Parameters:
orgId(string, optional): Organization ID to filter users by organization
Returns: Promise<Array>
Example:
// Get all users in project
const users = await userManagement.getAllUsers();
console.log(users);
// Get all users in a specific organization
const orgUsers = await userManagement.getAllUsers('123456789');Retrieves details of a specific user by ID.
Parameters:
id(string): User ID
Returns: Promise
Example:
const userDetails = await userManagement.getUserDetails('987654321');
console.log(userDetails);Deletes a user from the project.
Parameters:
id(string): User ID
Returns: Promise - Returns true if deletion was successful
Example:
const isDeleted = await userManagement.deleteUser('987654321');
console.log(isDeleted); // trueProgrammatically registers a new user in your Catalyst project. The user receives an email invitation to set up their password.
Parameters:
signupConfig(object): Signup configurationplatform_type(string, required): Platform type ('web','ios','android')
userDetails(object): User detailsemail_id(string, required): User's email addressfirst_name(string, required): User's first namelast_name(string, optional): User's last namerole_id(string, optional): Role ID to assign
Returns: Promise
Example:
const newUser = await userManagement.registerUser(
{ platform_type: 'web' },
{
email_id: '[email protected]',
first_name: 'John',
role_id: '1234556'
}
);
console.log(newUser);Retrieves all organization IDs associated with the project.
Returns: Promise<Array>
Example:
const orgIds = await userManagement.getAllOrgs();
console.log(orgIds);Adds a user to a specific organization within your Catalyst project. Organizations in Catalyst allow you to segment users for multi-tenant applications.
Parameters:
signupConfig(object): Signup configurationplatform_type(string, required): Platform type ('web','ios','android')
userDetails(object): User detailsemail_id(string, required): User's email addressfirst_name(string, required): User's first namelast_name(string, optional): User's last nameorg_id(string, required): Organization ID (also known as ZAAID)
Returns: Promise
Example:
const user = await userManagement.addUserToOrg(
{ platform_type: 'web' },
{
email_id: '[email protected]',
first_name: 'Jane',
org_id: '12345'
}
);
console.log(user);Generates a custom authentication token for a user. Used for implementing custom authentication flows or integrating with third-party systems.
Parameters:
customTokenDetails(object): Details for token generationuser_id(string): User ID for whom to generate the token
Returns: Promise
Example:
const token = await userManagement.generateCustomToken({ user_id: '12345' });
console.log(token);Enables or disables a user account. Disabled users cannot access the application.
Parameters:
id(string): User IDuserStatus(USER_STATUS): Status to setUSER_STATUS.ENABLE: Enable user accountUSER_STATUS.DISABLE: Disable user account
Returns: Promise - Returns true if status was updated successfully
Example:
import { UserManagement, USER_STATUS } from "@zcatalyst/auth/node";
const userManagement = new UserManagement();
const statusChanged = await userManagement.updateUserStatus(
'12345',
USER_STATUS.ENABLE
);
console.log(statusChanged);Updates details for a specific user.
Parameters:
id(string): User IDuserDetails(object): Details to updateemail_id(string, required): User's email addressrole_id(string): Role ID- Other user properties
Returns: Promise
Example:
const updatedUser = await userManagement.updateUserDetails('12345', {
email_id: '[email protected]',
role_id: 'admin'
});
console.log(updatedUser);Retrieves signup validation request details from a Basic I/O request object.
Parameters:
bioReq(object): Basic I/O request object withgetArgumentmethod
Returns: ICatalystSignupValidationReq | undefined
Example:
const request = userManagement.getSignupValidationRequest(bioReq);
if (request) {
console.log(request);
}Resources
Contributing
See CONTRIBUTING for more information on how to get started.
License
This SDK is distributed under the Apache License 2.0. See LICENSE file for more information.
