Authentication Overview
Understanding authentication in DeesseJS
Authentication Overview
DeesseJS includes a built-in authentication system that provides secure user management and access control for your admin dashboard and application.
Features
Built-in Authentication
- Admin Dashboard Access: Secure login for the admin panel
- Role-Based Access Control: Define user roles and permissions
- Session Management: Secure session handling with configurable expiration
- Password Security: Strong password hashing with bcrypt
- Two-Factor Authentication: Optional 2FA for enhanced security
User Management
- User Creation: Create users programmatically or through the dashboard
- Password Reset: Built-in password reset functionality
- Email Verification: Optional email verification for new accounts
- Session Management: View and manage active sessions
Getting Started
Initial Setup
When you create a new DeesseJS project with npx create-deesse-app, you'll be prompted to create your first admin user:
npx create-deesse-app my-app
# Interactive prompts:
? Enter your database connection string: postgresql://user:password@localhost:5432/mydb
? Create first admin user
? Admin email: admin@example.com
? Admin password: ********
? Confirm password: ********
✓ Admin user created successfully
✓ Database configuredDatabase Configuration
The authentication system requires a database connection. Your database URL should be set in .env.local:
# .env.local
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"User Table
DeesseJS automatically creates a users table in your database:
// Generated schema
model User {
id String @id @default(cuid())
email String @unique
password String // Hashed with bcrypt
name String?
role String @default("author")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
posts Post[]
}Default Roles
DeesseJS includes four default roles:
| Role | Permissions |
|---|---|
| Admin | Full access to all features and settings |
| Editor | Can create, edit, and publish all content |
| Author | Can create and edit own content only |
| Viewer | Read-only access to content |
Admin Dashboard Access
Login URL
Access the admin dashboard at /admin:
# Development
http://localhost:3000/admin
# Production
https://yourdomain.com/adminDefault Admin User
If you didn't create an admin user during setup, you can create one manually:
import { db } from '@deessejs/db'
import { hashPassword } from '@deessejs/auth'
await db.users.create({
data: {
email: 'admin@example.com',
password: await hashPassword('secure-password'),
role: 'admin',
},
})Configuration
Basic Configuration
Configure authentication in deesse.config.ts:
import { defineConfig } from '@deessejs/core'
export const config = defineConfig({
auth: {
// Session configuration
session: {
maxAge: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 24 hours
},
// Password requirements
passwordPolicy: {
minLength: 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSpecialChars: false,
},
},
})Two-Factor Authentication
Enable 2FA for enhanced security:
auth: {
twoFactor: {
enabled: true,
issuer: 'MyApp', // App name shown in authenticator
digits: 6,
period: 30,
},
}Users can enable 2FA in their profile settings using an authenticator app like Google Authenticator or Authy.
Session Management
Session Configuration
auth: {
session: {
maxAge: 60 * 60 * 24 * 7, // Session duration (7 days)
updateAge: 60 * 60 * 24, // Update session every 24 hours
cookieName: 'deesse-session',
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
sameSite: 'lax',
},
}Session Strategy
DeesseJS uses database sessions by default:
- Sessions stored in the database
- Automatic cleanup of expired sessions
- View active sessions in the admin dashboard
- Revoke sessions remotely
Password Management
Password Hashing
Passwords are automatically hashed using bcrypt:
import { hashPassword, verifyPassword } from '@deessejs/auth'
// Hash a password
const hashed = await hashPassword('plain-password')
// Verify a password
const isValid = await verifyPassword('plain-password', hashed)Password Reset Flow
Built-in password reset functionality:
- User requests password reset
- DeesseJS sends reset email with token
- User clicks link and enters new password
- Token is validated and password updated
// Request password reset
await requestPasswordReset('user@example.com')
// Reset password with token
await resetPassword(token, 'new-password')Protecting Routes
Admin Dashboard Routes
Admin routes are automatically protected. Users must be logged in to access /admin.
Protecting API Routes
// app/api/protected/route.ts
import { getServerSession } from '@deessejs/auth'
import { NextResponse } from 'next/server'
export async function GET() {
const session = await getServerSession()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
return NextResponse.json({ data: 'protected data' })
}Protecting Server Components
// app/protected/page.tsx
import { getServerSession } from '@deessejs/auth'
import { redirect } from 'next/navigation'
export default async function ProtectedPage() {
const session = await getServerSession()
if (!session) {
redirect('/login')
}
return <div>Welcome, {session.user.name}!</div>
}Custom Authentication
Using NextAuth.js
Integrate with NextAuth.js for social logins:
// deesse.config.ts
export const config = defineConfig({
auth: {
provider: 'nextauth',
nextAuth: {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
},
},
})Custom Auth Provider
Create a custom authentication provider:
// lib/custom-auth.ts
import { AuthProvider } from '@deessejs/auth'
export const customAuthProvider: AuthProvider = {
async authenticate(credentials) {
// Custom authentication logic
const user = await validateWithExternalService(credentials)
return user
},
async getSession(token) {
// Custom session retrieval
return await getSessionFromToken(token)
},
}Next Steps
- Learn about User Management
- Configure Role-Based Access Control
- Explore Security Best Practices