1.2.3 • Published 7 months ago

egzix-auth v1.2.3

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

egzix-auth

egzix-auth is a simple, flexible, and easy-to-use authentication library for Express applications, integrating with Prisma and JSON Web Tokens (JWT). It provides authentication routes for login, token validation, registration, account updates, and account deletion. It also allows the ability to include related data from Prisma dynamically based on the user's requirements.

If you face any problem or want further explanation, message me on Instagram @its_egzix.


Features

  • 🚀 Login Authentication: Authenticate users with username and password.
  • 🔐 Secure Password Hashing: Passwords are hashed using js-sha256.
  • 🔑 JWT-based Authentication: Secure token generation with customizable expiration times.
  • 📊 Prisma ORM Support: Integrate with Prisma for database interaction.
  • 🔗 Data Inclusion Support: Dynamically fetch related Prisma fields during authentication.
  • 🛡️ Registration Support: Allows new users to sign up securely.
  • 🖉️ Update User Data: Update user data securely.
  • 🗑️ Delete User Account: Delete user accounts when requested.

Installation

To install egzix-auth, use either npm or yarn:

Using npm:

npm install egzix-auth

Using yarn:

yarn add egzix-auth

Getting Started

Add "type": "module" to package.json

Ensure you include "type": "module" in your package.json to enable ES module support.


Basic Example

Import the library and setup Prisma with Express

import express from "express";
import { PrismaClient } from "@prisma/client";
import createAuthRouter from "egzix-auth";

const app = express();
const prisma = new PrismaClient();

const jwtSecret = "your-secret-key"; // Replace this with an environment variable for better security

// Create authentication routes using your Prisma client and configuration
const authRouter = createAuthRouter({
  prisma,
  jwtSecret,
  tableName: "User",
  usernameField: "username",
  passwordField: "password",
  userIdField: "id",
  prismaMethod: "findUnique",
  tokenExpiration: "1h",
  include: "profile,settings", // Include related fields if necessary
});

// Use the authentication routes
app.use("/auth", authRouter);

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Routes

Below are the routes supported by egzix-auth:


1. Login - POST /auth/login

Authenticates a user with the given credentials and returns a JWT token.

Request:

{
  "username": "user123",
  "password": "user-password"
}

Response (Success):

{
  "success": true,
  "message": "Login successful",
  "token": "your-jwt-token-here"
}

Response (Failure):

{
  "success": false,
  "message": "Invalid username or password"
}

2. Token Validation - GET /auth/token

Validates a JWT token and returns user information (excluding password).

Request:

Include the token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Response (Success):

{
  "success": true,
  "user": {
    "id": 1,
    "username": "user123",
    "profile": {
      "bio": "User bio"
    },
    "settings": {
      "theme": "dark"
    }
  }
}

Response (Failure):

{
  "success": false,
  "message": "Invalid or expired token"
}

3. Registration - POST /auth/register

Allows new users to sign up by providing username and password.

Request:

{
  "username": "newuser123",
  "password": "securepassword"
}

Response (Success):

{
  "success": true,
  "message": "User registered successfully"
}

Response (Failure):

{
  "success": false,
  "message": "Username already exists"
}

4. Update User Data - PUT /auth/update

Allows an authenticated user to securely update their data.

Request:

Include token authentication via Authorization: Bearer <your-token>.

{
  "updates": [
    {
      "field": "username",
      "value": "newusername"
    },
    {
      "field": "profile.bio",
      "value": "Updated bio"
    }
  ]
}

Response (Success):

{
  "success": true,
  "message": "User data updated successfully"
}

Response (Failure):

{
  "success": false,
  "message": "Invalid token or update failed"
}

5. Delete User Account - DELETE /auth/delete

Allows authenticated users to delete their account securely.

Request:

Include token authentication via Authorization: Bearer <your-token>.

Response (Success):

{
  "success": true,
  "message": "Account successfully deleted"
}

Response (Failure):

{
  "success": false,
  "message": "Invalid token or deletion failed"
}

Configuration Options

The createAuthRouter() function accepts a configuration object with the following options:

OptionTypeDescription
prismaPrismaClientRequired. An instance of your PrismaClient.
jwtSecretstringRequired. Secret key for signing JWT tokens.
tokenExpirationstringExpiration time for tokens (default: '1h').
tableNamestringThe name of the Prisma table to use for authentication (default: 'adm_user').
usernameFieldstringThe username field name in your DB (default: 'username').
passwordFieldstringThe password field name in your DB (default: 'password').
userIdFieldstringThe user ID field name (default: 'id').
prismaMethodstringThe Prisma method used (findFirst, findUnique).
includestringA comma-separated list of Prisma fields to include.

Error Handling

egzix-auth uses appropriate HTTP status codes and responses:

  • 400 - Missing or invalid request payload.
  • 401 - Authentication error (invalid credentials or expired token).
  • 500 - Internal server error.

Security Recommendations

  1. 🔑 Use environment variables to store sensitive information like jwtSecret.
  2. 🔒 Ensure password hashing (js-sha256) is always applied before database comparison.
  3. 🚀 Use HTTPS to encrypt all sensitive requests.

Contributing

If you encounter a bug, have feature suggestions, or want to contribute, feel free to open an issue or submit a pull request!


✉️ Contact

If you face any issues, want explanations, or need help, connect with me on Instagram: @its_egzix.


I’ve added Update and Delete routes to give users the ability to manage their account. These routes follow standard security measures by ensuring proper token-based validation (JWT) and secure communication practices. Let me know if you'd like additional features or changes! 🚀

1.2.0

7 months ago

1.2.3

7 months ago

1.2.2

7 months ago

1.2.1

7 months ago

1.0.6

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago