Send reset password email

Header

  • Composable Action: composables/useDjustAuth/useAuthApi.ts
  • API Route: POST /api/auth/send-reset-password-email

Detailed Description

The sendResetPasswordEmail action is a secure password recovery function that initiates the password reset process by sending a reset link to the user's registered email address. It provides a safe and user-friendly method for users to regain access to their accounts when they forget their passwords.

This action implements security best practices including email validation, rate limiting protection, and secure token generation. The function handles the complete email sending process while providing clear feedback about the operation's success or failure.

The function is commonly used in forgot password flows, user account recovery scenarios, and administrative password reset procedures. It integrates seamlessly with the overall authentication system while maintaining strict security standards.

Process Flow

sequenceDiagram
    participant U as User
    participant C as Vue Component
    participant UA as useDjustAuth
    participant API as Auth API
    participant Email as Email Service
    participant Auth as Auth Service

    U->>C: Enter email address
    C->>UA: sendResetPasswordEmail(email)
    UA->>API: POST /auth/send-reset-password-email
    API->>Auth: Validate email & generate token
    Auth->>Email: Send reset email
    Email-->>Auth: Email sent
    Auth-->>API: Success response
    API-->>UA: Response
    UA-->>C: Operation result
    C-->>U: Confirmation message

    alt Invalid Email
        API-->>UA: 400 Bad Request
        UA-->>C: Validation error
        C-->>U: "Please enter valid email"
    else Email Not Found
        API-->>UA: 404 Not Found
        UA-->>C: Email not found
        C-->>U: "No account found"
    else Rate Limit Exceeded
        API-->>UA: 429 Too Many Requests
        UA-->>C: Rate limit error
        C-->>U: "Too many requests"
    end

Call Parameters

Main Interface

const sendResetPasswordEmail = async (email: string): Promise<SendResetPasswordEmailResponse>

Detailed Parameters

ParameterTypeRequiredDefaultExampleImpact
emailstring-"[email protected]"Email address to send reset link

Example Call

const { sendResetPasswordEmail } = useDjustAuth();

try {
  const result = await sendResetPasswordEmail("[email protected]");

  if (result.success) {
    console.log("Reset email sent successfully");
    // Show success message to user
  } else {
    console.error("Failed to send reset email:", result.message);
    // Show error message to user
  }
} catch (error) {
  console.error("Reset email error:", error);
}

Returns from Composable

Success Response Format

interface SendResetPasswordEmailResponse {
  success: boolean;
  message: string;
}

Example Success Response

{
  "success": true,
  "message": "Password reset instructions have been sent to your email address. Please check your inbox and follow the instructions to reset your password."
}

Example Error Response

{
  "success": false,
  "message": "No account found with the provided email address."
}

Error Management

Error Types and Returns

HTTP CodeError TypeCauseSystem ActionUser Message
400Bad RequestInvalid email formatReturn error response"Please enter a valid email address"
404Not FoundEmail address not registeredReturn error response"No account found with this email"
429Too Many RequestsRate limiting triggeredReturn error response"Too many requests. Please wait"
500Internal Server ErrorEmail service or server issuesReturn error response"Unable to send email. Try again"

Error Handling Code Example

const { sendResetPasswordEmail } = useDjustAuth();
const { $toast } = useNuxtApp();

const handlePasswordReset = async (email: string) => {
  try {
    const result = await sendResetPasswordEmail(email);

    if (result.success) {
      $toast.success("Password reset instructions sent to your email");

      // Optionally redirect to login with message
      await navigateTo({
        path: "/auth/login",
        query: { message: "check-email" },
      });
    } else {
      // Handle specific error messages
      if (result.message.includes("No account found")) {
        $toast.error("No account found with this email address");
      } else if (result.message.includes("Too many")) {
        $toast.error(
          "Too many reset requests. Please wait before trying again"
        );
      } else {
        $toast.error(result.message || "Failed to send reset email");
      }
    }
  } catch (error) {
    console.error("Password reset error:", error);
    $toast.error("Unable to send reset email. Please try again later");
  }
};

Use Cases

  1. Forgot Password Flow

    • User clicks "Forgot Password" link on login page
    • System prompts for email address
    • User receives reset link via email
    • User follows link to reset password
  2. Account Recovery

    • User loses access to account due to forgotten credentials
    • Admin initiates password reset on user's behalf
    • User receives recovery instructions via email
    • Account access is restored after password reset
  3. Security Incident Response

    • Suspicious account activity detected
    • Proactive password reset triggered for security
    • User notified via email about security measure
    • User required to set new password
  4. Bulk Password Reset

    • Administrative bulk password reset operations
    • System-wide security updates requiring password changes
    • Automated password reset triggers
    • Mass notification to affected users

Important Points

Performance

The function is optimized for reliable email delivery with efficient API calls, proper timeout handling, and graceful error recovery. It includes built-in retry mechanisms for transient failures and optimized email templating for faster processing.

Security

Security is paramount with comprehensive email validation, secure token generation with limited lifetime, rate limiting to prevent abuse, and protection against email enumeration attacks. The system never exposes whether an email exists in the database to unauthorized users.

Flexibility

The system provides flexible configuration options with customizable email templates, configurable rate limiting parameters, support for multiple email providers, and extensible error handling for different scenarios.

Integration

Seamless integration includes coordination with email service providers, integration with user notification preferences, consistent error handling with other authentication functions, and proper logging for security monitoring.

Technical Implementation

/**
 * Sends a password reset email to the specified email address
 * @param email - Email address to send reset instructions to
 * @returns Promise<SendResetPasswordEmailResponse> - Operation result
 * @throws {Error} - Network or server errors (handled gracefully)
 */
const sendResetPasswordEmail = async (
  email: string
): Promise<SendResetPasswordEmailResponse> => {
  try {
    // Make API call to send reset email
    const { data, error } = await useFetch<SendResetPasswordEmailResponse>(
      "/api/auth/send-reset-password-email",
      {
        method: "POST",
        body: { email },
      }
    );

    // Handle API errors
    if (error.value) {
      throw new Error(error.value.message);
    }

    // Return successful response or default error
    return data.value
      ? data.value
      : { success: false, message: "Failed to send reset password email." };
  } catch (err) {
    // Handle and format errors gracefully
    return {
      success: false,
      message: err instanceof Error ? err.message : "An error occurred",
    };
  }
};

Execution Flow

  1. Email Validation

    // Client-side validation
    if (!email || !isValidEmail(email)) {
      throw new Error("Please enter a valid email address");
    }
  2. API Request

    const { data, error } = await useFetch(
      "/api/auth/send-reset-password-email",
      {
        method: "POST",
        body: { email },
      }
    );
  3. Error Handling

    if (error.value) {
      throw new Error(error.value.message);
    }
  4. Response Processing

    return (
      data.value || {
        success: false,
        message: "Failed to send reset password email.",
      }
    );
  5. Graceful Error Recovery

    catch (err) {
      return {
        success: false,
        message: err instanceof Error ? err.message : 'An error occurred'
      };
    }

Security Considerations

Rate Limiting

  • Maximum 3 reset requests per email per hour
  • Progressive backoff for repeated requests
  • IP-based rate limiting for additional protection

Token Security

  • Cryptographically secure random tokens
  • Limited lifetime (15-30 minutes)
  • Single-use tokens that expire after use

Email Privacy

  • No confirmation of email existence for non-users
  • Consistent response times regardless of email validity
  • Secure email content with no sensitive information exposure