Authentication
Cocobase provides a complete authentication system with user registration, login, session management, and profile handling. No complex setup required - just use the built-in auth methods.Quick Start
- JavaScript
- Dart
- Go
- Python
- HTTP
import { Cocobase } from "cocobase";
const db = new Cocobase({
apiKey: "YOUR_API_KEY",
projectId: "YOUR_PROJECT_ID" // Optional
});
// Register a new user
const user = await db.auth.register({
email: "user@example.com",
password: "securePassword123",
data: { full_name: "Alice Johnson" }
});
// Login
const result = await db.auth.login({
email: "alice@example.com",
password: "SecurePass123!"
});
final db = Cocobase(CocobaseConfig(apiKey: "YOUR_API_KEY"));
// Register a new user
final user = await db.register(
email: 'user@example.com',
password: 'securePassword123',
data: {
'full_name': 'Alice Johnson',
'role': 'developer',
},
);
// Login
final session = await db.login(
email: 'user@example.com',
password: 'securePassword123',
);
client := cocobase.NewClient(cocobase.Config{
APIKey: "YOUR_API_KEY",
})
// Register a new user
user, err := client.Register(ctx, "user@example.com", "securePassword123", map[string]any{
"full_name": "Alice Johnson",
"role": "developer",
})
// Login
err = client.Login(ctx, "user@example.com", "securePassword123")
if err != nil {
log.Fatal(err)
}
// Get user separately
user, err = client.GetCurrentUser(ctx)
from cocobase_client.client import CocoBaseClient
db = CocoBaseClient(api_key="YOUR_API_KEY")
# Register a new user
user = db.auth.register(
"user@example.com",
"securePassword123",
{
"full_name": "Alice Johnson",
"role": "developer"
}
)
# Login
session = db.auth.login("user@example.com", "securePassword123")
# Register
curl -X POST https://api.cocobase.buzz/auth-collections/signup \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securePassword123",
"data": {
"full_name": "Alice Johnson",
"role": "developer"
}
}'
# Login
curl -X POST https://api.cocobase.buzz/auth-collections/login \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securePassword123"
}'
User Registration
Create new user accounts with email and password:- JavaScript
- Dart
- Go
- Python
- HTTP
// Basic registration
const result = await db.auth.register({
email: "alice@example.com",
password: "SecurePass123!"
});
if (!result.requires_2fa) {
console.log("Registered user:", result.user);
}
// With additional user data
const userWithData = await db.auth.register({
email: "bob@example.com",
password: "SecurePass123!",
data: {
full_name: "Bob Smith",
age: 25,
role: "admin",
preferences: {
theme: "dark",
notifications: true
}
}
});
{
"id": "user_123abc",
"email": "alice@example.com",
"data": {
"full_name": "Bob Smith",
"age": 25,
"role": "admin",
"preferences": {
"theme": "dark",
"notifications": true
}
},
"createdAt": "2024-01-15T10:30:00Z",
"token": "eyJhbGc..."
}
// Basic registration
final user = await db.register(
email: 'alice@example.com',
password: 'SecurePass123!',
);
// With additional user data
final userWithData = await db.register(
email: 'bob@example.com',
password: 'SecurePass123!',
data: {
'full_name': 'Bob Smith',
'age': 25,
'role': 'admin',
'preferences': {
'theme': 'dark',
'notifications': true,
},
},
);
// Basic registration
user, err := client.Register(ctx, "alice@example.com", "SecurePass123!", nil)
if err != nil {
log.Fatal(err)
}
// With additional user data
userWithData, err := client.Register(ctx, "bob@example.com", "SecurePass123!", map[string]any{
"full_name": "Bob Smith",
"age": 25,
"role": "admin",
"preferences": map[string]any{
"theme": "dark",
"notifications": true,
},
})
# Basic registration
user = db.auth.register("alice@example.com", "SecurePass123!")
# With additional user data
user_with_data = db.auth.register(
"bob@example.com",
"SecurePass123!",
{
"full_name": "Bob Smith",
"age": 25,
"role": "admin",
"preferences": {
"theme": "dark",
"notifications": True
}
}
)
curl -X POST https://api.cocobase.buzz/auth-collections/signup \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "bob@example.com",
"password": "SecurePass123!",
"data": {
"full_name": "Bob Smith",
"age": 25,
"role": "admin",
"preferences": {
"theme": "dark",
"notifications": true
}
}
}'
Password requirements: - Minimum 8 characters - At least one uppercase letter
- At least one lowercase letter - At least one number
User Login
Authenticate users and get access tokens:- JavaScript
- Dart
- Go
- Python
- HTTP
const result = await db.auth.login({
email: "alice@example.com",
password: "SecurePass123!"
});
if (result.requires_2fa) {
console.log("2FA required:", result.message);
} else {
console.log("Logged in user:", result.user);
}
// Token is automatically stored internally
// Token is automatically saved to localStorage
await db.auth.initAuth();
if (db.auth.isAuthenticated()) {
const currentUser = await db.auth.getCurrentUser();
console.log("User is logged in:", currentUser);
}
// Login
final session = await db.login(
email: 'alice@example.com',
password: 'SecurePass123!',
);
print('Token: ${session.token}');
print('User: ${session.user}');
// Check current user
final currentUser = await db.getCurrentUser();
if (currentUser != null) {
print('User is logged in: $currentUser');
}
// Login
err = client.Login(ctx, "alice@example.com", "SecurePass123!")
if err != nil {
log.Fatal(err)
}
user, err := client.GetCurrentUser(ctx)
fmt.Printf("Email: %s\n", user.Email)
// Token is automatically stored and used for future requests
# Login
session = db.auth.login("alice@example.com", "SecurePass123!")
print(f"Token: {session['token']}")
print(f"User: {session['user']}")
# Check current user
current_user = db.auth.get_current_user()
if current_user:
print(f"User is logged in: {current_user}")
curl -X POST https://api.cocobase.buzz/auth-collections/login \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "alice@example.com",
"password": "SecurePass123!"
}'
**Use the token in subsequent requests:**
```bash
curl -X GET https://api.cocobase.buzz/collections/posts \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Get Current User
Retrieve the currently authenticated user:- JavaScript
- Dart
- Go
- Python
- HTTP
await db.auth.initAuth();
if (db.auth.isAuthenticated()) {
const user = await db.auth.getCurrentUser();
console.log("Logged in as:", user.email);
console.log("User data:", user.data);
} else {
console.log("No user logged in");
}
// Get current user
final user = await db.getCurrentUser();
if (user != null) {
print('Logged in as: ${user.email}');
print('User data: ${user.data}');
} else {
print('No user logged in');
}
// Get current user
user, err := client.GetCurrentUser(ctx)
if err != nil {
log.Printf("No user logged in: %v", err)
return
}
fmt.Printf("Logged in as: %s\n", user.Email)
fmt.Printf("User data: %+v\n", user.Data)
# Get current user
user = db.auth.get_current_user()
if user:
print(f"Logged in as: {user['email']}")
print(f"User data: {user['data']}")
else:
print("No user logged in")
curl -X GET https://api.cocobase.buzz/auth-collections/me \
-H "Authorization: Bearer YOUR_USER_TOKEN"
Update User Profile
Update user data after authentication:- JavaScript
- Dart
- Go
- Python
- HTTP
const updatedUser = await db.auth.updateUser({
data: {
full_name: "Alice Johnson Smith",
bio: "Full-stack developer",
avatar: "https://example.com/avatar.jpg",
preferences: {
theme: "dark",
language: "en"
}
}
});
console.log("Updated user:", updatedUser);
// Update user profile
final updatedUser = await db.updateUser(data: {
'full_name': 'Alice Johnson Smith',
'bio': 'Full-stack developer',
'avatar': 'https://example.com/avatar.jpg',
'preferences': {
'theme': 'dark',
'language': 'en',
},
});
print('Updated user: $updatedUser');
// Update user profile
updatedUser, err := client.UpdateUser(ctx, map[string]interface{}{
"full_name": "Alice Johnson Smith",
"bio": "Full-stack developer",
}, nil, nil)
# Update user profile
updated_user = db.auth.update_profile({
"full_name": "Alice Johnson Smith",
"bio": "Full-stack developer",
"avatar": "https://example.com/avatar.jpg",
"preferences": {
"theme": "dark",
"language": "en"
}
})
curl -X PATCH https://api.cocobase.buzz/auth-collections/user \
-H "Authorization: Bearer YOUR_USER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"data": {
"full_name": "Alice Johnson Smith",
"bio": "Full-stack developer",
"avatar": "https://example.com/avatar.jpg"
}
}'
Logout
End the user session:- JavaScript
- Dart
- Go
- Python
- HTTP
// Logout current user
await db.auth.logout();
console.log("User logged out");
// Verify logout
const user = db.auth.getCurrentUser(); // Returns null
// Logout current user
await db.logout();
print('User logged out');
// Verify logout
final user = await db.getCurrentUser(); // Returns null
// Logout current user
err := client.Logout(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("User logged out")
# Logout current user
db.auth.logout()
print("User logged out")
curl -X POST https://api.cocobase.buzz/auth-collections/logout \
-H "Authorization: Bearer YOUR_USER_TOKEN"
Password Management
Change Password
- JavaScript
- Go
- Python
- HTTP
// Change password (user must be logged in)
await db.auth.changePassword("oldPassword123", "newPassword456");
This feature is not yet available in the Go SDK.
db.auth.change_password("oldPassword123", "newPassword456")
curl -X POST https://api.cocobase.buzz/auth/change-password \
-H "Authorization: Bearer YOUR_USER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"oldPassword": "oldPassword123",
"newPassword": "newPassword456"
}'
Request Password Reset
- JavaScript
- Dart
- Go
- Python
- HTTP
// Send password reset email
await db.auth.requestPasswordReset("user@example.com");
await db.requestPasswordReset(email: 'user@example.com');
This feature is not yet available in the Go SDK.
db.auth.request_password_reset("user@example.com")
curl -X POST https://api.cocobase.buzz/auth/request-password-reset \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com"
}'
Reset Password with Token
- JavaScript
- Dart
- Go
- Python
- HTTP
// Reset password using token from email
await db.auth.resetPassword("reset_token_from_email", "newPassword123");
await db.resetPassword(
token: 'reset_token_from_email',
newPassword: 'newPassword123',
);
This feature is not yet available in the Go SDK.
db.auth.reset_password("reset_token_from_email", "newPassword123")
curl -X POST https://api.cocobase.buzz/auth/reset-password \
-H "Content-Type: application/json" \
-d '{
"token": "reset_token_from_email",
"newPassword": "newPassword123"
}'
OAuth Authentication
Authenticate users with Google, GitHub, and other OAuth providers:- JavaScript
- Dart
- Go
- Python
- HTTP
// Cocobase does NOT handle the Google popup.
// You handle OAuth yourself, then send the token to Cocobase.
// Option 1: Using Google Identity Services
google.accounts.id.initialize({
client_id: 'YOUR_GOOGLE_CLIENT_ID',
callback: async (response) => {
// Send the ID token to Cocobase
const user = await db.auth.loginWithGoogle({
idToken: response.credential,
platform: "web"
});
console.log("Logged in:", user.email);
}
});
google.accounts.id.renderButton(
document.getElementById("google-btn"),
{ theme: "outline", size: "large" }
);
// Option 2: Using react-google-login
// import { useGoogleLogin } from '@react-oauth/google';
// const login = useGoogleLogin({
// onSuccess: async (tokenResponse) => {
// const user = await db.auth.loginWithGoogle({
// idToken: tokenResponse.credential,
// platform: "web"
// });
// }
// });
// For mobile (iOS/Android)
// const user = await db.auth.loginWithGoogle({
// idToken: "token-from-native-google-sdk",
// platform: "ios" // or "android"
// });
// Initiate Google OAuth flow
final authUrl = await db.getOAuthUrl(
provider: 'google',
redirectUrl: 'yourapp://auth/callback',
scopes: ['email', 'profile'],
);
// Open authUrl in browser/webview
// Handle callback
final session = await db.handleOAuthCallback(
provider: 'google',
code: authorizationCode,
);
This feature is not yet available in the Go SDK.
# Initiate Google OAuth flow
auth_url = db.auth.get_oauth_url(
"google",
redirect_url="https://yourapp.com/auth/callback",
scopes=["email", "profile"]
)
# Handle callback
session = db.auth.handle_oauth_callback("google", authorization_code)
# Get OAuth URL
curl -X POST https://api.cocobase.buzz/auth/oauth/google/url \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"redirectUrl": "https://yourapp.com/auth/callback",
"scopes": ["email", "profile"]
}'
# Handle callback
curl -X POST https://api.cocobase.buzz/auth/oauth/google/callback \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"code": "AUTHORIZATION_CODE_FROM_GOOGLE"
}'
- GitHub
- Microsoft
- Apple
Two-Factor Authentication (2FA)
Enable 2FA
- JavaScript
- Go
- Python
- HTTP
// Enable 2FA for current user
await db.auth.enable2FA();
console.log("2FA enabled successfully");
// Verify 2FA setup with code from authenticator app
await db.auth.verify2FA("123456");
// Disable 2FA
await db.auth.disable2FA();
console.log("2FA disabled");
This feature is not yet available in the Go SDK.
# Enable 2FA
db.auth.enable_2fa()
print("2FA enabled")
# Verify 2FA
db.auth.verify_2fa("123456")
# Disable 2FA
db.auth.disable_2fa()
print("2FA disabled")
# Enable 2FA
curl -X POST https://api.cocobase.buzz/auth/2fa/enable \
-H "Authorization: Bearer YOUR_USER_TOKEN"
# Verify 2FA
curl -X POST https://api.cocobase.buzz/auth/2fa/verify \
-H "Authorization: Bearer YOUR_USER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"code": "123456"
}'
Login with 2FA
- JavaScript
- Go
- Python
- HTTP
// First attempt login
const result = await db.auth.login({
email: "user@example.com",
password: "password123"
});
if (result.requires_2fa) {
const code = prompt("Enter 2FA code:");
await db.auth.verify2FALogin({
email: "user@example.com",
code
});
console.log("2FA login successful");
}
This feature is not yet available in the Go SDK.
try:
db.auth.login("user@example.com", "password123")
except TwoFactorRequiredError:
# Prompt user for 2FA code
code = input("Enter 2FA code: ")
# Complete login with 2FA
db.auth.verify_2fa_login(code)
# Login
curl -X POST https://api.cocobase.buzz/auth-collections/login \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "password123"
}'
# Complete 2FA login
curl -X POST https://api.cocobase.buzz/auth-collections/verify-2fa-login \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"code": "123456"
}'
Email Verification
Verify user email addresses to ensure account authenticity and improve security.- JavaScript
- Python
- HTTP
// Request verification email for current user
await db.auth.requestEmailVerification();
// Verify email with token from link
const token = new URLSearchParams(window.location.search).get('token');
if (token) {
await db.auth.verifyEmail(token);
console.log("Email verified successfully");
}
// Resend if needed
await db.auth.resendVerificationEmail();
# Request verification
db.auth.request_email_verification()
# Verify email
db.auth.verify_email("verification_token_from_email")
# Resend
db.auth.resend_verification_email()
# Request verification
curl -X POST https://api.cocobase.buzz/auth/request-verification \
-H "Authorization: Bearer YOUR_USER_TOKEN"
# Verify email
curl -X POST https://api.cocobase.buzz/auth/verify-email \
-H "Content-Type: application/json" \
-d '{
"token": "verification_token_from_email"
}'
Email verification can be enforced globally in your project settings. When enabled, users will have limited access until their email is verified.
Role-Based Access Control
Manage user roles and permissions:- JavaScript
- Dart
- Go
- Python
- HTTP
const admin = await db.auth.register({
email: "admin@example.com",
password: "password123",
data: {
full_name: "Admin User",
role: "admin"
}
});
await db.auth.initAuth();
if (db.auth.isAuthenticated()) {
const currentUser = await db.auth.getCurrentUser();
if (db.auth.hasRole("admin")) {
// Show admin features
}
}
// Register user with role
final admin = await db.register(
email: 'admin@example.com',
password: 'password123',
data: {
'full_name': 'Admin User',
'role': 'admin',
},
);
// Check user role
final currentUser = await db.getCurrentUser();
if (currentUser?.data['role'] == 'admin') {
// Show admin features
}
// Register user with role
admin, err := client.Register(ctx, "admin@example.com", "password123", map[string]any{
"full_name": "Admin User",
"role": "admin",
})
// Check user role
currentUser, _ := client.GetCurrentUser(ctx)
if currentUser.Data["role"] == "admin" {
// Show admin features
}
# Register user with role
admin = db.auth.register(
"admin@example.com",
"password123",
{
"full_name": "Admin User",
"role": "admin"
}
)
# Check user role
current_user = db.auth.get_current_user()
if current_user['data']['role'] == 'admin':
# Show admin features
pass
# Register with role
curl -X POST https://api.cocobase.buzz/auth/register \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "admin@example.com",
"password": "password123",
"data": {
"role": "admin"
}
}'
Authentication with React
Complete example for React applications:// hooks/useAuth.ts
import { useState, useEffect } from "react";
import { db } from "@/lib/cocobase";
export function useAuth() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const currentUser = db.auth.getCurrentUser();
setUser(currentUser);
setLoading(false);
}, []);
const login = async (email: string, password: string) => {
const result = await db.auth.login({ email, password });
if (!result.requires_2fa) {
const user = await db.auth.getCurrentUser();
setUser(user);
}
return result;
};
const register = async (email: string, password: string, data?: any) => {
const result = await db.auth.register({ email, password, data });
if (!result.requires_2fa) {
setUser(result.user);
}
return result;
};
const logout = async () => {
await db.auth.logout();
setUser(null);
};
return { user, loading, login, register, logout };
}
// components/LoginForm.tsx
function LoginForm() {
const { login } = useAuth();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(email, password);
// Redirect to dashboard
} catch (error) {
console.error("Login failed:", error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}
Authentication with Flutter
Complete example for Flutter applications:// providers/auth_provider.dart
import 'package:flutter/foundation.dart';
import 'package:coco_base_flutter/coco_base_flutter.dart';
class AuthProvider with ChangeNotifier {
final Cocobase _db;
Map<String, dynamic>? _user;
AuthProvider(this._db) {
_loadUser();
}
Map<String, dynamic>? get user => _user;
bool get isAuthenticated => _user != null;
Future<void> _loadUser() async {
_user = await _db.getCurrentUser();
notifyListeners();
}
Future<void> login(String email, String password) async {
await _db.login(email, password);
_user = await _db.getCurrentUser();
notifyListeners();
}
Future<void> register(String email, String password, Map<String, dynamic>? data) async {
await _db.register(email, password, data: data);
_user = await _db.getCurrentUser();
notifyListeners();
}
Future<void> logout() async {
_db.logout();
_user = null;
notifyListeners();
}
}
// screens/login_screen.dart
class LoginScreen extends StatelessWidget {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
ElevatedButton(
onPressed: () async {
await context.read<AuthProvider>().login(
_emailController.text,
_passwordController.text,
);
},
child: Text('Login'),
),
],
),
),
);
}
}
Error Handling
Common authentication errors and how to handle them:- JavaScript
- Dart
- Go
- Python
- HTTP
try {
await db.auth.login({ email, password });
} catch (error) {
switch (error.code) {
case 'INVALID_CREDENTIALS':
console.error('Invalid email or password');
break;
case '2FA_REQUIRED':
console.log('2FA code required');
break;
case 'USER_NOT_FOUND':
console.error('User not found');
break;
case 'EMAIL_ALREADY_EXISTS':
console.error('Email already registered');
break;
default:
console.error('Authentication error:', error.message);
}
}
try {
await db.login(email: email, password: password);
} catch (e) {
if (e is CocobaseException) {
switch (e.code) {
case 'INVALID_CREDENTIALS':
print('Invalid email or password');
break;
case '2FA_REQUIRED':
print('2FA code required');
break;
case 'USER_NOT_FOUND':
print('User not found');
break;
default:
print('Authentication error: ${e.message}');
}
}
}
err := client.Login(ctx, email, password)
if err != nil {
var apiErr *cocobase.APIError
if errors.As(err, &apiErr) {
fmt.Println("Status:", apiErr.StatusCode)
fmt.Println("Error:", apiErr.Body)
} else {
fmt.Println("Error:", err)
}
}
try:
db.auth.login(email, password)
except InvalidCredentialsError:
print("Invalid email or password")
except TwoFactorRequiredError:
print("2FA code required")
except UserNotFoundError:
print("User not found")
except CocobaseError as e:
print(f"Authentication error: {e}")
HTTP status codes:
400- Invalid request401- Invalid credentials403- 2FA required404- User not found409- Email already exists500- Server error
Best Practices
Secure Password Storage
Secure Password Storage
Never store passwords in plain text. Use environment variables and secure storage:
// ✅ Good
const password = process.env.USER_PASSWORD;
// ❌ Bad
const password = "hardcoded_password123";
Token Security
Token Security
Tokens are automatically stored securely: - Browser: localStorage (with
HttpOnly flag) - Mobile: Secure storage (Keychain/Keystore) - Server:
Memory or secure storage backend
Session Management
Session Management
Implement automatic token refresh and session validation:
// Check session on app start
const user = db.auth.getCurrentUser();
if (user) {
try {
await db.auth.fetchCurrentUser(); // Validates token
} catch (error) {
// Token expired, redirect to login
await db.auth.logout();
}
}
Password Requirements
Password Requirements
Enforce strong password requirements:
- Minimum 8 characters
- Mix of uppercase, lowercase, numbers
- Consider special characters
- Implement password strength meter
Next Steps
CRUD Operations
Learn to create, read, update, and delete data
User Profiles
Build complete user profile management
Protected Routes
Secure your application routes
Social Login
Implement OAuth authentication
