askit-auth-sdk
v1.0.0
Published
ASK IT Auth Server SDK — client library for authenticating users via the ASK IT Auth Server
Maintainers
Readme
@askit/auth-sdk
Client SDK for the ASK IT Auth Server — a lightweight, fully-typed TypeScript library that wraps the Auth Server REST API. Works in Node.js, browsers, and any modern JavaScript runtime.
Installation
npm install @askit/auth-sdk
# or
pnpm add @askit/auth-sdk
# or
yarn add @askit/auth-sdkQuick Start
import { AskITAuth } from "@askit/auth-sdk";
const auth = new AskITAuth({
baseUrl: "https://auth.askaihk.com",
});
// Login
const { token, user } = await auth.login({
email: "[email protected]",
password: "myPassword123",
});
console.log(`Welcome, ${user.full_name}!`); // Welcome, Murphy Lai!
console.log(`Role: ${user.role}`); // Role: admin
// Get current user (token is auto-stored after login)
const me = await auth.me();
console.log(me.email);API Reference
Constructor
const auth = new AskITAuth({
baseUrl: "https://auth.askaihk.com", // Required: Auth Server URL
token: "existing-jwt-token", // Optional: pre-set a token
});auth.login(credentials)
Login with email and password. Automatically stores the JWT token for subsequent requests.
const { token, user } = await auth.login({
email: "[email protected]",
password: "password123",
});| Returns | Type |
|---------|------|
| token | string — JWT token (7-day expiry) |
| user | AuthUser — user profile |
auth.register(data)
Register a new user. Sends a verification email via Resend.
await auth.register({
email: "[email protected]",
password: "password123",
full_name: "New User",
});auth.verifyEmail(data)
Verify email using the token from the verification email. Auto-stores the JWT if returned.
const result = await auth.verifyEmail({ token: "token-from-email" });
// result.token is auto-stored if presentauth.forgotPassword(data)
Send a password reset email.
await auth.forgotPassword({ email: "[email protected]" });
// Always returns success (prevents email enumeration)auth.resetPassword(data)
Reset password using the token from the reset email. Also used for the Set Password flow when an admin creates a user.
await auth.resetPassword({
token: "token-from-email",
password: "newPassword123",
});auth.me(token?)
Get the current authenticated user's profile. Uses the stored token by default.
const user = await auth.me();
// or with explicit token:
const user = await auth.me("some-jwt-token");| Field | Type |
|-------|------|
| id | number |
| email | string |
| full_name | string |
| role | "admin" \| "user" |
| is_active | boolean |
| created_at | string |
| updated_at | string |
auth.logout()
Logout and clear the stored token.
await auth.logout();auth.validateToken(token?)
Validate a token without throwing. Returns null if invalid.
const user = await auth.validateToken(token);
if (!user) {
// redirect to login
}Token Management
auth.setToken("jwt-token"); // Set token manually
auth.getToken(); // Get current token
auth.clearToken(); // Clear tokenRole Helpers
const user = await auth.me();
auth.isAdmin(user); // true if role === "admin"
auth.hasRole(user, "admin"); // check specific roleError Handling
All methods throw AuthError on failure:
import { AuthError } from "@askit/auth-sdk";
try {
await auth.login({ email: "[email protected]", password: "wrong" });
} catch (err) {
if (err instanceof AuthError) {
console.log(err.message); // "Invalid email or password"
console.log(err.status); // 401
}
}Integration with Expense Claim (Express/Node.js)
import { AskITAuth, AuthError } from "@askit/auth-sdk";
const auth = new AskITAuth({ baseUrl: "https://auth.askaihk.com" });
// Middleware to protect routes
async function requireAuth(req, res, next) {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).json({ error: "No token" });
const user = await auth.validateToken(token);
if (!user) return res.status(401).json({ error: "Invalid token" });
req.user = user;
next();
}
// Middleware to require admin role
async function requireAdmin(req, res, next) {
if (!auth.isAdmin(req.user)) {
return res.status(403).json({ error: "Admin access required" });
}
next();
}
// Usage
app.get("/api/reports", requireAuth, async (req, res) => {
// req.user is available here
res.json({ user: req.user });
});Integration with React Frontend
import { AskITAuth } from "@askit/auth-sdk";
const auth = new AskITAuth({ baseUrl: "https://auth.askaihk.com" });
// Login
async function handleLogin(email: string, password: string) {
const { token, user } = await auth.login({ email, password });
localStorage.setItem("auth_token", token);
return user;
}
// Restore session
async function restoreSession() {
const token = localStorage.getItem("auth_token");
if (!token) return null;
auth.setToken(token);
return auth.validateToken();
}
// Logout
async function handleLogout() {
await auth.logout();
localStorage.removeItem("auth_token");
}Local Installation (without npm publish)
If you haven't published to npm yet, you can install directly from the local build:
# From the SDK directory, pack it
cd /path/to/askit-auth-sdk
npm pack
# Creates: askit-auth-sdk-1.0.0.tgz
# In your other project
npm install /path/to/askit-auth-sdk/askit-auth-sdk-1.0.0.tgzPublishing to npm
# Login to npm
npm login
# Publish (builds automatically via prepublishOnly)
npm publish --access publicLicense
MIT © ASK IT
