cms-laravel/app/Livewire/ChangePassword.php

92 lines
3.4 KiB
PHP

<?php
namespace App\Livewire;
use Livewire\Component;
use App\Services\ApiService;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
class ChangePassword extends Component
{
public $username = '';
public $admin_uuid = '';
public $newPassword = '';
public $confirmPassword = '';
public $isSubmitting = false;
public $errors = [];
protected $apiService;
public function boot(ApiService $apiService)
{
$this->apiService = $apiService;
}
public function mount()
{
// Get parameters from query or session
$this->username = request()->query('username', Session::get('change_password_username', ''));
$this->admin_uuid = request()->query('admin_uuid', Session::get('change_password_admin_uuid', ''));
if (!$this->username || !$this->admin_uuid) {
Session::flash('error', 'Sign in first before changing password.');
return redirect()->route('login');
}
}
public function changePassword()
{
$this->isSubmitting = true;
$this->errors = [];
try {
$this->validate([
'newPassword' => [
'required',
'min:6',
'regex:/[!@#$%^&*(),.?":{}|<>]/', // Special character
'regex:/[a-z]/', // Small letter
'regex:/[A-Z]/', // Capital letter
'regex:/\d+/', // Number
],
'confirmPassword' => ['required', 'same:newPassword'],
], [
'newPassword.required' => 'New password is required.',
'newPassword.min' => 'Password must be at least 6 characters.',
'newPassword.regex' => 'Password must contain a special character, a small letter, a capital letter, and a number.',
'confirmPassword.required' => 'Confirm password is required.',
'confirmPassword.same' => 'Passwords do not match.',
]);
$params = [
'username' => $this->username,
'admin_uuid' => $this->admin_uuid,
'password' => $this->confirmPassword,
];
$response = $this->apiService->post('login_changePassword', $params);
if ($response && isset($response['code']) && $response['code'] === 200) {
Session::flash('success', 'Password successfully updated. You may now login using your new password.');
Log::info('Password changed successfully', ['source' => 'ChangePasswordComponent']);
return redirect()->route('login');
} else {
throw new \Exception($response['data']['password'] ?? $response['message'] ?? 'Unknown error');
}
} catch (\Illuminate\Validation\ValidationException $e) {
$this->errors = $e->errors();
Log::error('Password change validation failed', ['errors' => $this->errors, 'source' => 'ChangePasswordComponent']);
} catch (\Exception $e) {
Session::flash('error', 'Error changing password: ' . $e->getMessage());
Log::error('Password change failed', ['error' => $e->getMessage(), 'source' => 'ChangePasswordComponent']);
} finally {
$this->isSubmitting = false;
}
}
public function render()
{
return view('livewire.change-password')->layout('layouts.app', ['title' => 'Change Password']);
}
}