Overview
Modelence authentication includes:- Email/Password Authentication - User signup and login with email and password
- Google Sign-In - OAuth authentication with Google accounts
- Session Management - Secure session handling with automatic token rotation
- Email Verification - Optional email verification for new signups
- Password Reset - Secure password reset flow with email tokens
- Rate Limiting - Built-in protection against brute force attacks
- User Management - User profile and role management
How Authentication Works
Session Management
When a user visits your application, Modelence automatically creates a session:- Session Creation - A secure session token is generated using cryptographically random bytes
- Token Storage - The session token is stored in the database and sent to the client
- Automatic Expiration - Sessions expire after 7 days of inactivity
- Heartbeat Updates - Active sessions are automatically renewed through periodic heartbeat requests
_modelenceSessions
collection and tracked with the following properties:
User Authentication Flow
Signup Process
When a user signs up with email and password:- Validation - Email format and password strength are validated
- Duplicate Check - System checks if email already exists
- Password Hashing - Password is securely hashed using bcrypt (never stored in plain text)
- User Creation - User record is created in the
_modelenceUsers
collection - Session Linking - The session is linked to the new user
- Email Verification (Optional) - If enabled, a verification email is sent
Login Process
When a user logs in:- Credential Verification - Email and password are validated against stored credentials
- Session Update - Current session is linked to the authenticated user
- User Data - User information is returned to the client
- State Update - Client-side session state is updated
Basic Implementation
Client-Side Usage
Signup
Login
Logout
Accessing Current User
Server-Side Configuration
Basic Setup
Configure authentication in your startApp call:Auth Callbacks
The AuthConfig type provides hooks for authentication events:Google Sign-In
Modelence supports OAuth authentication with Google, allowing users to sign in with their Google accounts.Prerequisites
Before implementing Google Sign-In, you need to:- Create a project in the Google Cloud Console
- Configure the OAuth consent screen
- Create OAuth 2.0 credentials (Client ID and Client Secret)
- Configure authorized redirect URIs
Google Cloud Console Setup
-
Create a Project
- Go to Google Cloud Console
- Click “Select a project” → “New Project”
- Name your project and click “Create”
-
Configure OAuth Consent Screen
- Go to “APIs & Services” → “OAuth consent screen”
- Choose user type (External for most applications)
- Fill in the required fields:
- App name
- User support email
- Developer contact information
- Click “Save and Continue”
- Add scopes if needed (profile and email are included by default)
- Click “Save and Continue”
-
Create OAuth Credentials
- Go to “APIs & Services” → “Credentials”
- Click “Create Credentials” → “OAuth client ID”
- Select “Web application” as the application type
- Add a name for your OAuth client
-
Configure Redirect URIs
- Under “Authorized JavaScript origins”, add:
http://localhost:3000
(for local development)https://yourdomain.com
(for production)
- Under “Authorized redirect URIs”, add:
http://localhost:3000/api/_internal/auth/google/callback
(for local development)https://yourdomain.com/api/_internal/auth/google/callback
(for production)
- Click “Create”
- Under “Authorized JavaScript origins”, add:
-
Save Credentials
- Copy your Client ID and Client Secret
- Store them securely (use environment variables or Modelence Cloud config)
Server-Side Configuration
Google Sign-In is built into Modelence and requires no additional packages.Option 1: Modelence Cloud (Recommended)
The preferred way to configure Google authentication is through Modelence Cloud:- Go to https://cloud.modelence.com/
- Navigate to your project’s configuration
- Set the following configs:
_system.user.auth.google.enabled
- Set totrue
_system.user.auth.google.clientId
- Your Google Client ID_system.user.auth.google.clientSecret
- Your Google Client Secret
Option 2: Environment Variables
Alternatively, you can use environment variables. Create a.env
file in your project root:
.env
to your .gitignore
file to keep credentials secure.
The Google authentication is automatically enabled when these configurations are set. No additional server code is needed.
Client-Side Implementation
To initiate Google Sign-In, redirect the user to the Google authentication endpoint:UI Integration
Add a Google Sign-In button to your UI:How Google Sign-In Works
- Initiation - User clicks “Sign in with Google” button
- Redirect - User is redirected to Google’s OAuth consent screen
- Authorization - User grants permission to your app
- Callback - Google redirects back to your app with an authorization code
- Token Exchange - Your server exchanges the code for user information
- User Creation/Login - If user doesn’t exist, a new account is created; otherwise, user is logged in
- Session Creation - A session is established and the user is authenticated
User Data Handling
When a user signs in with Google, Modelence automatically:- Creates a user account if one doesn’t exist
- Links the Google account to the user profile
- Retrieves profile information (name, email, profile picture)
- Marks the email as verified (since Google has verified it)
Combining with Email/Password Authentication
Users can have both Google and email/password authentication on the same account:Troubleshooting
Redirect URI Mismatch Error- Ensure the redirect URI in Google Cloud Console exactly matches your application URL
- Check for trailing slashes and http vs https
- Common format:
https://yourdomain.com/api/_internal/auth/google/callback
- Verify your Client ID and Client Secret are correct
- Check that environment variables are properly loaded
- Ensure credentials are from the correct Google Cloud project
- Make sure Google+ API is enabled in your project
- Verify your OAuth consent screen is configured
- Check that your domain is authorized
Email Verification
Email verification adds an extra layer of security by ensuring users own the email address they register with.Enabling Email Verification
First, configure your email provider (see Email Configuration):How It Works
- When a user signs up, a verification token is generated and stored
- An email with a verification link is sent to the user’s email address
- The link contains the token:
https://yourapp.com/api/_internal/auth/verify-email?token=...
- When clicked, the token is validated and the user’s email is marked as verified
- The user is redirected to your configured
redirectUrl
Custom Verification Templates
You can customize the verification email template:Manual Verification
You can also manually trigger email verification from the client:Password Reset
Modelence provides a secure password reset flow with email tokens.Configuration
Configure password reset emails in your server setup:How It Works
- User requests a password reset by providing their email
- A secure reset token is generated and stored in the database
- An email with a reset link is sent to the user
- The link redirects to your app with the token as a query parameter
- User enters their new password along with the token
- Password is updated and token is invalidated
Client Implementation
Request Password Reset
Reset Password with Token
Custom Reset Email Template
Rate Limiting
Modelence includes built-in rate limiting to protect against brute force attacks and abuse. Rate limits are automatically applied to authentication endpoints.Default Rate Limits
- Signup: 20 attempts per 15 minutes, 200 per day (per IP)
- Login: 50 attempts per 15 minutes, 500 per day (per IP)
- Email Verification: 3 attempts per 15 minutes, 10 per day (per user)
Handling Rate Limit Errors
Security Best Practices
Password Security
- Minimum Length: Enforce minimum password length (8+ characters recommended)
- Complexity: Consider requiring mixed case, numbers, or special characters
- Hashing: Passwords are automatically hashed with bcrypt - never store plain text
- No Validation on Client: Always validate passwords on the server
Session Security
- Token Storage: Session tokens are automatically managed - don’t expose them
- HTTPS Only: Always use HTTPS in production to protect session tokens
- Automatic Expiration: Sessions expire after 7 days of inactivity
- Logout: Always provide a clear logout option for users
Email Validation
- Format Validation: Email format is automatically validated
- Disposable Email Detection: Modelence includes protection against disposable email services
- Verification: Enable email verification for sensitive applications
UI Components
Modelence provides pre-built authentication UI components through the @modelence/auth-ui package.API Reference
Client Functions
- signupWithPassword - Sign up with email and password
- loginWithPassword - Log in with email and password
- logout - Log out current user
- useSession - Access current user session
- verifyEmail - Verify email with token
- sendResetPasswordToken - Request password reset
- resetPassword - Reset password with token
Server Types
- AuthConfig - Authentication configuration
- UserInfo - User information type
- dbUsers - User database collection
Error Types
- AuthError - Authentication errors
- ValidationError - Validation errors
- RateLimitError - Rate limit errors
Next Steps
- Learn about Email Configuration to enable verification and password reset
- Explore the @modelence/auth-ui package for pre-built UI components
- Check out the Tutorial for a complete application example
- Review Database documentation for custom user data