1.1.3 • Published 4 months ago
@koompi/oauth v1.1.3
Koompi OAuth Client
A TypeScript client library for interacting with the Koompi OAuth service.
Installation
npm install @koompi/oauth
# or
yarn add @koompi/oauth
Configuration
First, you'll need to configure the client with your OAuth credentials:
import { SelOAuthClient } from '@koompi/oauth';
const client = new SelOAuthClient({
clientId: 'your-client-id', // Required
redirectUri: 'your-redirect-uri', // Required
clientSecret: 'your-client-secret', // Optional
baseUrl: 'https://oauth.koompi.org', // Optional, defaults to https://oauth.koompi.org
timeout: 30000, // Optional, defaults to 30000ms
});
API Reference
getLoginUrl
Generates the OAuth login URL for initiating the authentication flow. Uses the redirectUri from the client configuration.
const loginUrl = client.getLoginUrl();
// Returns: https://oauth.koompi.org/v1/oauth/login?client_id=your-client-id&redirect_uri=your-redirect-uri
getUserProfile
Retrieves the user profile using an access token.
const userProfile = await client.getUserProfile({
accessToken: string, // Required: The access token received from OAuth flow
clientSecret: string, // Required: Your application's client secret
});
// Example
const client = new SelOAuthClient({
clientId: 'your-client-id',
redirectUri: 'https://yourapp.com/callback',
clientSecret: 'your-client-secret',
});
const userProfile = await client.getUserProfile({
accessToken: 'received-access-token',
clientSecret: 'your-client-secret',
});
// Returns:
{
user: {
id: string;
fullname?: string;
first_name?: string;
last_name?: string;
email?: string;
phone?: string;
profile?: string;
telegram_id?: string | number;
wallet_address?: string;
};
state?: string;
}
Framework Examples
Next.js Example
// pages/auth/callback.tsx
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { SelOAuthClient } from '@koompi/oauth';
export default function CallbackPage() {
const router = useRouter();
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const handleCallback = async () => {
const { access_token } = router.query;
if (!access_token) return;
const client = new SelOAuthClient({
clientId: process.env.NEXT_PUBLIC_CLIENT_ID!,
redirectUri: process.env.NEXT_PUBLIC_REDIRECT_URI!,
clientSecret: process.env.CLIENT_SECRET!, // Keep this server-side only
});
try {
const userProfile = await client.getUserProfile({
accessToken: access_token as string,
clientSecret: process.env.CLIENT_SECRET!,
});
setUser(userProfile);
// Store user data or redirect
router.push('/dashboard');
} catch (err) {
setError(err.message);
router.push('/login?error=auth_failed');
}
};
handleCallback();
}, [router.query]);
if (error) return <div>Error: {error}</div>;
if (!user) return <div>Loading...</div>;
return <div>Welcome, {user.user.first_name || user.user.fullname}!</div>;
}
React Example
// hooks/useKoompiAuth.ts
import { useState, useCallback } from 'react';
import { SelOAuthClient } from '@koompi/oauth';
export function useKoompiAuth() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const client = new SelOAuthClient({
clientId: process.env.REACT_APP_CLIENT_ID!,
redirectUri: `${window.location.origin}/callback`,
clientSecret: process.env.REACT_APP_CLIENT_SECRET!,
});
const login = useCallback(() => {
const loginUrl = client.getLoginUrl();
window.location.href = loginUrl;
}, [client]);
const getUserProfile = useCallback(async (accessToken: string) => {
setLoading(true);
try {
const userProfile = await client.getUserProfile({
accessToken,
clientSecret: process.env.REACT_APP_CLIENT_SECRET!,
});
setUser(userProfile);
return userProfile;
} catch (err) {
setError(err.message);
throw err;
} finally {
setLoading(false);
}
}, [client]);
return { login, getUserProfile, user, loading, error };
}
// Usage in component
function LoginButton() {
const { login } = useKoompiAuth();
return <button onClick={login}>Login with Koompi</button>;
}
Node.js Example
// server/auth.ts
import express from 'express';
import { SelOAuthClient } from '@koompi/oauth';
const router = express.Router();
const client = new SelOAuthClient({
clientId: process.env.CLIENT_ID!,
redirectUri: 'https://your-app.com/api/auth/callback',
clientSecret: process.env.CLIENT_SECRET!,
});
// Handle OAuth callback
router.get('/auth/callback', async (req, res) => {
const { access_token } = req.query;
if (!access_token) {
return res.status(400).json({ error: 'No access token provided' });
}
try {
const userProfile = await client.getUserProfile({
accessToken: access_token as string,
clientSecret: process.env.CLIENT_SECRET!,
});
// Store user session
req.session.user = userProfile;
// Redirect to frontend
res.redirect('/dashboard');
} catch (error) {
console.error('Auth error:', error);
res.redirect('/login?error=auth_failed');
}
});
// Protected route example
router.get('/api/user/profile', async (req, res) => {
const { access_token } = req.headers;
if (!access_token) {
return res.status(401).json({ error: 'No access token provided' });
}
try {
const userProfile = await client.getUserProfile({
accessToken: access_token as string,
clientSecret: process.env.CLIENT_SECRET!,
});
res.json(userProfile);
} catch (error) {
res.status(401).json({ error: 'Invalid or expired token' });
}
});
export default router;
Error Handling
The client includes built-in error handling for common OAuth scenarios:
InvalidRequestError
: When required parameters are missingInvalidClientError
: When client credentials are invalidInvalidTokenError
: When the access token is invalidNetworkError
: When network requests failUserNotFoundError
: When the requested user is not foundProjectNotFoundError
: When the requested project is not foundOAuthClientError
: For other OAuth-related errors
Example error handling:
try {
const userProfile = await client.getUserProfile({
accessToken: 'your-token',
clientSecret: 'your-secret',
});
} catch (error) {
if (error instanceof InvalidTokenError) {
// Handle invalid token
} else if (error instanceof NetworkError) {
// Handle network issues
}
// Handle other errors
}
Types
The package includes TypeScript types for better development experience:
interface OAuthConfig {
clientId: string; // Required
redirectUri: string; // Required
clientSecret?: string; // Optional
baseUrl?: string; // Optional
timeout?: number; // Optional
}
interface UserProfile {
id: string;
fullname?: string;
first_name?: string;
last_name?: string;
email?: string;
phone?: string;
profile?: string;
telegram_id?: string | number;
wallet_address?: string;
}
interface UserResponse {
user: UserProfile;
state?: string;
}
License
MIT