npm package: @jopijs/jopimod_user_auth
Description: This module provides a complete user authentication system for JopiJS applications. It includes server-side infrastructure for handling JWT authentication, managing user stores, and ready-to-use UI pages for login and registration.
Latest version: 1.0.2

# @jopijs/jopimod_user_auth

This module provides a complete user authentication system for JopiJS applications. It includes server-side infrastructure for handling JWT authentication, managing user stores, and ready-to-use UI pages for login and registration.

## Role of the Module

The `@jopijs/jopimod_user_auth` module serves as the foundation for user management:

-   **Authentication Core**: Implements JWT (Json Web Token) based authentication using JopiJS security primitives.
-   **User Store Management**: Provides an extensible `AuthController` to manage user data (find, verify password, create).
-   **Ready-to-use UI**: Includes standard "Login" and "Register" pages with built-in forms and validation.
    *Note: These components are intentionally left **unstyled and minimalist** to make their structure clear. You are expected to apply your own design by overriding the form components.*
-   **Server Initialization**: Automatically configures the server security middleware via `serverInit.ts`.

## Structure

-   `@routes/login`: The public route for the login page.
-   `@routes/register`: The public route for user registration.
-   `@alias/lib`: Core logic and types (`AuthController`, `UserEntry`).
-   `@alias/ui`: Reusable UI components for auth forms.

## Usage

This module is plug-and-play. Once installed, it automatically registers the authentication middleware.

To customize user handling (e.g., to use a real database instead of the default in-memory list), you should override the `AuthController`.

### Default Configuration

By default, the module uses:
-   A `user.gen.json` file for storing users (in-memory, persisted to file).
-   A `defaultLoginPassword.json` for initial setup.
-   A randomly generated JWT secret key (if `JWT_SECRET_KEY` env var is not set).

## API Reference

### Library & Control

*   `getAuthController()`: Returns the singleton instance of `AuthController`. Use this to interact with user data programmatically.
*   `AuthController`: The class responsible for user logic.
    -   `findUser(loginInfo)`: Search for a user by login.
    -   `checkAuthData(fromBDD, fromBrowser)`: Verify password matches.
    -   `addUser(info)`: Create a new user.

### Types

*   `IUserEntry`: Represents a full user object with authentication and profile data.
*   `IAuthData`: Basic login/password structure.

## Override Organization

To successfully override default behaviors, your project structure must mirror the alias structure of this module.

### File Structure

Assuming you are working in your own module (e.g., `mod_myApp`), you should create the files as follows:

```text
src/
└── mod_myApp/              <-- Your custom module
    ├── package.json        <-- IMPORTANT: Must define devdependency
    └── @alias/
        ├── lib/
        │   └── jopijs.auth.AuthController/
        │       ├── high.priority  <-- OPTIONAL: Ensures this override wins
        │       └── index.ts       <-- Your custom logic
        └── ui/
            └── jopijs.auth.loginForm/
                └── index.tsx      <-- Your custom UI
                └── high.priority
```

### Module Priority (package.json)

For your overrides to take precedence over the default implementation, your module must declare a **devdependency** on the original module. This tells the JopiJS linker that your module "sits on top" of the `user_auth` module.

**File:** `src/mod_myApp/package.json`

```json
{
    "name": "my-app-module",
    "version": "1.0.0",
    "devdependencies": {
        "@jopijs/jopimod_user_auth": "latest" 
    }
}
```

*By adding this dependency, JopiJS understands that `mod_myApp` depends on `jopimod_user_auth`, and therefore any alias defined in `mod_myApp` will override the one in `jopimod_user_auth`.*


### 1. Customizing Authentication Logic (Database Integration)

To connect the authentication system to your own database (MySQL, PostgreSQL, etc.), you must override the default `AuthController`.

**Do not edit the original file.** Instead, create a new file in your own module using the exact same alias path. The JopiJS build system will automatically use your version instead of the default one.

**File Location:**  
`src/[your_module]/@alias/lib/jopijs.auth.AuthController/index.ts`

**Implementation:**
You must extend `CoreAuthController` and implement the required abstract methods.

```typescript
import CoreAuthController from "@/lib/jopijs.auth.CoreAuthController";
import IUserInfos from "@/lib/jopijs.auth.IUserInfos";
import UserEntry from "@/lib/jopijs.auth.IUserEntry";
import IAuthData from "@/lib/jopijs.auth.IAuthData";

export default class AuthController extends CoreAuthController {
    
    // Abstract method: Search for a user in your DB
    async findUser(loginInfo: IAuthData): Promise<UserEntry | undefined> {
        // e.g., return db.users.findOne({ login: loginInfo.login });
    }

    // Abstract method: Verify password (hash comparison)
    async checkAuthData(fromBDD: IAuthData, fromBrowser: IAuthData): Promise<boolean> {
        // e.g., return bcrypt.compare(fromBrowser.password, fromBDD.password);
    }

    // Abstract method: Add a new user to your DB
    async addUser(newUserInfos: Omit<IUserInfos, "id">): Promise<UserEntry | undefined> {
        // ...
    }
}
```

### 2. Customizing the UI (Login/Register Forms)

If you want to change the design of the login or registration forms, you should not override the entire Page/Route. Instead, override the specific UI component via the alias system.

**File Location:**  
`src/[your_module]/@alias/ui/jopijs.auth.loginForm/index.tsx`

**Implementation:**

```tsx
import React from "react";
// You can import the original types/interfaces if needed

export default function LoginForm() {
    return (
        <div className="my-custom-login-form">
            <h1>Welcome to My Awesome App</h1>
            <form action="/api/login" method="POST">
                {/* Your custom inputs and styling */}
            </form>
        </div>
    );
}
```

## Documentation

For comprehensive documentation on authentication flows and security, visit:

[https://jopijs.com](https://jopijs.com)