Skip to main content

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

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!"
});

User Registration

Create new user accounts with email and password:

// 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
}
}
});
Response:
{
  "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..."
}
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:

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
With automatic token persistence:
// 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);
}

Get Current User

Retrieve the currently authenticated user:

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");
}

Update User Profile

Update user data after authentication:

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);

Logout

End the user session:
// Logout current user
await db.auth.logout();

console.log("User logged out");

// Verify logout
const user = db.auth.getCurrentUser(); // Returns null

Password Management

Change Password

// Change password (user must be logged in)
await db.auth.changePassword("oldPassword123", "newPassword456");

Request Password Reset

// Send password reset email
await db.auth.requestPasswordReset("user@example.com");

Reset Password with Token

// Reset password using token from email
await db.auth.resetPassword("reset_token_from_email", "newPassword123");

OAuth Authentication

Authenticate users with Google, GitHub, and other OAuth providers:
{/**    // Initiate Google OAuth flow
const authUrl = await db.auth.getOAuthUrl("google", {
  redirectUrl: "https://yourapp.com/auth/callback",
  scopes: ["email", "profile"]
});

// Redirect user to authUrl
window.location.href = authUrl;

// In your callback handler
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');

// Exchange code for token
const session = await db.auth.handleOAuthCallback("google", code);
console.log("User logged in:", session.user); **/}
Web - Using Google Identity Services
* google.accounts.id.initialize({
*   client_id: 'YOUR_GOOGLE_CLIENT_ID',
*   callback: async (response) => {
*     const user = await db.auth.loginWithGoogle(response.credential, 'web');
*     console.log('Logged in:', user.email);
*   }
* });

Supported OAuth Providers:
  • Google
  • GitHub
  • Facebook
  • Twitter
  • Microsoft
  • Apple

Two-Factor Authentication (2FA)

Enable 2FA

// Enable 2FA for current user
const { qrCode, secret } = await db.auth.enable2FA();

console.log("Scan this QR code:", qrCode);
console.log("Or enter this secret manually:", secret);

// Verify 2FA setup with code from authenticator app
await db.auth.verify2FA("123456");

Login with 2FA


// 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");
}

Role-Based Access Control

Manage user roles and permissions:

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 (currentUser.data.role === "admin") {
// Show admin features
}
}

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 {
    final session = await _db.login(email: email, password: password);
    _user = session.user;
    notifyListeners();
  }

  Future<void> register(String email, String password, Map<String, dynamic>? data) async {
    final user = await _db.register(
      email: email,
      password: password,
      data: data,
    );
    _user = user;
    notifyListeners();
  }

  Future<void> logout() async {
    await _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:
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);
  }
}

Best Practices

Never store passwords in plain text. Use environment variables and secure storage:
// ✅ Good
const password = process.env.USER_PASSWORD;

// ❌ Bad
const password = "hardcoded_password123";
Tokens are automatically stored securely: - Browser: localStorage (with HttpOnly flag) - Mobile: Secure storage (Keychain/Keystore) - Server: Memory or secure storage backend
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();
  }
}
Enforce strong password requirements:
  • Minimum 8 characters
  • Mix of uppercase, lowercase, numbers
  • Consider special characters
  • Implement password strength meter

Next Steps