Skip to main content

Authentication

Learn how to authenticate with the Taruvi platform using the SDK. The Python and JavaScript SDKs use different authentication patterns optimized for their respective environments.


Authentication Overview

The Taruvi SDK supports multiple authentication methods depending on your use case:

FeaturePython SDKJavaScript SDK
PatternJWT/API Key basedWeb UI Flow (OAuth) + Token-based
Use CaseServer-side, scripts, CLI toolsBrowser apps, SPAs, Node.js
Token StorageIn-memorylocalStorage (browser) / in-memory (server)
RedirectsNoYes (browser only)
Methods4 methodsWeb UI + Token management

Python Authentication

The Python SDK uses a token-based authentication pattern with multiple methods.

AuthManager Pattern

The Python SDK uses an immutable client pattern:

  1. Create an unauthenticated client
  2. Call authentication method
  3. Receive a new authenticated client instance
from taruvi import Client

# Step 1: Create unauthenticated client
client = Client(api_url="https://api.taruvi.cloud", app_slug="my-app")

# Step 2: Authenticate (returns NEW client)
auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="secret123"
)

# Step 3: Use authenticated client
users = auth_client.database.query("users").get()
Why Immutable Clients?

This pattern ensures authentication state is explicit and prevents accidental use of unauthenticated clients.


Method 1: Username + Password

Best for: Scripts, CLI tools, server-side applications

from taruvi import Client

# Create client
client = Client(
api_url="https://api.taruvi.cloud",
app_slug="my-app"
)

# Authenticate with credentials
auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="secret123"
)

# SDK automatically obtains and manages JWT token
print(f"Authenticated: {auth_client.is_authenticated}")

# Use authenticated client
result = auth_client.functions.execute("my-function")

How it works:

  1. SDK sends credentials to /api/v1/auth/login
  2. Receives JWT access token and refresh token
  3. Stores tokens in memory
  4. Automatically includes token in all subsequent requests

Method 2: JWT Bearer Token

Best for: When you already have a JWT token (e.g., from another service)

from taruvi import Client

client = Client(api_url="https://api.taruvi.cloud", app_slug="my-app")

# Authenticate with existing JWT token
auth_client = client.auth.signInWithToken(
token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
token_type="jwt"
)

# Use authenticated client
users = auth_client.database.query("users").get()

Token format:

  • Header: Authorization: Bearer eyJhbGc...
  • Token must be a valid JWT from Taruvi's auth system

Method 3: Knox API Key

Best for: Machine-to-machine authentication, long-lived tokens

from taruvi import Client

client = Client(api_url="https://api.taruvi.cloud", app_slug="my-app")

# Authenticate with API key
auth_client = client.auth.signInWithToken(
token="your_knox_api_key_here",
token_type="api_key"
)

# Use authenticated client
result = auth_client.functions.execute("my-function")

How to create an API key:

  1. Log into Taruvi dashboard
  2. Navigate to Settings → API Keys
  3. Click "Create API Key"
  4. Copy the key (shown only once!)

Token format:

  • Header: Authorization: Api-Key your_knox_api_key_here

Method 4: Session Token

Best for: Web applications with session-based auth

from taruvi import Client

client = Client(api_url="https://api.taruvi.cloud", app_slug="my-app")

# Authenticate with session token
auth_client = client.auth.signInWithToken(
token="session_token_here",
token_type="session_token"
)

# Use authenticated client
users = auth_client.database.query("users").get()

Token format:

  • Header: X-Session-Token: session_token_here

Authentication Status

Check if a client is authenticated:

from taruvi import Client

client = Client(api_url="...", app_slug="...")
print(f"Authenticated: {client.is_authenticated}") # False

auth_client = client.auth.signInWithPassword(username="...", password="...")
print(f"Authenticated: {auth_client.is_authenticated}") # True

Get Current User

Retrieve the currently authenticated user:

auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="secret123"
)

# Get current user from API
user = auth_client.auth.get_current_user()
print(f"User: {user['username']} ({user['email']})")
print(f"Roles: {user['roles']}")

Sign Out

Remove authentication from a client:

