# Password Requirements

## Password Validation Rules
The system enforces the following password requirements:

1. Minimum length: 8 characters
2. Maximum length: 50 characters
3. Must contain at least:
   - One uppercase letter (A-Z)
   - One number (0-9)
   - One special character (#?!@$%^&*-)

## Example Valid Passwords
- `Password123!`
- `SecurePass#2024`
- `MyP@ssw0rd`

## Example Invalid Passwords
- `password` (no uppercase, no number, no special char)
- `Password` (no number, no special char)
- `pass123` (no uppercase, no special char)
- `Pass123` (no special char)

## Change Password Requirements
When changing your password:
1. You must provide your current password (oldPassword)
2. The new password must meet all the above requirements
3. The new password must be different from the old password
4. The system will validate:
   - Current password must be correct
   - New password must meet complexity requirements
   - New password cannot be the same as the old password
   - Password change must be successful

## Forgot Password Requirements
When requesting a password reset:
1. You must provide your registered email address
2. The system will validate:
   - Email must be in valid format
   - Email must be registered in the system
   - Rate limiting to prevent abuse
3. After successful request:
   - A reset link will be sent to your email
   - Link contains a secure token
   - Link is valid for limited time
   - Link can only be used once
4. Security measures:
   - Rate limiting on requests
   - Secure token generation
   - One-time use links
   - Email verification required

## Error Messages
The system will display the following messages during password operations:

### Change Password Messages
- "Incorrect old password" - When the current password is wrong
- "New password must be different from the old password" - When trying to reuse the same password
- "Unable to update password" - When there's a system error during the update
- "Password changed successfully" - When the password is updated successfully

### Forgot Password Messages
- "Link to reset your password has been sent to the registered mail" - When request is successful
- "Email link is expired please try again" - When reset link has expired
- "Link already used or invalid" - When reset link has already been used
- "Invalid email format" - When email format is incorrect
- "Email not found" - When email is not registered in the system

## Email Templates
The system uses email templates for various automated communications. Each template has the following structure:

### Database Schema
```sql
CREATE TABLE EmailTemplates (
    id INT PRIMARY KEY AUTO_INCREMENT,
    key VARCHAR(255) NOT NULL UNIQUE,
    title VARCHAR(255),
    fromEmail VARCHAR(255),
    fromName VARCHAR(255),
    subject VARCHAR(255),
    body LONGTEXT,
    isManualMail BOOLEAN NOT NULL DEFAULT false,
    isContactUsMail BOOLEAN NOT NULL DEFAULT false,
    status VARCHAR(255) NOT NULL DEFAULT 'Active',
    createdAt TIMESTAMP NOT NULL,
    updatedAt TIMESTAMP NOT NULL,
    deletedAt TIMESTAMP NULL
);
```

### Field Descriptions
1. Primary Fields:
   - `id`: Auto-incrementing primary key
   - `key`: Unique identifier for the template (required)
   - `title`: Template title
   - `fromEmail`: Sender email address
   - `fromName`: Sender name
   - `subject`: Email subject line
   - `body`: Email content in LONGTEXT format

2. Control Flags:
   - `isManualMail`: Boolean flag for manually triggered emails (default: false)
   - `isContactUsMail`: Boolean flag for contact form submissions (default: false)
   - `status`: Template status (default: 'Active')

3. Timestamps:
   - `createdAt`: Record creation timestamp
   - `updatedAt`: Record update timestamp
   - `deletedAt`: Soft delete timestamp

### Constraints
- `key` field must be unique
- `status` defaults to 'Active'
- `isManualMail` and `isContactUsMail` default to false
- All timestamps are automatically managed

### Service Requirements
The email template service provides the following functionality:

1. Template Retrieval:
   - Get template by key
   - Returns all template fields:
     ```typescript
     {
       id: number,
       key: string,
       title: string,
       fromEmail: string,
       fromName: string,
       subject: string,
       body: string,
       isManualMail: boolean,
       isContactUsMail: boolean,
       status: string,
       createdAt: Date,
       updatedAt: Date,
       deletedAt: Date | null
     }
     ```

2. Service Methods:
   - `getEmailTemplateByKey(key: string)`: Retrieves a template by its unique key
   - Returns null if template not found
   - Returns full template object if found

3. Usage Example:
   ```typescript
   const template = await getEmailTemplateByKey('password-reset');
   if (template) {
     // Use template fields
     const { subject, body, fromEmail, fromName } = template;
   }
   ```

## Database Schema Requirements

### Email Templates Table
```sql
CREATE TABLE EmailTemplates (
    Id INT PRIMARY KEY AUTO_INCREMENT,
    Key VARCHAR(255) NOT NULL UNIQUE,
    Title VARCHAR(255),
    FromEmail VARCHAR(255),
    FromName VARCHAR(255),
    Subject VARCHAR(255),
    Body LONGTEXT,
    isManualMail BOOLEAN NOT NULL DEFAULT false,
    isContactUsMail BOOLEAN NOT NULL DEFAULT false,
    Status VARCHAR(255) NOT NULL DEFAULT 'Active',
    CreatedAt TIMESTAMP NOT NULL,
    UpdatedAt TIMESTAMP NOT NULL,
    DeletedAt TIMESTAMP NULL,
    createdBy INT NULL,
    updatedBy INT NULL,
    deletedBy INT NULL
);
```

### Field Descriptions
1. Primary Fields:
   - `Id`: Auto-incrementing primary key
   - `Key`: Unique identifier for the template (required)
   - `Title`: Template title
   - `FromEmail`: Sender email address
   - `FromName`: Sender name
   - `Subject`: Email subject line
   - `Body`: Email content in LONGTEXT format

2. Control Flags:
   - `isManualMail`: Boolean flag for manually triggered emails
   - `isContactUsMail`: Boolean flag for contact form submissions
   - `Status`: Template status (default: 'Active')

3. Timestamps:
   - `CreatedAt`: Record creation timestamp
   - `UpdatedAt`: Record update timestamp
   - `DeletedAt`: Soft delete timestamp

4. Audit Fields:
   - `createdBy`: User ID who created the template
   - `updatedBy`: User ID who last updated the template
   - `deletedBy`: User ID who deleted the template

### Constraints
- `Key` field must be unique
- `Status` defaults to 'Active'
- `isManualMail` and `isContactUsMail` default to false
- All timestamps are automatically managed
- Audit fields are nullable for tracking purposes

## Email Service
The system provides a robust email service for sending automated communications.

### Configuration
```typescript
// Environment Variables Required
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-specific-password
SMTP_FROM=noreply@adminpanel.com  // Optional, defaults to noreply@adminpanel.com
```

### Features
1. Singleton Pattern:
   - Single instance of email service
   - Reusable transporter
   - Connection verification before sending

2. Error Handling:
   - Configuration validation
   - Connection verification
   - Detailed error logging
   - User-friendly error messages

3. Security:
   - TLS encryption
   - Secure authentication
   - Environment variable configuration
   - No hardcoded credentials

### Usage Example
```typescript
import { sendMail } from '../services/email.service';

// Basic usage
await sendMail({
  to: 'user@example.com',
  subject: 'Welcome',
  html: '<h1>Welcome to our platform</h1>'
});

// With custom from address
await sendMail({
  from: 'custom@example.com',
  to: 'user@example.com',
  subject: 'Custom From',
  html: '<p>Email content</p>'
});
```

### Error Handling
The service handles various error scenarios:
1. Missing Configuration:
   - Throws error if SMTP credentials are missing
   - Validates configuration on service initialization

2. Connection Issues:
   - Verifies SMTP connection before sending
   - Handles connection timeouts
   - Manages authentication failures

3. Sending Failures:
   - Logs detailed error information
   - Provides user-friendly error messages
   - Maintains error history for debugging

## Authentication

### Forgot Password Flow
The forgot password functionality provides a secure way for users to reset their passwords. Here's the detailed flow:

#### 1. Request Password Reset
- **Endpoint**: `POST /auth/forgot-password`
- **Request Body**: 
  ```json
  {
    "email": "user@example.com"
  }
  ```
- **Validation**:
  - Email format validation
  - Email existence check in database
  - Rate limiting to prevent abuse

#### 2. Reset Link Generation
- System generates a secure encrypted token using `getEncryptedToken` with:
  - User ID encrypted in token
  - 12-minute expiry time
  - Purpose set as "forgot-password"
  - Additional security with nonce and hash verification

#### 3. Email Sending
- Uses email template system with:
  - Customizable subject and body
  - Dynamic reset link insertion
  - From name and email configuration
  - HTML formatting support
- Reset link format: `{client_url}/reset-password/{encrypted_token}`

#### 4. Password Reset
- **Endpoint**: `POST /auth/reset-password/:token`
- **Request Body**:
  ```json
  {
    "password": "NewSecurePassword123!"
  }
  ```
- **Validation**:
  - Password strength requirements
  - Token verification and expiry check
  - Token purpose validation
  - Token integrity verification

#### Security Features
1. **Token Security**:
   - AES-256-GCM encryption
   - 12-minute expiry time
   - Purpose-specific tokens
   - Integrity verification with hash
   - Nonce for replay prevention

2. **Password Requirements**:
   - Minimum 8 characters
   - Must contain uppercase letter
   - Must contain number
   - Must contain special character
   - Maximum 50 characters

3. **Rate Limiting**:
   - Prevents brute force attempts
   - Configurable limits per IP
   - Temporary blocking on excessive attempts

#### Response Messages
- `EMAIL_NOT_REGISTERED`: When email is not found
- `RESET_LINK_SENT`: When reset link is sent successfully
- `PASSWORD_RESET_SUCCESS`: When password is reset successfully
- `EMAIL_SEND_ERROR`: When email sending fails
- `INVALID_RESET_LINK`: When token is invalid/expired
- `RESET_LINK_USED`: When token is already used
- `TOKEN_EXPIRED`: When token has expired
- `TOKEN_INTEGRITY_FAILED`: When token is tampered with
- `INVALID_TOKEN_PURPOSE`: When token is used for wrong purpose

#### Error Handling
1. **Email Validation**:
   - Invalid email format
   - Non-existent email
   - Email sending failures

2. **Token Validation**:
   - Expired tokens
   - Invalid tokens
   - Tampered tokens
   - Wrong purpose tokens

3. **Password Validation**:
   - Weak passwords
   - Missing requirements
   - Length violations

#### Usage Example
```typescript
// Request password reset
const response = await axios.post('/auth/forgot-password', {
  email: 'user@example.com'
});

// Reset password with token
const resetResponse = await axios.post('/auth/reset-password/encrypted-token', {
  password: 'NewSecurePassword123!'
});
```

### Reset Password Flow
The reset password functionality allows users to set a new password using a secure token. Here's the detailed flow:

#### 1. Token Verification
- **Endpoint**: `POST /auth/reset-password/:token`
- **Token Validation**:
  - Verifies token authenticity
  - Checks token expiry (12 minutes)
  - Validates token purpose
  - Ensures token hasn't been used before

#### 2. Password Reset Process
- **Request Body**:
  ```json
  {
    "password": "NewSecurePassword123!"
  }
  ```
- **Validation Steps**:
  1. Token decryption and verification
  2. Password strength validation
  3. User existence verification
  4. Password update in database

#### 3. Security Measures
1. **Token Security**:
   - AES-256-GCM encryption
   - One-time use tokens
   - 12-minute expiry
   - Purpose-specific validation
   - Integrity verification

2. **Password Requirements**:
   - Minimum 8 characters
   - Maximum 50 characters
   - Must contain:
     - At least one uppercase letter
     - At least one number
     - At least one special character
   - Cannot be the same as previous password

3. **Database Updates**:
   - Password is hashed using bcrypt
   - Updates user record
   - Maintains audit trail
   - Invalidates old sessions

#### 4. Response Handling
- **Success Response**:
  ```json
  {
    "status": 201,
    "message": "Password reset successful"
  }
  ```
- **Error Responses**:
  - Invalid token
  - Expired token
  - Weak password
  - User not found
  - Database errors

#### 5. Error Scenarios
1. **Token Errors**:
   - `INVALID_RESET_LINK`: Invalid or malformed token
   - `TOKEN_EXPIRED`: Token has expired
   - `TOKEN_INTEGRITY_FAILED`: Token has been tampered with
   - `INVALID_TOKEN_PURPOSE`: Token used for wrong purpose

2. **Password Errors**:
   - Password too short/long
   - Missing required characters
   - Same as previous password
   - Invalid format

3. **System Errors**:
   - Database connection issues
   - User not found
   - Update failures

#### 6. Usage Example
```typescript
// Reset password with token
const resetResponse = await axios.post('/auth/reset-password/encrypted-token', {
  password: 'NewSecurePassword123!'
});

// Handle response
if (resetResponse.status === 201) {
  console.log('Password reset successful');
} else {
  console.error('Password reset failed:', resetResponse.data.message);
}
```

## User Service Requirements

### User Management Features
1. User Listing:
   - Pagination support
   - Sorting by any field
   - Filtering by:
     - First name
     - Last name
     - Email
     - Phone number
     - Status
     - Role name
     - Full name (concatenated first and last name)
   - Role information included in results
   - Soft delete support

2. User Creation:
   - Required fields:
     - First name
     - Last name
     - Email (unique)
     - Role ID
     - Status
   - Optional fields:
     - Phone number
     - Profile image
     - Password (auto-generated if not provided)
   - Soft delete handling:
     - Restore soft-deleted user if email exists
     - Update with new information
   - Welcome email sent with credentials

3. User Update:
   - All fields updatable except password
   - Email uniqueness check
   - Profile image handling
   - Role and status restrictions for self-update
   - Soft delete handling for duplicate emails

4. User Deletion:
   - Soft delete implementation
   - Audit trail (deletedBy)
   - Cascade handling for related records

5. Password Management:
   - Reset password functionality
   - Email notification
   - Password encryption
   - Password generation for new users

### Database Schema
```sql
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    firstName VARCHAR(255) NOT NULL,
    lastName VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    roleId INT NOT NULL,
    status VARCHAR(50) NOT NULL DEFAULT 'Active',
    phoneNumber VARCHAR(20),
    profileImage VARCHAR(255),
    createdBy INT,
    updatedBy INT,
    deletedBy INT,
    createdAt TIMESTAMP NOT NULL,
    updatedAt TIMESTAMP NOT NULL,
    deletedAt TIMESTAMP NULL,
    FOREIGN KEY (roleId) REFERENCES roles(id)
);
```

### Required Dependencies
```json
{
  "dependencies": {
    "bcrypt": "^5.1.0",
    "knex": "^2.4.2",
    "nodemailer": "^6.9.1"
  }
}
```

### Environment Variables
```env
# Database
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=your_database

# Email
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-specific-password
SMTP_FROM=noreply@adminpanel.com
``` 