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

mira-auth

v1.9.9

Published

A simple authentication library

Downloads

114

Readme

🛡️ Mira-Auth

Simple and Secure Authentication System

Mira-Auth is a powerful and easy-to-use authentication library designed to integrate secure sessions, password hashing, and user management into your application. With minimal setup, you can create sessions, manage users, and securely handle passwords.

Features

  • 🌟 Secure JWT Token Generation and Validation: Create and validate JWT tokens for secure user sessions.
  • 🔐 Password Hashing and Comparison: Hash passwords for storage and compare user input with stored hashes using bcrypt.
  • 🛠️ Simple Setup: Easy to configure with straightforward commands and TypeScript support.
  • 🔑 User Management: Create and retrieve user records with built-in Prisma integration.
  • 🚀 Sign In Functionality: Automatically verifies user existence and compares passwords.

Installation

Prerequisites

  • Node.js
  • npm or Yarn

Installation Steps

  1. Install the Library

    Install mira-auth via npm or Yarn:

    Using npm:

    npm install mira-auth

    Using Yarn:

    yarn add mira-auth
  2. Create a Secret

    Generate a secret and store it in a .env file:

    Using npm:

    npx mira-auth secret

    Using Yarn:

    yarn mira-auth secret

    This command will create a .env file with a secret key (MIRA_SECRET) needed for JWT token generation.

  3. Initialize Mira Instance

    Create a file @/lib/mira.ts and initialize Mira there:

    import { Mira } from 'mira-auth';
    export const mira = new Mira();

    Use this instance throughout your application.

Usage

Creating and Managing Sessions

  • createSession(userId: string, email?: string, role?: string): Creates a JWT token for the specified user.

    import { mira } from '@/lib/mira';
    
    const session = await mira.createSession({ userId: 'user123' });
    console.log(session.id); // JWT Token
  • validateSession(token: string): Validates the JWT token and returns the decoded information.

    import { mira } from '@/lib/mira';
    
    try {
      const decoded = await mira.validateSession(token);
      console.log(decoded); // Decoded user data
    } catch (error) {
      console.error(error.message); // Error handling
    }

Password Hashing

  • hashPassword(password: string): Hashes a password for secure storage.

    import { mira } from '@/lib/mira';
    
    const hashedPassword = await mira.hashPassword('mysecurepassword');
    console.log(hashedPassword); // Hashed password
  • comparePasswords(submittedPassword: string, storedPassword: string): Compares an input password with a stored hashed password.

    import { mira } from '@/lib/mira';
    
    const isMatch = await mira.comparePasswords('mysecurepassword', hashedPassword);
    console.log(isMatch); // true or false

Creating and Retrieving Users

  • createUser(data: { email: string, password: string, role?: string }): Creates a new user. The password is automatically hashed during creation.

    import { mira } from '@/lib/mira';
    
    const user = await mira.createUser({ email: '[email protected]', password: 'mypassword' });
    console.log(user.id); // ID of the newly created user
  • getUserById(userId: string): Retrieves user data by ID.

    import { mira } from '@/lib/mira';
    
    const user = await mira.getUserById('user123');
    console.log(user); // User data
  • getUserByEmail(email: string): Retrieves user data by email.

    import { mira } from '@/lib/mira';
    
    const user = await mira.getUserByEmail('[email protected]');
    console.log(user); // User data

Sign In and Sign Out

  • signIn(email: string, password: string): Authenticates a user by checking if the user exists and verifying the password. Creates a session if authentication is successful.

    import { mira } from '@/lib/mira';
    
    const response = await mira.signIn('[email protected]', 'mypassword');
    console.log(response); // Success or error message
  • signOut(): Signs out a user by clearing the session cookie.

    import { mira } from '@/lib/mira';
    
    const response = await mira.signOut();
    console.log(response); // Success message

Database Integration

Mira-Auth uses Prisma for ORM functionality, and the Prisma client is integrated into the package. The Prisma schema for user management is embedded in Mira-Auth:

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        String   @id @default(uuid())
  email     String   @unique
  password  String
  role      String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Future Support for Drizzle

Support for Drizzle, a lightweight ORM, is planned for a future update. Drizzle offers a simpler API and may be more suitable for smaller applications.

Architecture

Mira-Auth uses jsonwebtoken for token generation and validation, and bcrypt for password hashing. The library is written in TypeScript for a clear and simple API.

Folder Structure

mira-auth/
├── dist/
│   ├── bin/
│   │   └── mira.js        # Transpiled CLI commands
│   ├── db.js              # Transpiled prisma initialization
│   ├── errors.js          # Transpiled error handling logic
│   ├── handlers.js        # Transpiled request api handlers
│   ├── index.js           # Main entry point
│   ├── middleware.js      # Transpiled middleware
│   ├── mira.js            # Transpiled mira class
│   ├── provider.js        # Transpiled provider component
│   └── types/
│       ├── bin/
│       │   └── mira.d.ts  # TypeScript declaration for CLI commands
│       ├── db.d.ts        # TypeScript declaration for prisma initialization
│       ├── errors.d.ts    # TypeScript declaration for error handling
│       ├── handlers.d.ts  # TypeScript declaration for request api handlers
│       ├── index.d.ts     # TypeScript declaration for main entry point
│       ├── middleware.d.ts# TypeScript declaration for middleware
│       ├── mira.d.ts      # TypeScript declaration for mira class
│       └── provider.d.ts  # TypeScript declaration for provider component
├── package.json           # npm configuration file
├── LICENSE.md             # License file
├── README.md              # This file
└── CONTRIBUTING.md        # Contribution guidelines

Contributing

We welcome contributions! Please check our CONTRIBUTING.md for details on how to contribute.

License

This project is licensed under the MIT License. See the LICENSE file for more information.

Package Status

npm version

Contact