# 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 `UserActivity` model 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

1.  **Clone or Download**: Obtain the `pawa-user` module files.
2.  **Navigate to Project Directory**: Open your terminal and go to the `pawa-user` directory.
3.  **Install Dependencies**: Run the following command to install all necessary packages:

    ```bash
    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:

```javascript
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: "test@example.com",
      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("test@example.com", "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 containing `DB_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 after `initialize()`.
-   `pawaUser.sequelize`: The Sequelize instance (available after `initialize`).
-   `pawaUser.User`: The Sequelize User model (available after `initialize`).
-   `pawaUser.UserActivity`: The Sequelize UserActivity model (available after `initialize`).

### User CRUD Operations

-   `pawaUser.createUser(userData)`: Creates a new user. `userData` should 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. `userData` contains 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. `userData` is the same as for `createUser`.
-   `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:

1.  Ensure your database is configured and running. The `test.js` file uses environment variables from a `.env` file for database configuration and JWT secret, or falls back to default values.
2.  Run the test file:

    ```bash
    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.js
```

## Dependencies

-   `express`
-   `sequelize`
-   `pg` (or other database driver like `mysql2`, `sqlite3`)
-   `dotenv`
-   `bcryptjs`
-   `jsonwebtoken`

## License

ISC

