Agent skill
Better Auth
Authentication and session management with Better Auth in LivestockAI
Install this agent skill to your Project
npx add-skill https://github.com/majiayu000/claude-skill-registry/tree/main/skills/other/other/better-auth-captjay98-gemini-livestockai
SKILL.md
Better Auth
LivestockAI uses Better Auth for authentication. It provides secure session management with email/password authentication.
Table Structure
Better Auth uses two tables:
| Table | Purpose |
|---|---|
users |
User profile data (name, email, role) - NO password |
account |
Authentication credentials (password, providerId) |
Important: Passwords are stored in account, not users.
Creating Users Programmatically
ALWAYS use the createUserWithAuth helper:
import { createUserWithAuth } from '~/lib/db/seeds/helpers'
const result = await createUserWithAuth(db, {
email: '[email protected]',
password: 'securepassword',
name: 'John Doe',
role: 'user', // or 'admin'
})
This helper:
- Hashes the password using PBKDF2 (100,000 iterations, SHA-256)
- Creates entry in
userstable - Creates entry in
accounttable withproviderId: 'credential'
Wrong Way
// ❌ WRONG - users table has no password field!
await db
.insertInto('users')
.values({
email: '[email protected]',
password: 'hashedpassword', // This field doesn't exist!
})
.execute()
Auth Configuration
The auth config is in app/features/auth/config.ts:
import { betterAuth } from 'better-auth'
export const auth = betterAuth({
database: {
type: 'postgres',
url: process.env.DATABASE_URL,
},
emailAndPassword: {
enabled: true,
},
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 1 day
},
})
Server Middleware
Use requireAuth() in server functions:
export const myServerFn = createServerFn({ method: 'GET' }).handler(
async () => {
const { requireAuth } = await import('../auth/server-middleware')
const session = await requireAuth()
// session.user contains:
// - id: string
// - email: string
// - name: string
// - role: 'user' | 'admin'
return { userId: session.user.id }
},
)
Auth Utilities
// app/features/auth/utils.ts
// Check if user has access to a farm
export async function checkFarmAccess(
userId: string,
farmId: string,
): Promise<boolean>
// Get all farms a user has access to
export async function getUserFarms(userId: string): Promise<string[]>
Client-Side Auth
import { useSession, signIn, signOut } from '~/features/auth/client'
function LoginButton() {
const { data: session, isLoading } = useSession()
if (isLoading) return <Spinner />
if (session) {
return (
<Button onClick={() => signOut()}>
Sign Out ({session.user.email})
</Button>
)
}
return (
<Button onClick={() => signIn('credential', { email, password })}>
Sign In
</Button>
)
}
Protected Routes
The _auth.tsx layout protects routes:
// app/routes/_auth.tsx
export const Route = createFileRoute('/_auth')({
beforeLoad: async () => {
const session = await getSession()
if (!session) {
throw redirect({ to: '/login' })
}
return { session }
},
})
User Roles
LivestockAI supports roles:
| Role | Access |
|---|---|
user |
Standard farm access |
admin |
Full system access |
extension_agent |
District-level view |
// Check role in server function
const session = await requireAuth()
if (session.user.role !== 'admin') {
throw new AppError('ACCESS_DENIED')
}
Session Data
The session object contains:
interface Session {
user: {
id: string
email: string
name: string
role: 'user' | 'admin' | 'extension_agent'
image?: string
}
expires: Date
}
Related Skills
three-layer-architecture- Auth in server layererror-handling- Auth error handlingtanstack-start- Server function patterns
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
agent-ops-spec
Manage specification documents in .agent/specs/. Use when user provides requirements, acceptance criteria, or feature descriptions that need to be tracked and validated against implementation.
agent-ops-state
Maintain .agent state files. Use at session start, after meaningful steps, and before concluding: read/update constitution/memory/focus/issues/baseline consistently.
agent-ops-spec
Manage specification documents in .agent/specs/. Use when user provides requirements, acceptance criteria, or feature descriptions that need to be tracked and validated against implementation.
agent-ops-testing
Test strategy, execution, and coverage analysis. Use when designing tests, running test suites, or analyzing test results beyond baseline checks.
agent-ops-testing
Test strategy, execution, and coverage analysis. Use when designing tests, running test suites, or analyzing test results beyond baseline checks.
agent-ops-state
Maintain .agent state files. Use at session start, after meaningful steps, and before concluding: read/update constitution/memory/focus/issues/baseline consistently.
Didn't find tool you were looking for?