@qyh213/easyauth-client
v1.0.0-beta.1
Published
Official client library for Easy Auth - Multi-tenant authentication-as-a-service
Maintainers
Readme
@easyauth/client
Official client library for Easy Auth - Multi-tenant authentication-as-a-service platform.
Features
- 🔐 Simple Authentication - Login/logout with tokens
- 🛡️ Token Validation - Validate tokens with easy-auth service
- 👥 User Management - Create, list, delete users
- 🔑 API Key Management - Create and revoke service API keys
- ⚛️ React Integration - Hooks and context for React apps
- ▲ Next.js Support - Middleware and server-side helpers
- 📘 TypeScript - Full type definitions included
Installation
npm install @easyauth/client
# or
yarn add @easyauth/client
# or
pnpm add @easyauth/clientQuick Start
1. Initialize the Client
import { EasyAuthClient } from "@easyauth/client";
const client = new EasyAuthClient({
baseUrl: "https://auth.yourservice.com",
apiKey: "ak-xxxxx", // Your service API key
});2. Login a User
// Login and store token
const token = await client.login({
email: "[email protected]",
password: "password123",
});
console.log("Logged in! Token expires:", token.expiresAt);3. Validate Token
// Check if current token is valid
const result = await client.validate();
if (result.valid) {
console.log("User is authenticated!");
console.log("Service:", result.serviceId);
console.log("Scope:", result.scope); // "user", "admin", or "service"
} else {
console.log("Invalid token:", result.error);
}4. Logout
await client.logout();
console.log("Logged out!");React Integration
Setup Provider
import { EasyAuthProvider } from "@easyauth/client/react";
function App() {
return (
<EasyAuthProvider
config={{
baseUrl: "https://auth.yourservice.com",
apiKey: "ak-xxxxx",
}}
>
<YourApp />
</EasyAuthProvider>
);
}Use Hooks
import {
useIsAuthenticated,
useUser,
useAuthActions,
LoginForm
} from "@easyauth/client/react";
function Dashboard() {
const isAuthenticated = useIsAuthenticated();
const user = useUser();
const { logout } = useAuthActions();
if (!isAuthenticated) {
return <LoginForm onSuccess={() => console.log("Logged in!")} />;
}
return (
<div>
<h1>Welcome, {user?.email}!</h1>
<button onClick={logout}>Logout</button>
</div>
);
}Protected Component
import { Protected } from "@easyauth/client/react";
function App() {
return (
<Protected fallback={<p>Please login...</p>}>
<SecretContent />
</Protected>
);
}Next.js Integration
Middleware Setup
Create middleware.ts in your project root:
import { createEasyAuthMiddleware } from "@easyauth/client/next";
export const middleware = createEasyAuthMiddleware({
baseUrl: process.env.EASY_AUTH_URL!,
protectedPaths: ["/dashboard", "/profile", "/settings"],
authPaths: ["/login", "/signup"],
loginPath: "/login",
dashboardPath: "/dashboard",
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};API Route Protection
import { NextResponse } from "next/server";
import { withAuth, withScope } from "@easyauth/client/next";
// Any authenticated user
export const GET = withAuth(
{ baseUrl: process.env.EASY_AUTH_URL! },
async (request, { userId, scope }) => {
return NextResponse.json({
message: "Hello user!",
userId
});
}
);
// Admin only
export const POST = withScope(
{ baseUrl: process.env.EASY_AUTH_URL! },
["admin"], // Only admins
async (request, { userId }) => {
return NextResponse.json({
message: "Admin action performed"
});
}
);Server-Side Usage
import { createServerClient } from "@easyauth/client/next";
const serverClient = createServerClient({
baseUrl: process.env.EASY_AUTH_URL!,
apiKey: process.env.EASY_AUTH_API_KEY!, // Server-only
});
// Create a user
const user = await serverClient.createUser({
email: "[email protected]",
password: "secure123",
});User Management
Create User (Admin)
const user = await client.createUser({
email: "[email protected]",
password: "securePassword123",
});
console.log("Created user:", user.userId);List Users
const users = await client.listUsers();
users.forEach(user => {
console.log(`${user.email} (${user.userId})`);
});Delete User
await client.deleteUser("user-xxxxx");API Key Management
Create API Key
const key = await client.createApiKey({
name: "Production Backend",
scope: "service",
tpsLimit: 1000,
});
console.log("New API Key (save this!):", key.apiKey);
// ⚠️ Only shown once!List API Keys
const keys = await client.listApiKeys();
keys.forEach(key => {
console.log(`${key.name}: ${key.keyId} (${key.revoked ? "revoked" : "active"})`);
});Revoke API Key
await client.revokeApiKey("key-xxxxx");Service Onboarding
For platform admins who onboard new services:
import { EasyAuthClient } from "@easyauth/client";
// Use master admin key
const adminClient = new EasyAuthClient({
baseUrl: "https://auth.yourservice.com",
});
const service = await adminClient.onboardService(
{
serviceName: "my-new-service",
ownerEmail: "[email protected]",
},
process.env.MASTER_ADMIN_KEY! // Master onboarding key
);
console.log("Service ID:", service.serviceId);
console.log("Admin API Key (save this!):", service.serviceAdminApiKey);Token Storage
By default, tokens are stored in localStorage. For custom storage:
import {
EasyAuthClient,
MemoryTokenStorage
} from "@easyauth/client";
// Server-side or memory-only storage
const client = new EasyAuthClient(
{ baseUrl: "...", apiKey: "..." },
new MemoryTokenStorage()
);Create custom storage:
import { TokenStorage } from "@easyauth/client";
class CookieStorage implements TokenStorage {
getToken(): string | null {
// Read from cookies
}
setToken(token: string): void {
// Set cookie
}
removeToken(): void {
// Delete cookie
}
}Error Handling
import { EasyAuthError } from "@easyauth/client";
try {
await client.login({ email, password });
} catch (error) {
if (error instanceof EasyAuthError) {
console.log("Error code:", error.code);
console.log("Status:", error.statusCode);
console.log("Message:", error.message);
}
}Common error codes:
MISSING_API_KEY- API key not configuredNETWORK_ERROR- Connection failedUNKNOWN_ERROR- Server returned error
Complete Example: Protected API
// middleware.ts
import { createEasyAuthMiddleware } from "@easyauth/client/next";
export const middleware = createEasyAuthMiddleware({
baseUrl: process.env.EASY_AUTH_URL!,
protectedPaths: ["/api/protected"],
});
export const config = {
matcher: "/api/:path*",
};
// app/api/protected/route.ts
import { NextResponse } from "next/server";
import { withAuth } from "@easyauth/client/next";
export const GET = withAuth(
{ baseUrl: process.env.EASY_AUTH_URL! },
async (request, { userId, scope }) => {
// User is authenticated!
return NextResponse.json({
message: "Secret data",
userId,
scope,
});
}
);TypeScript Support
Full TypeScript definitions are included:
import {
EasyAuthClient,
AuthToken,
User,
ApiKey,
ValidationResult,
EasyAuthConfig
} from "@easyauth/client";License
MIT License - see LICENSE file for details.
Contributing
Contributions welcome! Please read our Contributing Guide.
