mern-authentication
v1.0.0
Published
A flexible and customizable authentication library for Node.js applications using MongoDB, with built-in validation using Zod.
Downloads
18
Maintainers
Readme
User Authentication Library
A flexible and customizable authentication library for Node.js applications using MongoDB, with built-in validation using Zod.
Features
- 🔐 Secure user authentication with JWT
- 🎯 Custom schema definition support
- ✅ Customizable validation rules using Zod
- 🔄 Built-in password hashing
- 🎨 Flexible user model configuration
- 🚀 Easy integration with Express/Node.js applications
Installation
npm install user-authenctication
Quick Start
const UserAuth = require('user-authenctication');
const { z } = require('zod');
const auth = new UserAuth({
schemaDefinition: {
email: { type: String, required: true },
password: { type: String, required: true },
name: { type: String, required: true }
},
databaseUrl: 'mongodb://localhost:27017/your-db',
jwtExpiration: '7d',
validationRules: {
login: {
email: {
validation: z.string().email(),
message: 'Valid email is required'
},
password: {
validation: z.string().min(6),
message: 'Password must be at least 6 characters'
}
},
register: {
email: {
validation: z.string().email(),
message: 'Valid email is required'
},
password: {
validation: z.string().min(6),
message: 'Password must be at least 6 characters'
},
name: {
validation: z.string().min(2),
message: 'Name is required'
}
}
}
});
Configuration Options
| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | schemaDefinition | Object | Yes | - | MongoDB schema definition | | databaseUrl | String | Yes | - | MongoDB connection URL | | jwtSecret | String | No | "default_jwt_secret" | Secret key for JWT | | jwtExpiration | String | Yes | "7d" | JWT token expiration time | | cookieName | String | No | "jwt_token" | Name of the JWT cookie | | validationRules | Object | Yes | - | Zod validation rules for login and register |
API Reference
Register User
const { error, user } = await auth.register({
email: '[email protected]',
password: 'password123',
name: 'John Doe'
});
Returns:
error
: Error message if registration failsuser
: Created user object if successful
Login User
const { error, token, user } = await auth.login({
email: '[email protected]',
password: 'password123'
});
Returns:
error
: Error message if login failstoken
: JWT token if login successfuluser
: User object if login successful
Logout User
const { error, message } = await auth.logout({ response: res });
Returns:
error
: Error message if logout failsmessage
: Success message if logout successful
Find User
const { error, user } = await auth.findUser({ email: '[email protected]' });
Returns:
error
: Error message if search failsuser
: User object if found
Update User
const { error, user } = await auth.updateUser({
findQuery: { email: '[email protected]' },
updateQuery: { name: 'New Name' }
});
Returns:
error
: Error message if update failsuser
: Updated user object if successful
Delete User
const { error, user } = await auth.deleteUser({
findQuery: { email: '[email protected]' }
});
Returns:
error
: Error message if deletion failsuser
: Deleted user object if successful
Custom Validation Example
You can customize validation rules using Zod schemas:
const validationRules = {
register: {
email: {
validation: z.string().email().endsWith('@company.com'),
message: 'Must use company email'
},
password: {
validation: z.string()
.min(8)
.regex(/[A-Z]/, 'Need one uppercase letter')
.regex(/[0-9]/, 'Need one number'),
message: 'Password must meet complexity requirements'
}
}
// ... login validation rules
};
Error Handling
The library uses a consistent error handling pattern:
- All methods return an object with
error
property - If operation is successful,
error
will benull
- If operation fails,
error
will contain error message
Database Connection
The library automatically manages database connections:
- Connects on first operation if not connected
- Maintains connection for subsequent operations
- Handles connection errors gracefully
Security Features
- Automatic password hashing using bcrypt
- JWT token generation and validation
- Cookie-based token storage
- Protection against common security vulnerabilities
Best Practices
- Always provide a strong JWT secret in production
- Implement proper error handling in your application
- Use environment variables for sensitive configuration
- Set appropriate JWT expiration times
- Customize validation rules based on your requirements
License
[Your License Here]
Contributing
[Your Contributing Guidelines Here]