identity_ui_service
v1.0.3
Published
Reusable authentication module for Nuxt applications with Pinia store, composables, and utilities
Maintainers
Readme
Identity UI Service
A reusable authentication module for Nuxt applications with Pinia store, composables, and utilities
Identity UI Service is a comprehensive authentication module for Nuxt 3 that provides a complete authentication system including login, registration, OTP verification, password reset, session management, and more. It's designed to be shared across multiple Nuxt applications with a consistent authentication interface.
✨ Features
- 🔐 Complete Authentication Flow - Login, registration, OTP verification, password reset
- 🎯 Pinia Store Integration - Centralized state management with reactive computed values
- 🧩 Auto-imported Composable - Use
useAuth()anywhere without imports - 📦 TypeScript Support - Full type definitions included
- 🍪 Session Management - Cookie-based sessions with configurable expiry
- 🔒 Device Fingerprinting - Automatic device registration for security
- 🌍 Multi-country Support - Phone number validation for multiple countries
- ✅ Form Validation - Built-in validation for login, registration, and OTP forms
- 🚀 Auto-initialization - Automatically checks for existing sessions on app load
- 📱 Reactive State - All state is reactive and updates automatically
📦 Installation
Step 1: Install the module
npm install identity_ui_service
# or
pnpm add identity_ui_service
# or
yarn add identity_ui_serviceStep 2: Install peer dependencies
npm install @pinia/nuxt pinia
# or
pnpm add @pinia/nuxt pinia
# or
yarn add @pinia/nuxt pinia🚀 Quick Start
1. Configure in nuxt.config.ts
export default defineNuxtConfig({
modules: [
'@pinia/nuxt', // Required: Pinia must be installed first
'identity_ui_service',
],
federation: {
// REQUIRED: Base URL for your identity API
// Note: Config key is 'federation' even though package name is 'identity_ui_service'
baseIdentityUrl: 'https://api.example.com',
// Optional: Default language (default: 'en')
language: 'en',
// Optional: Default country code (default: 'ug')
countryCode: 'ug',
// Optional: Session expiry in days (default: 3)
sessionExpiryDays: 3,
},
})2. Use in your components
<script setup>
const {
login,
isAuthenticated,
user,
isLoading,
error,
} = useAuth()
// Login example
const handleLogin = async () => {
const result = await login({
msisdn: 256700000000,
password: 'your-password',
country_code: 'ug',
})
if (result.success) {
// Successfully logged in
console.log('User:', result.data)
} else if (result.needsOTP) {
// OTP required
navigateTo('/verify-otp')
} else {
// Handle error
console.error('Login failed:', result.error)
}
}
</script>
<template>
<div v-if="isLoading">Loading...</div>
<div v-else-if="isAuthenticated">
<p>Welcome, {{ user?.first_name }}!</p>
<button @click="logout">Logout</button>
</div>
<div v-else>
<button @click="handleLogin">Login</button>
</div>
</template>📖 Configuration
Module Options
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| baseIdentityUrl | string | ✅ Yes | - | Base URL for your identity API |
| language | string | ❌ No | 'en' | Default language for API requests |
| countryCode | string | ❌ No | 'ug' | Default country code |
| sessionExpiryDays | number | ❌ No | 3 | Session cookie expiry in days |
Configuration Priority
The module reads baseIdentityUrl in this order (highest to lowest priority):
- Module option:
federation.baseIdentityUrl(config key isfederation) - Runtime config:
runtimeConfig.public.baseIdentityUrl - Environment variable:
NUXT_PUBLIC_BASE_IDENTITY_URL
Note: The module configuration key is
federationeven though the package name isidentity_ui_service. This maintains backward compatibility and is the internal module identifier.
Using Environment Variables
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@pinia/nuxt', 'identity_ui_service'],
federation: {
baseIdentityUrl: process.env.NUXT_PUBLIC_BASE_IDENTITY_URL,
},
})# .env
NUXT_PUBLIC_BASE_IDENTITY_URL=https://api.example.com🎯 API Reference
useAuth() Composable
The composable is auto-imported, so you can use it directly without importing.
Authentication Methods
// Login
const result = await login(loginData: LoginRequest)
// Register
const result = await register(registrationData: RegistrationRequest)
// Verify OTP
const result = await verifyOTP(otpData: OTPVerificationRequest)
// Forgot Password
const result = await forgotPassword(forgotData: ForgotPasswordRequest)
// Reset Password
const result = await resetPassword(resetData: PasswordResetRequest)
// Self-exclude user
const result = await selfExclude(exclusionData: SelfExclusionRequest)
// Logout
logout()
// Check session
const hasSession = checkSession()
// Initialize auth (called automatically)
initAuth()Reactive State
const {
// Authentication state
isAuthenticated, // Computed: boolean
isLoggedIn, // Computed: boolean
isLoading, // Computed: boolean
user, // Computed: Identity | null
error, // Computed: string | null
// User information
userId, // Computed: number | null
userMsisdn, // Computed: string
userFullName, // Computed: string
userReferralCode, // Computed: string
userAuthToken, // Computed: string | null
} = useAuth()Session Management
// Set user manually
setUser(userData: Identity)
// Clear user data
clearUser()
// Clear error
clearError()📝 Type Definitions
All TypeScript types are exported and available:
import type {
Identity,
LoginRequest,
RegistrationRequest,
OTPVerificationRequest,
PasswordResetRequest,
ForgotPasswordRequest,
SelfExclusionRequest,
MetaDataRequest,
} from 'identity_ui_service'🔄 Authentication Flow Examples
Login Flow
const { login, verifyOTP } = useAuth()
// Step 1: Login
const loginResult = await login({
msisdn: 256700000000,
password: 'password123',
country_code: 'ug',
})
if (loginResult.success) {
// Success - user is logged in
navigateTo('/dashboard')
} else if (loginResult.needsOTP) {
// OTP required
navigateTo('/verify-otp')
}Registration Flow
const { register, verifyOTP } = useAuth()
// Step 1: Register
const registerResult = await register({
msisdn: 256700000000,
password: 'password123',
first_name: 'John',
last_name: 'Doe',
country_code: 'ug',
})
if (registerResult.needsOTP) {
// OTP sent - verify it
const otpResult = await verifyOTP({
msisdn: 256700000000,
code: 1234,
country_code: 'ug',
})
if (otpResult.success) {
navigateTo('/dashboard')
}
}Password Reset Flow
const { forgotPassword, resetPassword } = useAuth()
// Step 1: Request reset code
await forgotPassword({
msisdn: 256700000000,
country_code: 'ug',
})
// Step 2: Reset password with code
const result = await resetPassword({
msisdn: 256700000000,
code: 1234,
password: 'newPassword123',
country_code: 'ug',
})
if (result.success) {
navigateTo('/login')
}🌍 Supported Countries
The module supports phone number validation for:
- 🇺🇬 Uganda (ug)
- 🇰🇪 Kenya (ke) - uncomment in store to enable
- 🇳🇬 Nigeria (ng) - uncomment in store to enable
- 🇨🇩 DRC (cd) - uncomment in store to enable
- 🇨🇲 Cameroon (cm) - uncomment in store to enable
🔧 Advanced Usage
Direct Store Access
If you need direct access to the Pinia store:
import { useAuthStore } from 'identity_ui_service/dist/runtime/stores/authStore'
const authStore = useAuthStore()
// Access store methods and state directlyCustom Endpoints
You can extend the store to customize endpoints or add new functionality.
📚 Documentation
- Usage Guide - Detailed usage instructions
- Module Structure - Architecture and implementation details
- Publishing Guide - How to publish and share the module
- Quick Start - Quick reference guide
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Run tests
npm run test
# Run linting
npm run lint
# Build
npm run prepack📄 License
MIT License
🙏 Credits
Built for Nuxt 3