# Authenticated client
auth_client = client.auth.signInWithPassword(username="...", password="...")

# Sign out (returns unauthenticated client)
unauth_client = auth_client.auth.signOut()

print(f"Authenticated: {unauth_client.is_authenticated}") # False

Token Refresh

Refresh an expired JWT token:

# Refresh token (obtained during login)
refresh_token = "refresh_token_here"

# Refresh access token
new_auth_client = client.auth.refreshToken(refresh_token)

# Use new client with fresh token
users = new_auth_client.database.query("users").get()
Automatic Token Refresh

The SDK does not automatically refresh tokens. You must implement token refresh logic in your application.


Switching Authentication at Runtime

You can switch between different users/auth methods:

from taruvi import Client

client = Client(api_url="...", app_slug="...")

# Authenticate as user 1
alice_client = client.auth.signInWithPassword(
username="alice@example.com",
password="alice-password"
)
alice_data = alice_client.database.query("users").get()

# Authenticate as user 2
bob_client = client.auth.signInWithPassword(
username="bob@example.com",
password="bob-password"
)
bob_data = bob_client.database.query("users").get()

# Each client maintains its own authentication

JavaScript Authentication

The JavaScript SDK uses Web UI Flow for browser apps and token-based auth for Node.js.

Web UI Flow (Browser)

Best for: Browser-based applications, SPAs

The JavaScript SDK uses OAuth-style redirects for authentication:

import { Client, Auth } from '@taruvi/sdk'

// Create client
const client = new Client({
apiKey: "site-api-key",
appSlug: "my-app",
baseUrl: "https://site.taruvi.cloud",
deskUrl: "https://desk.taruvi.cloud" // Login page URL
})

// Instantiate auth module
const auth = new Auth(client)

// Redirect to login page
auth.login("/dashboard") // Callback URL after login

// After redirect back from login:
if (auth.isUserAuthenticated()) {
const user = auth.getCurrentUser()
console.log(`Welcome, ${user.username}!`)
}

How it works:

  1. auth.login() redirects to Taruvi's login page
  2. User enters credentials
  3. Taruvi redirects back to your app with token in URL hash
  4. SDK automatically extracts and stores token in localStorage
  5. Token is automatically included in all subsequent requests

Login Flow Example

import { Client, Auth } from '@taruvi/sdk'

const client = new Client({
apiKey: "site-api-key",
appSlug: "my-app",
baseUrl: "https://site.taruvi.cloud",
deskUrl: "https://desk.taruvi.cloud"
})

const auth = new Auth(client)

// On login button click
function handleLogin() {
// Redirects to https://desk.taruvi.cloud/login
// and returns to /dashboard after successful login
auth.login("/dashboard")
}

// On your callback page (/dashboard)
function checkAuth() {
if (auth.isUserAuthenticated()) {
const user = auth.getCurrentUser()
console.log("User:", user)

// User is authenticated - proceed
loadDashboard()
} else {
// Not authenticated - redirect to login
auth.login("/dashboard")
}
}

Signup Flow

Similar to login, but redirects to the signup page:

import { Auth } from '@taruvi/sdk'

const auth = new Auth(client)

// Redirect to signup page
function handleSignup() {
auth.signup("/dashboard") // Callback URL after signup
}

// After redirect back:
if (auth.isUserAuthenticated()) {
console.log("Signup successful!")
}

Token Management

Check and manage authentication state:

import { Auth } from '@taruvi/sdk'

const auth = new Auth(client)

// Check if user is authenticated
if (auth.isUserAuthenticated()) {
console.log("User is logged in")
}

// Get tokens
const accessToken = auth.getAccessToken()
const refreshToken = auth.getRefreshToken()

// Check if token is expired
if (auth.isTokenExpired()) {
console.log("Token expired - need to refresh")
}

// Get current user (from JWT payload)
const user = auth.getCurrentUser()
console.log(`User ID: ${user.user_id}`)
console.log(`Username: ${user.username}`)
console.log(`Email: ${user.email}`)

Refresh Token

Refresh an expired access token:

import { Auth } from '@taruvi/sdk'

