pawa-user
v1.0.1
Published
A user management service for Cosmo Pawa, handling authentication and authorization.
Maintainers
Readme
pawa-user: Reusable Node.js Express.js User Management Module
pawa-user is a comprehensive and reusable Node.js module designed for robust user management within Express.js applications. It provides full CRUD (Create, Read, Update, Delete) functionality for user accounts, along with a complete authentication system including registration, login, and JWT-based authorization. The module leverages Sequelize as its ORM, supporting various SQL databases, and includes a dedicated user activity logging model.
Features
- User CRUD: Full set of operations to manage user records.
- Authentication: Secure user registration, login, and JWT generation for API authentication.
- Comprehensive User Model: Includes a wide range of standard user fields (e.g.,
firstName,lastName,email,phoneNumber,address,role,profilePicture,lastLogin). - User Activity Logging: A dedicated
UserActivitymodel to log user actions like login/logout, with details and timestamps, enabling tracking for the last 30 days. - Sequelize ORM: Database abstraction for easy integration with PostgreSQL, MySQL, SQLite, and MSSQL.
- Dynamic Configuration: Database parameters and JWT secret are passed dynamically during module initialization, making it highly reusable without modifying internal files.
Installation
Clone or Download: Obtain the
pawa-usermodule files.Navigate to Project Directory: Open your terminal and go to the
pawa-userdirectory.Install Dependencies: Run the following command to install all necessary packages:
npm install
Usage
To use pawa-user in your Express.js application, you first need to initialize it with your database configuration and JWT secret. Then you can use its exported functions:
const pawaUser = require("pawa-user");
// 1. Define your database configuration and JWT secret
const dbConfig = {
DB_NAME: process.env.DB_NAME || "your_database_name",
DB_USER: process.env.DB_USER || "your_database_user",
DB_PASSWORD: process.env.DB_PASSWORD || "your_database_password",
DB_HOST: process.env.DB_HOST || "localhost",
DB_DIALECT: process.env.DB_DIALECT || "postgres", // e.g., "postgres", "mysql", "sqlite", "mssql"
};
const jwtSecret = process.env.JWT_SECRET || "your_super_secret_jwt_key";
// 2. Initialize the pawa-user module
pawaUser.initialize({ dbConfig, jwtSecret });
// 3. Connect to the database (this will also synchronize models)
pawaUser.connectDB();
// Example: Register a new user
async function registerNewUser() {
try {
const user = await pawaUser.registerUser({
firstName: "Test",
lastName: "User",
email: "[email protected]",
password: "securepassword123",
});
console.log("User registered:", user.toJSON());
} catch (error) {
console.error("Registration failed:", error.message);
}
}
// registerNewUser();
// Example: Login a user
async function loginExistingUser() {
try {
const { user, token } = await pawaUser.loginUser("[email protected]", "securepassword123");
console.log("User logged in:", user.toJSON());
console.log("JWT Token:", token);
} catch (error) {
console.error("Login failed:", error.message);
}
}
// loginExistingUser();
// Example: Get all users
async function retrieveAllUsers() {
try {
const users = await pawaUser.getAllUsers();
console.log("All users:", users.map(u => u.toJSON()));
} catch (error) {
console.error("Failed to retrieve users:", error.message);
}
}
// retrieveAllUsers();
// Example: Get user activity
async function getUserActivities(userId) {
try {
const activities = await pawaUser.getUserActivity(userId);
console.log("User activities:", activities.map(a => a.toJSON()));
} catch (error) {
console.error("Failed to retrieve activities:", error.message);
}
}
// getUserActivities("some-user-id");API Reference
Initialization and Database
pawaUser.initialize({ dbConfig, jwtSecret }): Initializes the module with database configuration and JWT secret. Must be called once before using other functions.dbConfig: An object containingDB_NAME,DB_USER,DB_PASSWORD,DB_HOST,DB_DIALECT.jwtSecret: The secret key for JWT signing.
pawaUser.connectDB(): Asynchronously connects to the database and synchronizes models. Call this afterinitialize().pawaUser.sequelize: The Sequelize instance (available afterinitialize).pawaUser.User: The Sequelize User model (available afterinitialize).pawaUser.UserActivity: The Sequelize UserActivity model (available afterinitialize).
User CRUD Operations
pawaUser.createUser(userData): Creates a new user.userDatashould be an object containing user fields (e.g.,firstName,lastName,email,password).pawaUser.getAllUsers(): Retrieves all users, excluding passwords.pawaUser.getUserById(id): Retrieves a single user by their ID, excluding password.pawaUser.updateUser(id, userData): Updates a user by ID.userDatacontains fields to update.pawaUser.deleteUser(id): Deletes a user by ID.pawaUser.getUserActivity(userId): Retrieves user activity logs for a given user ID for the last 30 days.
Authentication Operations
pawaUser.registerUser(userData): Registers a new user.userDatais the same as forcreateUser.pawaUser.loginUser(email, password): Authenticates a user with email and password, returning the user object and a JWT token.pawaUser.logoutUser(userId): Logs a user logout activity (does not invalidate JWT).
Testing
A test.js file is included for basic testing of the module's functionalities. To run the tests:
Ensure your database is configured and running. The
test.jsfile uses environment variables from a.envfile for database configuration and JWT secret, or falls back to default values.Run the test file:
node test.js
Project Structure
pawa-user/
├── config/
│ └── database.js
├── controllers/
│ ├── authController.js
│ └── userController.js
├── models/
│ ├── user.js
│ └── userActivity.js
├── .env
├── index.js
├── package.json
├── package-lock.json
└── README.md
└── test.jsDependencies
expresssequelizepg(or other database driver likemysql2,sqlite3)dotenvbcryptjsjsonwebtoken
License
ISC
