@apyrn/utils
v0.0.13
Published
Utility package for Google OAuth integration, email notifications, and ZeptoMail integration with template engine
Maintainers
Readme
apyrn-utils
A utility package for common features like Google OAuth integration, email notifications (including ZeptoMail), and more.
Features
- Google OAuth 2.0 authentication with Passport.js
- Email notification system using Nodemailer
- ZeptoMail integration for reliable email delivery
- Email template engine with pre-built business templates
- Rate limiting protection
- PostgreSQL integration
- Express.js middleware support
- Winston logging integration
- Feature toggles
- Monitoring utilities
- Environment-based configuration
Installation
npm install apyrn-utilsUsage
Google OAuth Authentication
The package provides a complete solution for Google OAuth 2.0 authentication using Passport.js with database integration for user management.
Setup
- Configure your Google OAuth credentials:
// Create a GoogleAuthConfig object
const config = {
oauthConfig: {
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
scope: ['profile', 'email']
},
pgConfig: {
host: process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT || '5432'),
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
},
onAuthSuccess: (userData) => {
// Optional callback when authentication succeeds
console.log('User authenticated:', userData);
},
onAuthFailure: (error) => {
// Optional callback when authentication fails
console.error('Authentication failed:', error);
}
};
// Register Google OAuth
const auth = await registerGoogleAuth(config);
// Initialize Express app with authentication middleware
app.use(auth.initialize());
app.use(auth.session());
// Create authentication routes
app.get('/auth/google', auth.authenticate());
app.get('/auth/google/callback', auth.callback());Authentication Flow
- User clicks on the Google login button, triggering
/auth/google - User is redirected to Google's OAuth consent screen
- After authentication, Google redirects back to
/auth/google/callback - The package handles the OAuth callback, user creation/lookup, and session management
- On success, the user is authenticated and their data is stored in the database
- On failure, the user is redirected to
/auth/failureapp.get('/auth/google/callback', auth.callback());
#### Database Integration
The package automatically creates and manages a PostgreSQL table for storing user information:
```sql
CREATE TABLE users_gmail_info (
id SERIAL PRIMARY KEY,
google_id TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)User Management Functions
// Find a user by Google ID
const user = await auth.findUserByGoogleId(googleId);
// Create a new user from Google profile
const newUser = await auth.createUser(userInfo);
// Find or create a user
const user = await auth.findOrCreateUser(userInfo);
// User data structure
interface UserData {
id: number;
google_id: string;
name: string;
email: string;
created_at: Date;
}Error Handling
The package includes comprehensive error handling with specific error types:
try {
const user = await auth.findOrCreateUser(userInfo);
} catch (error) {
if (error instanceof DatabaseError) {
switch (error.type) {
case 'DUPLICATE_KEY':
// Handle duplicate user
break;
case 'NOT_FOUND':
// Handle user not found
break;
// ... other error types
}
}
}
// Database error types:
// - CONNECTION_ERROR
// - QUERY_ERROR
// - DUPLICATE_KEY
// - NOT_FOUND
// - VALIDATION_ERROR
#### Rate Limiting Protection
The authentication service includes built-in rate limiting to prevent abuse:
```typescript
// Configure rate limiting
await auth.configureRateLimit({
points: 100,
duration: 60, // seconds
keyPrefix: 'google_auth_rate_limit'
});
// Check rate limit before authentication
const isLimited = await auth.checkRateLimit(userId);
if (isLimited) {
throw new RateLimitError('Too many authentication attempts');
}Email Notifications
Traditional SMTP (Nodemailer)
import { sendEmail } from 'apyrn-utils';
// Send an email using SMTP
const result = await sendEmail({
transport: {
host: 'smtp.example.com',
port: 587,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
},
email: {
to: '[email protected]',
subject: 'Welcome!',
text: 'Hello! Welcome to our service.',
html: '<h1>Welcome!</h1><p>Hello! Welcome to our service.</p>'
}
});
if (result.success) {
console.log('Email sent successfully:', result.messageId);
} else {
console.error('Failed to send email:', result.error);
}ZeptoMail Integration
ZeptoMail is Zoho's reliable email delivery service. This package provides full integration with ZeptoMail for enhanced email delivery.
import {
sendZeptoEmail,
createZeptoEmailConfig,
createZeptoEmailSender
} from 'apyrn-utils';
// Basic ZeptoMail configuration
const zeptoConfig = {
apiKey: process.env.ZEPTOMAIL_API_KEY,
domain: process.env.ZEPTOMAIL_DOMAIN // Optional
};
// Method 1: Using helper function
const emailConfig = createZeptoEmailConfig(
{ address: '[email protected]', name: 'Your Name' }, // from
['[email protected]'], // to
'Test Email Subject', // subject
'This is a plain text message.', // textBody
'<h1>This is an HTML message</h1>', // htmlBody
{
cc: ['[email protected]'],
trackClicks: true,
trackOpens: true
}
);
const result = await sendZeptoEmail({
transport: zeptoConfig,
email: emailConfig
});
// Method 2: Create reusable sender
const zeptoSender = createZeptoEmailSender(zeptoConfig);
const result2 = await zeptoSender(emailConfig);
// Method 3: Advanced configuration
const advancedResult = await sendZeptoEmail({
transport: zeptoConfig,
email: {
from: { address: '[email protected]', name: 'Your Name' },
to: [
{ email_address: { address: '[email protected]', name: 'Recipient 1' } },
{ email_address: { address: '[email protected]', name: 'Recipient 2' } }
],
subject: 'Advanced ZeptoMail Example',
htmlbody: '<h1>Hello from ZeptoMail!</h1>',
textbody: 'Hello from ZeptoMail!',
track_clicks: true,
track_opens: true,
attachments: [
{
name: 'document.pdf',
content: 'base64-encoded-content-here',
mime_type: 'application/pdf'
}
]
}
});
// Bulk email with throttling
import { sendZeptoEmailWithThrottling } from 'apyrn-utils';
const throttledResult = await sendZeptoEmailWithThrottling(
{ transport: zeptoConfig, email: emailConfig },
{ maxRetries: 3, retryDelayMs: 1000 }
);ZeptoMail Features:
- Reliable email delivery with high deliverability rates
- Built-in tracking for opens and clicks
- Support for attachments
- Advanced recipient management
- Rate limiting and retry logic
- Full TypeScript support
Email Templates
The package includes a comprehensive email template system with pre-built templates for common business scenarios:
import { TemplateEngine, EMAIL_TEMPLATES, createZeptoEmailSender } from 'apyrn-utils';
const templateEngine = new TemplateEngine();
const sender = createZeptoEmailSender({
apiKey: 'your-zepto-api-key',
domain: 'yourdomain.com'
});
// Send signup confirmation email
const signupTemplate = EMAIL_TEMPLATES.SIGNUP_CONFIRMATION;
const params = {
companyName: 'Acme Corp',
name: 'John Doe',
confirmationUrl: 'https://yourdomain.com/confirm?token=abc123',
contactEmail: '[email protected]'
};
const rendered = await templateEngine.renderTemplate(signupTemplate, params);
await sender({
to: ['[email protected]'],
from: { address: '[email protected]', name: 'Acme Corp' },
subject: rendered.subject,
htmlbody: rendered.html,
textbody: rendered.text
});Available Templates:
SIGNUP_CONFIRMATION- Account signup confirmationLOGIN_OTP- One-time password for loginPASSWORD_RESET- Password reset linksORDER_CONFIRMATION- Order confirmation with itemsCART_ABANDONMENT- Cart abandonment remindersPAYMENT_RECEIVED- Payment confirmationSUBSCRIPTION_ACTIVATED- Subscription welcome emails
Template Features:
- Variable substitution with
{{variable}}syntax - Conditional content with
{{#if condition}}...{{/if}} - Loops with
{{#each items}}...{{/each}} - Both HTML and plain text versions
- Full TypeScript support
- Parameter validation
For detailed documentation, see EMAIL_TEMPLATES.md
Rate Limiting
import { RateLimiter } from 'apyrn-utils';
const rateLimiter = new RateLimiter({
points: 100, // Number of points
duration: 1, // Duration in seconds
keyPrefix: 'api_rate_limit'
});
// Check rate limit
const isLimited = await rateLimiter.consume('user123');Logging
import { Logger } from 'apyrn-utils';
const logger = new Logger();
logger.info('This is an info message');
logger.error('This is an error message');Configuration
The package requires several environment variables:
# Google OAuth
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
# Traditional Email (SMTP)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your_username
SMTP_PASS=your_password
# ZeptoMail Configuration
ZEPTOMAIL_API_KEY=your_zeptomail_api_key
ZEPTOMAIL_DOMAIN=your_custom_domain # Optional
# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DB=your_databaseDevelopment
To run the tests:
npm testTo build the package:
npm run buildLicense
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
