unioil-cms-fe/app/Livewire/Buttons/UpdateUser.php

121 lines
3.6 KiB
PHP

<?php
namespace App\Livewire\Buttons;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Livewire\Component;
class UpdateUser extends Component
{
public $uuid;
public $username;
public $firstname;
public $lastname;
public $email;
public $status;
public $role;
public $default_password = '********************';
public function mount($uuid)
{
$this->uuid = $uuid;
$token = Session::get('user')['access_token'] ?? null;
if (!$token) {
$this->addError('users', 'No access token found.');
return;
}
$response = Http::withToken($token)->get(config('services.backend_api.url') . "/api/cms/admin/{$uuid}");
if ($response->successful()) {
$user = $response->json('data');
$this->username = $user['username'] ?? '';
$this->firstname = $user['firstname'] ?? '';
$this->lastname = $user['lastname'] ?? '';
$this->email = $user['email'] ?? '';
$this->status = $user['status'] ?? '';
$this->role = $user['role'] ?? '';
} else {
$this->addError('users', 'Failed to fetch user data.');
}
}
public function generatePassword()
{
try {
// Get the access token from the session
$token = Session::get('user')['access_token'] ?? null;
if (!$token) {
$this->addError('users', 'No access token found.');
return;
}
// Make the request to generate the password
$response = Http::withToken($token)
->post(config('services.backend_api.url') . '/api/cms/generatePassword');
// Check if the request was successful
if ($response->successful()) {
// Retrieve the password from the response
$this->default_password = $response->json()['data']['password'];
} else {
$this->addError('users', 'Failed to generate password.');
}
} catch (\Exception $e) {
// Handle any exceptions that occur during the request
$this->addError('users', 'Error: ' . $e->getMessage());
}
}
public function submit()
{
$token = Session::get('user')['access_token'] ?? null;
if (!$token) {
$this->addError('users', 'No access token found.');
return;
}
$response = Http::withToken($token)->put(config('services.backend_api.url') . "/api/cms/admin/{$this->uuid}", [
'username' => $this->username,
'firstname' => $this->firstname,
'lastname' => $this->lastname,
'email' => $this->email,
'status' => $this->status,
'password' => $this->default_password,
'role' => $this->role,
]);
if ($response->status() === 422) {
$errors = $response->json('data');
foreach ($errors as $field => $messages) {
$this->addError($field, $messages[0]);
}
return;
}
if ($response->successful()) {
session()->flash('success', 'User updated successfully.');
return redirect('/main/user-management');
} else {
$this->addError('users', 'Failed to update user.');
}
}
public function cancel()
{
return redirect()->to('/main/user-management');
}
public function render()
{
return view('livewire.buttons.update-user');
}
}