const auth = new Auth(client)

try {
// Refresh token
const tokens = await auth.refreshAccessToken()

console.log("Access token refreshed")
console.log(`New access token: ${tokens.access}`)
console.log(`New refresh token: ${tokens.refresh}`)
console.log(`Expires in: ${tokens.expires_in} seconds`)
} catch (error) {
console.error("Token refresh failed:", error)
// Redirect to login
auth.login()
}
Token Rotation

Taruvi uses refresh token rotation. Each refresh returns a new access token AND a new refresh token. The old refresh token becomes invalid.


Logout

Log out and redirect:

import { Auth } from '@taruvi/sdk'

const auth = new Auth(client)

// Logout and redirect to home page
await auth.logout("/")

// Tokens are cleared from localStorage
// User is redirected to "/"

Token-Based Auth (Node.js)

For Node.js server applications, use token-based authentication:

import { Client } from '@taruvi/sdk'

// Create client with token
const client = new Client({
apiKey: "site-api-key",
appSlug: "my-app",
baseUrl: "https://site.taruvi.cloud",
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." // Existing JWT
})

// Token is automatically included in all requests
const database = new Database(client)
const users = await database.from("users").execute()

Environment Variables

Store credentials securely using environment variables:

# .env
TARUVI_API_URL=https://api.taruvi.cloud
TARUVI_APP_SLUG=my-app

# Choose ONE authentication method:

# Method 1: Username + Password
TARUVI_USERNAME=alice@example.com
TARUVI_PASSWORD=secret123

# Method 2: JWT Token
TARUVI_JWT=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# Method 3: API Key
TARUVI_API_KEY=your_knox_api_key

# Method 4: Session Token
TARUVI_SESSION_TOKEN=session_token_here
import os
from dotenv import load_dotenv
from taruvi import Client

load_dotenv()

client = Client(
api_url=os.getenv("TARUVI_API_URL"),
app_slug=os.getenv("TARUVI_APP_SLUG")
)

# Authenticate based on available credentials
if os.getenv("TARUVI_USERNAME"):
auth_client = client.auth.signInWithPassword(
username=os.getenv("TARUVI_USERNAME"),
password=os.getenv("TARUVI_PASSWORD")
)
elif os.getenv("TARUVI_JWT"):
auth_client = client.auth.signInWithToken(
token=os.getenv("TARUVI_JWT"),
token_type="jwt"
)
elif os.getenv("TARUVI_API_KEY"):
auth_client = client.auth.signInWithToken(
token=os.getenv("TARUVI_API_KEY"),
token_type="api_key"
)
Security Warning
  • Never commit .env files to version control
  • Use .gitignore to exclude .env files
  • Rotate API keys and tokens regularly
  • Use environment-specific credentials (dev/staging/prod)

Best Practices

1. Use API Keys for Machine-to-Machine

# Good for: Background jobs, cron tasks, server-to-server
auth_client = client.auth.signInWithToken(
token="knox_api_key",
token_type="api_key"
)

2. Use Username/Password for Interactive Scripts

# Good for: CLI tools, interactive scripts
auth_client = client.auth.signInWithPassword(
username=input("Username: "),
password=getpass("Password: ")
)

3. Implement Token Refresh

import time
from taruvi import AuthenticationError

def with_token_refresh(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except AuthenticationError as e:
if "expired" in str(e).lower():
# Refresh token and retry
refresh_token = get_refresh_token()
new_client = client.auth.refreshToken(refresh_token)
return func(*args, **kwargs)
raise
return wrapper

4. Store Tokens Securely

  • Never hardcode tokens in source code
  • Use environment variables or secure vaults (AWS Secrets Manager, HashiCorp Vault)
  • Encrypt tokens at rest
  • Use short-lived tokens when possible

5. Handle Authentication Errors

from taruvi import Client, AuthenticationError, NotAuthenticatedError

try:
auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="wrong-password"
)
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
# Prompt user to re-enter credentials

try:
# Attempt operation without authentication
users = client.database.query("users").get()
except NotAuthenticatedError as e:
print("Please authenticate first")
# Redirect to login

Next Steps