apyrn-utils
v0.0.7
Published
Utility package for Google OAuth integration and email notifications
Downloads
29
Maintainers
Readme
apyrn-utils
A utility package for common features like Google OAuth integration, email notifications, and more.
Features
- Google OAuth 2.0 authentication with Passport.js
- Email notification system using Nodemailer
- 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
import { EmailService } from 'apyrn-utils';
const emailService = new EmailService({
host: 'smtp.example.com',
port: 587,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
// Send an email
await emailService.sendEmail({
to: '[email protected]',
subject: 'Welcome!',
text: 'Hello! Welcome to our service.',
html: '<h1>Welcome!</h1><p>Hello! Welcome to our service.</p>'
});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
# Email
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your_username
SMTP_PASS=your_password
# 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.
