Overview
AI Studio uses Better Auth for authentication, providing a secure, modern authentication system with email/password support, session management, and admin capabilities.
All authentication endpoints are available at /api/auth/* and handle user registration, login, email verification, password reset, and session management.
Base URL
https://yourdomain.com/api/auth
Authentication Methods
AI Studio supports the following authentication methods:
Email & Password : Traditional email/password authentication with verification
Session-based : Secure HTTP-only cookie sessions (7-day expiry)
Key Features
Email Verification Required email verification for new accounts with automatic workspace creation
Session Management 7-day sessions with 1-day refresh window and automatic cleanup
Password Reset Secure password reset with 1-hour token expiration
Admin Plugin Built-in admin impersonation and user management capabilities
Configuration
The authentication system is configured in lib/auth.ts with the following settings:
{
emailAndPassword : {
enabled : true ,
minPasswordLength : 8 ,
requireEmailVerification : true ,
resetPasswordTokenExpiresIn : 3600 // 1 hour
},
session : {
expiresIn : 604800 , // 7 days
updateAge : 86400 // 1 day refresh window
}
}
Database Schema
Authentication data is stored across multiple tables:
User Table
user {
id : string // Primary key
name : string // User's display name
email : string // Unique email address
emailVerified : boolean // Verification status
image : string ? // Profile image URL
workspaceId : string // Associated workspace
role : string // owner | admin | member
isSystemAdmin : boolean // Super admin flag
banned : boolean // Ban status
banReason : string ? // Reason for ban
banExpires : timestamp ? // Ban expiration
createdAt : timestamp
updatedAt : timestamp
}
Session Table
See Session Management for details.
Account Table
account {
id : string
accountId : string // Provider-specific ID
providerId : string // Auth provider (email, google, etc.)
userId : string // Foreign key to user
password : string // Hashed password (for email provider)
createdAt : timestamp
updatedAt : timestamp
}
Verification Table
verification {
id : string
identifier : string // Email or phone
value : string // Verification token
expiresAt : timestamp // Token expiration
createdAt : timestamp
updatedAt : timestamp
}
Automatic Workspace Creation
When a user signs up, a workspace is automatically created:
// From lib/auth.ts database hooks
databaseHooks : {
user : {
create : {
after : async ( createdUser ) => {
// Generate workspace slug from email
const slug = createdUser . email
. split ( "@" )[ 0 ]
. toLowerCase ()
. replace ( / [ ^ a-z0-9 ] / g , "-" );
const workspaceId = nanoid ();
// Create workspace
await db . insert ( workspace ). values ({
id: workspaceId ,
name: ` ${ createdUser . name } 's Workspace` ,
slug: ` ${ slug } - ${ workspaceId . slice ( 0 , 6 ) } ` ,
});
// Link user to workspace as owner
await db . update ( user )
. set ({ workspaceId , role: "owner" })
. where ( eq ( user . id , createdUser . id ));
}
}
}
}
Client-Side Usage
The authentication client is available via lib/auth-client.ts:
import { authClient , signIn , signUp , signOut , useSession } from "@/lib/auth-client" ;
// In React components
const { data : session , isPending } = useSession ();
// Sign up
await signUp . email ({
email: "[email protected] " ,
password: "secure-password" ,
name: "John Doe"
});
// Sign in
await signIn . email ({
email: "[email protected] " ,
password: "secure-password"
});
// Sign out
await signOut ();
Core Endpoints
Sign Up Create a new user account with email and password
Sign In Authenticate with email and password
Sign Out End the current session
Verify Email Verify user email address with token
Reset Password Request and complete password reset
Get Session Retrieve current user session
Sign Up
Create a new user account with email and password. Sends a verification email and creates a workspace automatically.
Request Body
User’s email address (must be unique)
User’s password (minimum 8 characters)
Response
The created user object Email verification status (false initially)
Associated workspace ID (created automatically)
User role in workspace (“owner” for new signups)
Account creation timestamp
The created session (only if auto-sign-in is enabled) Session token (set as HTTP-only cookie)
Session expiration time (7 days from creation)
Example Request
curl -X POST https://yourdomain.com/api/auth/sign-up/email \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected] ",
"password": "SecurePass123!",
"name": "John Doe"
}'
Example Response
{
"user" : {
"id" : "usr_a1b2c3d4e5" ,
"email" : "[email protected] " ,
"name" : "John Doe" ,
"emailVerified" : false ,
"workspaceId" : "wks_x9y8z7w6v5" ,
"role" : "owner" ,
"isSystemAdmin" : false ,
"banned" : false ,
"createdAt" : "2024-01-15T10:30:00Z" ,
"updatedAt" : "2024-01-15T10:30:00Z"
}
}
A verification email is automatically sent to the user’s email address. The user must verify their email before signing in.
Sign In
Authenticate a user with email and password. Creates a new session on successful authentication.
Request Body
Whether to extend session duration (default: false)
Response
The authenticated user object Email verification status
The created session Session token (set as HTTP-only cookie)
Example Request
curl -X POST https://yourdomain.com/api/auth/sign-in/email \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected] ",
"password": "SecurePass123!"
}'
Example Response
{
"user" : {
"id" : "usr_a1b2c3d4e5" ,
"email" : "[email protected] " ,
"name" : "John Doe" ,
"emailVerified" : true ,
"workspaceId" : "wks_x9y8z7w6v5" ,
"role" : "owner" ,
"isSystemAdmin" : false
},
"session" : {
"id" : "ses_p9o8i7u6y5" ,
"token" : "session_token_here" ,
"expiresAt" : "2024-01-22T10:30:00Z"
}
}
If email is not verified, the request will fail with a 403 error. A new verification email is automatically sent.
Sign Out
End the current user session and clear the session cookie.
Session cookie (automatically sent by browser)
Response
Whether the sign-out was successful
Example Request
curl -X POST https://yourdomain.com/api/auth/sign-out \
-H "Cookie: better-auth.session_token=session_token_here"
Example Response
Verify Email
Verify a user’s email address using the token sent via email.
Query Parameters
Email verification token from the verification email
Response
The user object with updated email verification status Updated to true after successful verification
Automatically created session after verification Session token (set as HTTP-only cookie)
Example Request
curl https://yourdomain.com/api/auth/verify-email?token=verify_abc123xyz789
Example Response
{
"user" : {
"id" : "usr_a1b2c3d4e5" ,
"email" : "[email protected] " ,
"emailVerified" : true
},
"session" : {
"token" : "session_token_here" ,
"expiresAt" : "2024-01-22T10:30:00Z"
}
}
After successful verification, the user is automatically signed in with a new session.
Reset Password
Password reset is a two-step process:
Step 1: Request Reset
Request a password reset email with a reset token.
Request Body
Email address of the account to reset
URL to redirect to after reset (default: /reset-password)
Example Request
curl -X POST https://yourdomain.com/api/auth/forget-password \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected] "
}'
Example Response
{
"success" : true ,
"message" : "Password reset email sent"
}
Step 2: Complete Reset
Reset the password using the token from the email.
Request Body
Password reset token from email (valid for 1 hour)
New password (minimum 8 characters)
Example Request
curl -X POST https://yourdomain.com/api/auth/reset-password \
-H "Content-Type: application/json" \
-d '{
"token": "reset_abc123xyz789",
"password": "NewSecurePass123!"
}'
Example Response
{
"success" : true ,
"message" : "Password reset successful"
}
Reset tokens expire after 1 hour. If the token is expired, the user must request a new password reset email.
Get Session
Retrieve the current user session and user information.
Session cookie (automatically sent by browser)
Response
Current session information IP address from session creation
User agent from session creation
Current user information Email verification status
Example Request
curl https://yourdomain.com/api/auth/get-session \
-H "Cookie: better-auth.session_token=session_token_here"
Example Response
{
"session" : {
"id" : "ses_p9o8i7u6y5" ,
"userId" : "usr_a1b2c3d4e5" ,
"expiresAt" : "2024-01-22T10:30:00Z" ,
"ipAddress" : "192.168.1.1" ,
"userAgent" : "Mozilla/5.0..." ,
"createdAt" : "2024-01-15T10:30:00Z" ,
"updatedAt" : "2024-01-15T10:30:00Z"
},
"user" : {
"id" : "usr_a1b2c3d4e5" ,
"email" : "[email protected] " ,
"name" : "John Doe" ,
"emailVerified" : true ,
"workspaceId" : "wks_x9y8z7w6v5" ,
"role" : "owner" ,
"isSystemAdmin" : false
}
}
If the session is older than 1 day (updateAge), it will be automatically refreshed with a new expiration time.
Error Responses
All authentication endpoints return standard error responses:
400 Bad Request
{
"error" : "Validation failed" ,
"message" : "Password must be at least 8 characters"
}
401 Unauthorized
{
"error" : "Invalid credentials" ,
"message" : "Email or password is incorrect"
}
403 Forbidden
{
"error" : "Email not verified" ,
"message" : "Please verify your email before signing in"
}
429 Too Many Requests
{
"error" : "Rate limit exceeded" ,
"message" : "Too many attempts. Please try again later."
}
Security Considerations
Minimum 8 characters
Stored using bcrypt hashing
Never returned in API responses
HTTP-only cookies prevent XSS attacks
7-day expiration with 1-day refresh window
IP address and user agent tracking
Automatic cleanup of expired sessions
Required before first sign-in
Tokens are single-use and time-limited
Verification emails sent on signup and unverified sign-in attempts
Tokens expire after 1 hour
Single-use tokens
Secure token extraction from reset URLs
Next Steps
Session Management Learn about session lifecycle and management
User Management Manage users and workspace roles
Workspace API Work with workspaces and teams
Admin Plugin Admin impersonation and user management