# Forget Password API Documentation

## Overview

The Forget Password API allows users to reset their password using OTP (One-Time Password) verification. The process involves two steps:
1. Request a password reset OTP (sent via SMS)
2. Verify the OTP and set a new password

---

## Base URL

```
https://api.alldigtalseva.com/api
```

---

## API Endpoints

### 1. Request Password Reset OTP

Send a password reset OTP to the user's registered phone number.

**Endpoint:** `POST /user/forget-password`

**Authentication:** Not required

**Request Body:**
```json
{
    "email": "user@example.com"
}
```

**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| email | string | Yes | User's registered email address |

**Response (Success - 200):**
```json
{
    "success": true,
    "message": "OTP sent successfully to your registered phone number for password reset",
    "data": {
        "email": "user@example.com"
    }
}
```

**Response (SMS Failed - 200):**
```json
{
    "success": true,
    "message": "OTP generated but SMS sending failed. Please try again.",
    "data": {
        "email": "user@example.com"
    }
}
```

**Response (User Not Verified - 403):**
```json
{
    "success": false,
    "message": "User account is not verified. Please complete signup first."
}
```

**Response (Validation Error - 422):**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "email": [
            "The email field is required.",
            "The email must be a valid email address."
        ]
    }
}
```

**Notes:**
- For security reasons, the API returns a success message even if the email doesn't exist in the system
- The OTP is sent to the user's registered phone number via SMS
- OTP is valid for 10 minutes
- Only verified users can reset their password

---

### 2. Reset Password

Verify the OTP and set a new password.

**Endpoint:** `POST /user/reset-password`

**Authentication:** Not required

**Request Body:**
```json
{
    "email": "user@example.com",
    "otp": "123456",
    "password": "newpassword123"
}
```

**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| email | string | Yes | User's registered email address |
| otp | string | Yes | 6-digit OTP received via SMS |
| password | string | Yes | New password (minimum 6 characters) |

**Response (Success - 200):**
```json
{
    "success": true,
    "message": "Password reset successfully. You can now login with your new password.",
    "data": {
        "id": 1,
        "email": "user@example.com"
    }
}
```

**Response (User Not Found - 404):**
```json
{
    "success": false,
    "message": "User not found"
}
```

**Response (Invalid OTP - 401):**
```json
{
    "success": false,
    "message": "Invalid OTP"
}
```

**Response (OTP Expired - 401):**
```json
{
    "success": false,
    "message": "OTP has expired. Please request a new one."
}
```

**Response (User Not Verified - 403):**
```json
{
    "success": false,
    "message": "User account is not verified. Please complete signup first."
}
```

**Response (Validation Error - 422):**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "email": [
            "The email field is required."
        ],
        "otp": [
            "The otp must be 6 characters.",
            "The otp field is required."
        ],
        "password": [
            "The password must be at least 6 characters.",
            "The password field is required."
        ]
    }
}
```

**Notes:**
- The OTP must match the one sent to the user's phone
- OTP expires after 10 minutes
- Password is stored in plain text (consistent with existing system)
- After successful password reset, user can login with the new password

---

## cURL Examples

### Request Password Reset OTP

```bash
curl -X POST https://api.alldigtalseva.com/api/user/forget-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'
```

### Reset Password

```bash
curl -X POST https://api.alldigtalseva.com/api/user/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "otp": "123456",
    "password": "newpassword123"
  }'
```

---

## JavaScript/Angular Examples

### Request Password Reset OTP

```typescript
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

const apiUrl = 'https://api.alldigtalseva.com/api';

requestPasswordReset(email: string): Observable<any> {
  return this.http.post(`${apiUrl}/user/forget-password`, {
    email: email
  });
}

// Usage
this.authService.requestPasswordReset('user@example.com').subscribe(
  (response) => {
    if (response.success) {
      console.log('OTP sent successfully');
      // Show message to user
    }
  },
  (error) => {
    console.error('Error:', error);
  }
);
```

### Reset Password

```typescript
resetPassword(email: string, otp: string, newPassword: string): Observable<any> {
  return this.http.post(`${apiUrl}/user/reset-password`, {
    email: email,
    otp: otp,
    password: newPassword
  });
}

// Usage
this.authService.resetPassword('user@example.com', '123456', 'newpassword123').subscribe(
  (response) => {
    if (response.success) {
      console.log('Password reset successfully');
      // Redirect to login page
    }
  },
  (error) => {
    if (error.error.message === 'Invalid OTP') {
      console.error('Invalid OTP entered');
    } else if (error.error.message === 'OTP has expired') {
      console.error('OTP expired, please request a new one');
    } else {
      console.error('Error:', error);
    }
  }
);
```

