1.0.0 • Published 9 months ago

mern-authentication v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

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

OptionTypeRequiredDefaultDescription
schemaDefinitionObjectYes-MongoDB schema definition
databaseUrlStringYes-MongoDB connection URL
jwtSecretStringNo"default_jwt_secret"Secret key for JWT
jwtExpirationStringYes"7d"JWT token expiration time
cookieNameStringNo"jwt_token"Name of the JWT cookie
validationRulesObjectYes-Zod validation rules for login and register

API Reference

Register User

const { error, user } = await auth.register({
  email: 'user@example.com',
  password: 'password123',
  name: 'John Doe'
});

Returns:

  • error: Error message if registration fails
  • user: Created user object if successful

Login User

const { error, token, user } = await auth.login({
  email: 'user@example.com',
  password: 'password123'
});

Returns:

  • error: Error message if login fails
  • token: JWT token if login successful
  • user: User object if login successful

Logout User

const { error, message } = await auth.logout({ response: res });

Returns:

  • error: Error message if logout fails
  • message: Success message if logout successful

Find User

const { error, user } = await auth.findUser({ email: 'user@example.com' });

Returns:

  • error: Error message if search fails
  • user: User object if found

Update User

const { error, user } = await auth.updateUser({
  findQuery: { email: 'user@example.com' },
  updateQuery: { name: 'New Name' }
});

Returns:

  • error: Error message if update fails
  • user: Updated user object if successful

Delete User

const { error, user } = await auth.deleteUser({
  findQuery: { email: 'user@example.com' }
});

Returns:

  • error: Error message if deletion fails
  • user: 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 be null
  • 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

  1. Always provide a strong JWT secret in production
  2. Implement proper error handling in your application
  3. Use environment variables for sensitive configuration
  4. Set appropriate JWT expiration times
  5. Customize validation rules based on your requirements

License

Your License Here

Contributing

Your Contributing Guidelines Here