@mahdaad/auth-nodejs-sdk
v1.0.4
Published
TypeScript/JavaScript SDK for Auth Service with authentication, user management, and service role operations
Readme
@mahdaad/auth-nodejs-sdk
TypeScript/JavaScript SDK for Auth Service with authentication, user management, and service role operations.
Installation
npm install @mahdaad/auth-nodejs-sdkRequirements
- Node.js >= 18.0.0
- Redis (optional, for caching)
Quick Start
import AuthSDK from "@mahdaad/auth-nodejs-sdk";
// Initialize SDK
const sdk = new AuthSDK("http://localhost:3000");
// Login
const result = await sdk.auth.login("[email protected]", "password123");
console.log("Access Token:", result.accessToken);
// Get current user
const user = await sdk.user.getUser();
console.log("User:", user);Features
- ✅ TypeScript Support - Full type definitions included
- ✅ User authentication (register, login, logout)
- ✅ OTP authentication (email/SMS)
- ✅ Token management (refresh, revoke)
- ✅ User profile management
- ✅ Redis caching support (30 seconds TTL for user data)
- ✅ Service role operations (admin functions)
- ✅ Native Node.js fetch (no external dependencies except Redis)
TypeScript Support
This package is written in TypeScript and includes full type definitions:
import AuthSDK, { type User, type AuthResponse } from "@auth-service/sdk";
const sdk = new AuthSDK("http://localhost:3000");
const user: User = await sdk.user.getUser();Usage
Basic Authentication
import AuthSDK from "@mahdaad/auth-nodejs-sdk";
const sdk = new AuthSDK("http://localhost:3000");
// Register
const registerResult = await sdk.auth.register(
"[email protected]",
"Password123"
);
// Login
const loginResult = await sdk.auth.login("[email protected]", "Password123");
sdk.setAccessToken(loginResult.accessToken);
// Get current user
const user = await sdk.user.getUser();
// Logout
await sdk.auth.logout(loginResult.accessToken, loginResult.refreshToken);With Redis Caching
import AuthSDK from "@mahdaad/auth-nodejs-sdk";
// Initialize with Redis
const sdk = new AuthSDK("http://localhost:3000", "redis://localhost:6379");
// Login
const loginResult = await sdk.auth.login("[email protected]", "Password123");
sdk.setAccessToken(loginResult.accessToken);
// First call - fetches from API
const user1 = await sdk.user.getUser();
// Second call within 30 seconds - uses Redis cache
const user2 = await sdk.user.getUser(); // Cached!
// Disconnect Redis when done
await sdk.disconnect();Service Role Operations
import AuthSDK from "@mahdaad/auth-nodejs-sdk";
const sdk = new AuthSDK("http://localhost:3000");
// Create service role client
const serviceClient = sdk.createServiceRoleClient("your-service-role-key");
// Update user profile by ID
await serviceClient.updateProfileById("user-id", {
first_name: "John",
last_name: "Doe",
name: "John Doe",
});
// Get multiple users by IDs
const users = await serviceClient.getUsersByIds(["id1", "id2"]);
// Get access token for a user
const tokenResult = await serviceClient.getAccessToken("user-id");
// Logout a user by ID
await serviceClient.logoutUserById("user-id");
// Create a user
const user = await serviceClient.createUser("[email protected]", "Password123", {
first_name: "John",
last_name: "Doe",
name: "John Doe",
mobile: "+1234567890",
avatar: "https://example.com/avatar.jpg",
});
// Or create a user with only mobile
const user = await serviceClient.createUser(undefined, undefined, {
first_name: "John",
last_name: "Doe",
name: "John Doe",
mobile: "+1234567890",
avatar: "https://example.com/avatar.jpg",
});Token Management
// Set access token manually
sdk.setAccessToken("your-access-token");
// Use SDK with the token
const user = await sdk.user.getUser();
// Refresh token
const refreshResult = await sdk.auth.refreshToken("refresh-token");
sdk.setAccessToken(refreshResult.accessToken);
// Clear token
sdk.clearAccessToken();OTP Authentication
// Request OTP
await sdk.auth.requestOTP("[email protected]", "+1234567890");
// Verify OTP
const result = await sdk.auth.verifyOTP(
"[email protected]",
"+1234567890",
"123456"
);
sdk.setAccessToken(result.accessToken);API Reference
AuthSDK Class
Constructor
new AuthSDK(baseURL?: string, redisOptions?: string | RedisOptions | null)baseURL(string, optional): Base URL of the auth service API (default: "http://localhost:3000")redisOptions(string | object, optional): Redis connection options
Methods
setAccessToken(token: string): void- Set access token for requestsclearAccessToken(): void- Clear access tokencreateServiceRoleClient(secretKey: string): ServiceRoleClient- Create service role clientdisconnect(): Promise<void>- Disconnect Redis connection
AuthService
register(email: string, password: string): Promise<AuthResponse>- Register a new userlogin(email: string, password: string): Promise<AuthResponse>- Login userlogout(accessToken?: string, refreshToken?: string): Promise<{ message: string }>- Logout userrefreshToken(refreshToken: string): Promise<{ accessToken: string }>- Refresh access tokenrequestOTP(email?: string, phone?: string): Promise<{ message: string }>- Request OTP codeverifyOTP(email: string | undefined, phone: string | undefined, code: string): Promise<AuthResponse>- Verify OTP codegetGoogleAuthUrl(): string- Get Google OAuth URL
UserService
getUser(accessToken?: string): Promise<User>- Get current user (with Redis caching)
ServiceRoleClient
updateProfileById(userId: string, profileData: UpdateProfileData): Promise<User>- Update user profilegetUsersByIds(userIds: string[]): Promise<User[]>- Get users by IDslogoutUserById(userId: string): Promise<{ message: string }>- Logout user by IDgetAccessToken(userId: string): Promise<TokenResponse>- Get access token for user
Type Definitions
import type {
AuthResponse,
User,
UpdateProfileData,
TokenResponse,
RedisOptions,
RedisClient,
} from "@mahdaad/auth-nodejs-sdk";Examples
See examples/basic-usage.js for comprehensive examples.
Environment Variables
AUTH_API_URL=http://localhost:3000
REDIS_URL=redis://localhost:6379
SERVICE_ROLE_KEY=your-service-role-keyError Handling
All methods throw errors that can be caught:
try {
await sdk.auth.login("[email protected]", "password");
} catch (error) {
if (error instanceof Error) {
console.error("Login failed:", error.message);
}
}Building from Source
# Install dependencies
npm install
# Build TypeScript
npm run build
# Watch mode
npm run build:watchPublishing
# Build before publishing
npm run build
# Publish to npm
npm publish --access publicLicense
ISC
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