---

## React/Next.js Examples

### Request Password Reset OTP

```javascript
const requestPasswordReset = async (email) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/user/forget-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email
      }),
    });

    const data = await response.json();
    
    if (data.success) {
      console.log('OTP sent successfully');
      return { success: true, message: data.message };
    } else {
      return { success: false, message: data.message };
    }
  } catch (error) {
    console.error('Error:', error);
    return { success: false, message: 'An error occurred' };
  }
};
```

### Reset Password

```javascript
const resetPassword = async (email, otp, newPassword) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/user/reset-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email,
        otp: otp,
        password: newPassword
      }),
    });

    const data = await response.json();
    
    if (data.success) {
      console.log('Password reset successfully');
      return { success: true, message: data.message };
    } else {
      return { success: false, message: data.message };
    }
  } catch (error) {
    console.error('Error:', error);
    return { success: false, message: 'An error occurred' };
  }
};
```

---

## Complete Flow Example

### Step 1: User Requests Password Reset

```javascript
// User enters email and clicks "Forgot Password"
const email = 'user@example.com';

const response = await requestPasswordReset(email);
if (response.success) {
  // Show message: "OTP sent to your registered phone number"
  // Show OTP input field
}
```

### Step 2: User Enters OTP and New Password

```javascript
// User enters OTP received via SMS and new password
const otp = '123456';
const newPassword = 'newpassword123';

const response = await resetPassword(email, otp, newPassword);
if (response.success) {
  // Show success message
  // Redirect to login page
} else {
  // Show error message (Invalid OTP, Expired OTP, etc.)
}
```

---

## Error Handling

### Common Error Scenarios

1. **Invalid Email Format**
   - Status: 422
   - Message: "Validation error"
   - Solution: Ensure email is in valid format

2. **User Not Found**
   - Status: 404 (only for reset password)
   - Message: "User not found"
   - Solution: Verify email address

3. **Invalid OTP**
   - Status: 401
   - Message: "Invalid OTP"
   - Solution: Check OTP entered correctly

4. **Expired OTP**
   - Status: 401
   - Message: "OTP has expired. Please request a new one."
   - Solution: Request a new OTP

5. **User Not Verified**
   - Status: 403
   - Message: "User account is not verified. Please complete signup first."
   - Solution: Complete signup process first

6. **Weak Password**
   - Status: 422
   - Message: "Validation error"
   - Solution: Password must be at least 6 characters

---

## Security Considerations

1. **OTP Expiration**: OTPs expire after 10 minutes for security
2. **Email Privacy**: The API doesn't reveal if an email exists in the system (for forget password request)
3. **SMS Delivery**: OTP is sent via SMS to the registered phone number
4. **Plain Text Passwords**: Passwords are stored in plain text (consistent with existing system architecture)
5. **Rate Limiting**: Consider implementing rate limiting to prevent abuse

---

## Testing

### Test Case 1: Successful Password Reset Flow

1. Request OTP with valid email
2. Check SMS for OTP
3. Reset password with correct OTP and new password
4. Verify login works with new password

### Test Case 2: Invalid OTP

1. Request OTP
2. Enter incorrect OTP
3. Verify error message: "Invalid OTP"

### Test Case 3: Expired OTP

1. Request OTP
2. Wait more than 10 minutes
3. Try to reset password
4. Verify error message: "OTP has expired"

### Test Case 4: Unverified User

1. Try to reset password for unverified user
2. Verify error message: "User account is not verified"

---

## Integration Checklist

- [ ] Implement "Forgot Password" button/link on login page
- [ ] Create form to enter email for password reset request
- [ ] Display OTP input field after successful OTP request
- [ ] Create form to enter OTP and new password
- [ ] Handle success and error responses appropriately
- [ ] Redirect to login page after successful password reset
- [ ] Add loading states during API calls
- [ ] Implement proper error messages for users
- [ ] Test with valid and invalid scenarios

---

## Support

For issues or questions regarding the Forget Password API, please contact the development team.

---

**Last Updated:** December 2025

