npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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

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 fails
  • user: 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 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: '[email protected]' });

Returns:

  • error: Error message if search fails
  • user: 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 fails
  • user: Updated user object if successful

Delete User

const { error, user } = await auth.deleteUser({
  findQuery: { email: '[email protected]' }
});

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]