ocean-captcha
v1.0.3
Published
A beautiful puzzle slider captcha component for React applications
Maintainers
Readme
OceanCaptcha
A beautiful puzzle slider captcha component for React applications. This package provides a secure and user-friendly captcha verification system that can be easily integrated into any React project.
Features
- 🎨 Beautiful UI with smooth animations
- 🔒 Secure verification with backend integration
- 📱 Mobile-friendly touch support
- 🌙 Dark mode support
- ⚡ Lightweight and performant
- 🔧 Easy configuration with secret key support
- 📦 TypeScript support
Installation
npm install ocean-captcha
# or
yarn add ocean-captcha
# or
pnpm add ocean-captchaQuick Start
1. Configure the package
First, configure the package with your backend URL and secret key:
import { configure } from 'ocean-captcha';
configure({
backendUrl: 'https://your-backend-url.com', // Optional, defaults to http://localhost:4090
secretKey: 'your-secret-key-here', // Required
});2. Use the component
import React, { useState } from 'react';
import { Captcha } from 'ocean-captcha';
function MyComponent() {
const [isVerified, setIsVerified] = useState(false);
const [verificationCode, setVerificationCode] = useState<string | null>(null);
return (
<div>
<Captcha
onVerify={(verified, code) => {
setIsVerified(verified);
if (code) {
setVerificationCode(code);
}
}}
onError={(error) => {
console.error('Captcha error:', error);
}}
/>
{isVerified && (
<p>Verification successful! Code: {verificationCode}</p>
)}
</div>
);
}API Reference
configure(config: OceanCaptchaConfig)
Configures the package with backend URL and secret key.
Parameters:
config.backendUrl(optional): Your backend API URL. Defaults tohttp://localhost:4090config.secretKey(required): Your secret key for API authentication
Example:
import { configure } from 'ocean-captcha';
configure({
backendUrl: 'https://api.example.com',
secretKey: 'your-secret-key',
});<Captcha /> Component
The main captcha component.
Props:
onVerify: (isVerified: boolean, verificationCode?: string) => void- Callback when verification completesonError?: (error: string) => void- Optional error callbackclassName?: string- Optional CSS class name
Example:
<Captcha
onVerify={(verified, code) => {
if (verified) {
console.log('Verified! Code:', code);
}
}}
onError={(error) => {
console.error('Error:', error);
}}
className="my-custom-class"
/>API Functions
generateCaptchaChallenge()
Generates a new captcha challenge.
Returns: Promise<GenerateChallengeResponse>
Example:
import { generateCaptchaChallenge } from 'ocean-captcha';
const result = await generateCaptchaChallenge();
if (result.success) {
console.log('Challenge ID:', result.challengeId);
}verifyCaptcha(challengeId, sliderValue, metadata?)
Verifies a captcha challenge.
Parameters:
challengeId: string- The challenge ID fromgenerateCaptchaChallengesliderValue: number- The slider position (0-100)metadata?: { timeSpent?: number; interactionCount?: number }- Optional metadata
Returns: Promise<VerifyCaptchaResponse>
Example:
import { verifyCaptcha } from 'ocean-captcha';
const result = await verifyCaptcha(challengeId, 75, {
timeSpent: 5,
interactionCount: 1,
});
if (result.success) {
console.log('Verification code:', result.verificationCode);
}verifyCaptchaCode(verificationCode)
Verifies a previously obtained verification code (useful for multiple API calls).
Parameters:
verificationCode: string- The verification code from a previous verification
Returns: Promise<VerifyCodeResponse>
Example:
import { verifyCaptchaCode } from 'ocean-captcha';
const result = await verifyCaptchaCode(verificationCode);
if (result.success) {
console.log('Code is still valid');
}Backend Integration
Your backend should implement the following endpoints:
POST /auth/captcha/generate
Generates a new captcha challenge.
Headers:
X-Captcha-Secret: Your secret key (optional, but recommended)
Response:
{
"success": true,
"challengeId": "challenge-id-here"
}POST /auth/captcha/verify
Verifies a captcha challenge.
Headers:
X-Captcha-Secret: Your secret key (optional, but recommended)Content-Type:application/json
Body:
{
"challengeId": "challenge-id",
"sliderValue": 75,
"timeSpent": 5,
"interactionCount": 1
}Response:
{
"success": true,
"verificationCode": "verification-code-here"
}POST /auth/captcha/verify-code
Verifies a verification code.
Headers:
X-Captcha-Secret: Your secret key (optional, but recommended)Content-Type:application/json
Body:
{
"verificationCode": "verification-code-here"
}Response:
{
"success": true
}GET /auth/captcha/image/{challengeId}
Returns the background image for the captcha.
GET /auth/captcha/puzzle/{challengeId}
Returns the puzzle piece image for the captcha.
Complete Example
import React, { useState, useEffect } from 'react';
import { configure, Captcha } from 'ocean-captcha';
// Configure once at app startup
configure({
backendUrl: 'https://api.example.com',
secretKey: process.env.REACT_APP_CAPTCHA_SECRET || 'your-secret-key',
});
function LoginForm() {
const [isCaptchaVerified, setIsCaptchaVerified] = useState(false);
const [verificationCode, setVerificationCode] = useState<string | null>(null);
const [showCaptcha, setShowCaptcha] = useState(false);
const handleLogin = async () => {
if (!isCaptchaVerified) {
setShowCaptcha(true);
return;
}
// Use verificationCode in your login request
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'password',
captchaCode: verificationCode,
}),
});
// Handle response...
};
return (
<div>
<form onSubmit={(e) => { e.preventDefault(); handleLogin(); }}>
{/* Your form fields */}
<button type="submit">Login</button>
</form>
{showCaptcha && (
<div className="modal">
<Captcha
onVerify={(verified, code) => {
setIsCaptchaVerified(verified);
if (code) {
setVerificationCode(code);
setShowCaptcha(false);
}
}}
onError={(error) => {
console.error('Captcha error:', error);
}}
/>
</div>
)}
</div>
);
}Styling
The component uses Tailwind CSS classes. Make sure you have Tailwind CSS installed and configured in your project, or include the component's styles in your build process.
If you're not using Tailwind CSS, you can override the styles using the className prop or by providing custom CSS.
TypeScript Support
This package is written in TypeScript and includes type definitions. All types are exported and can be imported:
import type {
CaptchaProps,
OceanCaptchaConfig,
GenerateChallengeResponse,
VerifyCaptchaResponse,
VerifyCodeResponse,
} from 'ocean-captcha';License
MIT
Support
For issues and questions, please visit our GitHub repository.
