@meistrari/auth-nuxt
v2.4.0
Published
A Nuxt module that provides comprehensive authentication, organization management, and API key capabilities.
Keywords
Readme
@meistrari/auth-nuxt
A Nuxt module that provides comprehensive authentication, organization management, and API key capabilities.
Installation
npm install @meistrari/auth-nuxtPrerequisites
Before setting up the SDK, make sure the following are configured in the Auth API:
- Allowed Origins: Your application URL (e.g.,
https://your-app.com) must be added to the allowed origins list in the Auth API. This ensures the Auth API accepts requests from your application. - Allowed Email Domains: The email domains of users who will access the application must be added to the allowed email domains list in the Auth API. For example, if your users sign in with
@company.comemails, that domain must be whitelisted.
Setup
Add the module to your nuxt.config.ts:
export default defineNuxtConfig({
modules: ['@meistrari/auth-nuxt'],
telaAuth: {
apiUrl: 'https://your-auth-api.com',
jwtCookieName: 'tela-jwt', // Optional: custom JWT cookie name
skipServerMiddleware: false, // Optional: skip automatic server middleware
}
})Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiUrl | string | Required | Base URL of your authentication API |
| jwtCookieName | string | 'tela-jwt' | Name of the JWT cookie |
| skipServerMiddleware | boolean | false | Skip automatic server-side auth context setup |
Composables
The SDK provides three main composables for different aspects of authentication and organization management:
useTelaSession
Manages user sessions, authentication, and sign-in/sign-out operations.
<script setup>
const { user, session, signOut, getToken } = useTelaSession()
// Access current user
console.log(user.value) // User object or null
// Access current session
console.log(session.value) // Session object or null
// Get a valid JWT token
const token = await getToken()
// Sign out
await signOut(() => {
console.log('User signed out')
})
</script>
<template>
<div v-if="user">
Welcome, {{ user.name }}!
<button @click="signOut">
Sign Out
</button>
</div>
<div v-else>
Please sign in
</div>
</template>Available Methods
Session Management:
getSession()- Retrieves the current user sessiongetToken()- Retrieves a valid JWT token (refreshes if needed)signOut(callback?)- Signs out the user
Authentication Methods:
signInWithEmailAndPassword(options)- Email/password authenticationsignInWithSocialProvider(options)- Social authentication (Google, Microsoft)signInWithSaml(options)- SAML-based SSO authentication
Password Management:
requestPasswordReset(email, callbackURL)- Initiates password resetresetPassword(token, password)- Completes password reset
Sign-In Examples
Email and Password:
await signInWithEmailAndPassword({
email: '[email protected]',
password: 'secure-password',
})Social Authentication:
await signInWithSocialProvider({
provider: 'google', // or 'microsoft'
callbackURL: '/',
errorCallbackURL: '/login?error=true'
})SAML SSO:
await signInWithSaml({
email: '[email protected]',
callbackURL: '/',
errorCallbackURL: '/login?error=true'
})useTelaOrganization
Manages organizations, members, invitations, and teams.
<script setup>
const {
activeOrganization,
activeMember,
getActiveOrganization,
setActiveOrganization,
inviteUserToOrganization
} = useTelaOrganization()
// Get the active organization
await getActiveOrganization()
// Switch organizations
await setActiveOrganization('org-id')
// Invite a user
await inviteUserToOrganization({
userEmail: '[email protected]',
role: 'member'
})
</script>
<template>
<div v-if="activeOrganization">
<h2>{{ activeOrganization.name }}</h2>
<p>{{ activeOrganization.members.length }} members</p>
</div>
</template>Available Methods
Organization Management:
getActiveOrganization()- Gets the current active organization with members, invitations, and teamslistOrganizations()- Lists all organizations for the usersetActiveOrganization(id)- Sets the active organizationupdateOrganization(payload)- Updates organization details (name, logo, settings)
Member Management:
listMembers(options?)- Lists organization members with paginationgetActiveMember()- Gets the current user's member recordinviteUserToOrganization(options)- Invites a user to the organizationremoveUserFromOrganization(options)- Removes a user from the organizationupdateMemberRole(options)- Updates a member's roleacceptInvitation(id)- Accepts an organization invitationcancelInvitation(id)- Cancels a pending invitation
Team Management:
createTeam(payload)- Creates a new teamupdateTeam(id, payload)- Updates team detailsdeleteTeam(id)- Deletes a teamlistTeams()- Lists all teamslistTeamMembers(id)- Lists members of a specific teamaddTeamMember(teamId, userId)- Adds a user to a teamremoveTeamMember(teamId, userId)- Removes a user from a team
Organization Examples
Update Organization:
await updateOrganization({
name: 'New Organization Name',
logo: 'https://example.com/logo.png',
settings: { /* custom settings */ }
})Invite Member:
await inviteUserToOrganization({
userEmail: '[email protected]',
role: 'admin', // or 'member', 'reviewer'
teamId: 'team-id', // optional
resend: false // optional: resend if invitation exists
})Create and Manage Teams:
// Create team
const team = await createTeam({
name: 'Development Team'
})
// Add member to team
await addTeamMember(team.id, 'user-id')
// List team members
const members = await listTeamMembers(team.id)useTelaApiKey
Manages API keys for programmatic access.
<script setup>
const {
listApiKeys,
createApiKey,
deleteApiKey
} = useTelaApiKey()
// List all API keys
const apiKeys = await listApiKeys()
// Create a new API key
const newKey = await createApiKey({
name: 'Production API Key',
expiresIn: '90d',
prefix: 'prod',
metadata: { environment: 'production' }
})
// Delete an API key
await deleteApiKey('key-id')
</script>
<template>
<div v-for="key in apiKeys" :key="key.id">
<span>{{ key.name }}</span>
<button @click="deleteApiKey(key.id)">
Delete
</button>
</div>
</template>Available Methods
listApiKeys()- Lists all API keys for the current usergetApiKey(id)- Retrieves a specific API keycreateApiKey(payload)- Creates a new API keyupdateApiKey(payload)- Updates an API key (name)deleteApiKey(id)- Deletes an API key
Server-Side Usage
The SDK automatically sets up server-side authentication context for API routes.
Using Authentication Context
// server/api/protected.ts
export default defineEventHandler(async (event) => {
// Authentication context is automatically available
const { user, workspace } = event.context.auth
if (!user) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized'
})
}
return {
message: `Hello, ${user.email}!`,
userId: user.id
}
})Custom Middleware
Create custom server middleware using the provided helper:
// server/middleware/custom.ts
import { meistrariAuthMiddleware } from '@meistrari/auth-nuxt/server/middleware/auth'
export default meistrariAuthMiddleware(async (event) => {
// event.context.auth contains user and workspace
const { user, workspace } = event.context.auth
// Your custom logic here
if (user) {
console.log(`Authenticated user: ${user.email}`)
}
})Types
The SDK exports comprehensive TypeScript types from the core package:
import type {
User,
Session,
Organization,
FullOrganization,
Member,
Invitation,
Team,
TeamMember,
ApiKey,
CreateApiKeyPayload,
UpdateApiKeyPayload,
CreateTeamPayload,
UpdateTeamPayload,
InviteUserToOrganizationOptions,
RemoveUserFromOrganizationOptions,
UpdateMemberRoleOptions,
UpdateOrganizationPayload
} from '@meistrari/auth-nuxt/core'Key Types
- User: User account information including email, name, and verification status
- Session: Active session data with expiration and organization info
- Organization: Basic organization entity
- FullOrganization: Organization with members, invitations, and teams
- Member: Organization member with role and team assignments
- Team: Team entity within an organization
- Invitation: Pending organization invitations
- ApiKey: API key entity with metadata
JWT Token Management
The SDK automatically manages JWT tokens:
- Stores JWT tokens in cookies (configurable name)
- Refreshes tokens before expiration (every 60 seconds)
- Validates tokens client-side and server-side
- Provides
getToken()method for accessing valid tokens
The handshake flow ensures secure authentication:
- On initial visit without a token, redirects to auth API for handshake
- Auth API validates the session and redirects back with a nonce
- SDK exchanges the nonce for a JWT token
- Token is stored in a cookie and used for subsequent requests
Utilities
Token Validation
import { isTokenExpired, validateToken, extractTokenPayload } from '@meistrari/auth-nuxt/core'
// Check if token is expired
if (isTokenExpired(jwtToken)) {
// Token needs refresh
}
// Validate token against JWKS endpoint
const isValid = await validateToken(jwtToken, 'https://your-api.com')
// Extract token payload (without validation)
const payload = extractTokenPayload(jwtToken)
console.log(payload.user, payload.workspace)Security Features
- JWT Validation: Cryptographic validation using JWKS
- Secure Cookies: HTTP-only, secure cookies in production
- Token Refresh: Automatic token rotation every 60 seconds
- Session Management: Secure session handling with handshake flow
- Server-Side Validation: Middleware validates tokens on every API request
Error Handling
The SDK handles common authentication errors automatically:
- Expired tokens trigger sign-out when refresh fails
- Invalid tokens result in
nulluser/session values - Network errors are handled gracefully
- API errors can be caught and handled in your code
import { APIError } from '@meistrari/auth-nuxt/core'
try {
await signInWithEmailAndPassword({
email: '[email protected]',
password: 'wrong-password',
})
}
catch (error) {
if (error instanceof APIError) {
console.error('Authentication failed:', error.message, error.status)
}
}Migration
If upgrading from a previous version:
- Update package name to
@meistrari/auth-nuxt - Change config key from
authSdktotelaAuth - Replace
useMeistrariAuth()with appropriate composable:useTelaSession()for authenticationuseTelaOrganization()for organization managementuseTelaApiKey()for API key management
- Update cookie name if using custom value (default is now
tela-jwt) - Remove
useJwtandisDevelopmentoptions (no longer needed)
