WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Variable PasswordUpdateSchemaConst

    PasswordUpdateSchema: ZodEffects<
        ZodObject<
            { current_password: ZodString; new_password: ZodString },
            "strip",
            ZodTypeAny,
            { current_password: string; new_password: string },
            { current_password: string; new_password: string },
        >,
        { current_password: string; new_password: string },
        { current_password: string; new_password: string },
    > = ...

    Password update validation schema with security refinements

    Comprehensive validation schema for password change operations that ensures both current password verification and new password security compliance. The schema validates that users provide their current password for authentication and that the new password meets all security requirements while being different from the current password to prevent password reuse.

    The password update process is a critical security operation that requires careful validation to prevent unauthorized password changes and ensure new passwords meet current security standards. The schema implements a two-step validation process: first validating individual field requirements, then applying cross-field validation to ensure password uniqueness and security policy compliance.

    Security features include current password requirement to prevent unauthorized changes, new password complexity validation through PasswordSchema integration, password uniqueness enforcement to prevent password reuse, and comprehensive input validation to prevent injection attacks. The schema also supports password history checking and policy enforcement for enterprise security requirements.

    The validation supports various password change flows including user-initiated password updates, administrative password resets, and forced password changes due to security policy updates. It maintains compatibility with multi-factor authentication systems and password strength indicators for user guidance.

    // Standard password update validation
    const passwordUpdateData = {
    current_password: 'OldPassword123!',
    new_password: 'NewSecurePass456@'
    };

    const result = PasswordUpdateSchema.safeParse(passwordUpdateData);
    if (result.success) {
    console.log('Password update data is valid');
    } else {
    console.log('Validation errors:', result.error.errors);
    }
    // Password update endpoint with validation
    router.put('/auth/password',
    authenticateToken,
    validate({ body: PasswordUpdateSchema }),
    async (req, res) => {
    const { current_password, new_password } = req.body;
    const userId = req.user.id;

    try {
    // Verify current password
    const isCurrentValid = await authService.verifyPassword(userId, current_password);
    if (!isCurrentValid) {
    return res.status(400).json({ error: 'Current password is incorrect' });
    }

    // Update to new password
    await authService.updatePassword(userId, new_password);
    res.json({ success: true, message: 'Password updated successfully' });
    } catch (error) {
    res.status(500).json({ error: 'Password update failed' });
    }
    }
    );
    // Client-side password update with validation
    const updatePassword = async (currentPassword: string, newPassword: string) => {
    const updateData = {
    current_password: currentPassword,
    new_password: newPassword
    };

    const validation = PasswordUpdateSchema.safeParse(updateData);
    if (!validation.success) {
    const errors = validation.error.errors.map(err => ({
    field: err.path.join('.'),
    message: err.message
    }));
    throw new ValidationError('Password update validation failed', errors);
    }

    const response = await fetch('/api/auth/password', {
    method: 'PUT',
    headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify(validation.data)
    });

    return await response.json();
    };
    // Password update with history checking
    const validatePasswordUpdate = async (userId: string, updateData: unknown) => {
    const validation = PasswordUpdateSchema.safeParse(updateData);
    if (!validation.success) {
    throw new ValidationError('Invalid password update data');
    }

    const { current_password, new_password } = validation.data;

    // Check password history to prevent reuse
    const isPasswordReused = await passwordHistoryService.checkReuse(userId, new_password);
    if (isPasswordReused) {
    throw new ValidationError('Cannot reuse recent passwords');
    }

    return validation.data;
    };
    // Handling password update validation errors
    const handlePasswordUpdate = (formData: { currentPassword: string; newPassword: string }) => {
    const updateData = {
    current_password: formData.currentPassword,
    new_password: formData.newPassword
    };

    const result = PasswordUpdateSchema.safeParse(updateData);

    if (!result.success) {
    const fieldErrors = result.error.errors.reduce((acc, err) => {
    const field = err.path[0] as string;
    if (!acc[field]) acc[field] = [];
    acc[field].push(err.message);
    return acc;
    }, {} as Record<string, string[]>);

    return { isValid: false, errors: fieldErrors };
    }

    return { isValid: true, data: result.data };
    };