koel/app/Http/Controllers/API/ProfileController.php

63 lines
1.8 KiB
PHP
Raw Normal View History

2016-05-30 05:50:59 +00:00
<?php
namespace App\Http\Controllers\API;
2022-07-29 06:47:10 +00:00
use App\Http\Controllers\Controller;
2016-05-30 05:50:59 +00:00
use App\Http\Requests\API\ProfileUpdateRequest;
2022-06-10 10:47:46 +00:00
use App\Http\Resources\UserResource;
2020-09-13 22:04:07 +00:00
use App\Models\User;
use App\Services\TokenManager;
2024-03-19 22:48:12 +00:00
use App\Services\UserService;
2020-09-13 22:04:07 +00:00
use Illuminate\Contracts\Auth\Authenticatable;
2022-06-10 10:47:46 +00:00
use Illuminate\Contracts\Hashing\Hasher;
2024-02-25 19:32:53 +00:00
use Illuminate\Http\Response;
2024-03-19 22:48:12 +00:00
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
2016-05-30 05:50:59 +00:00
class ProfileController extends Controller
{
2022-06-10 10:47:46 +00:00
/** @param User $user */
public function __construct(
private Hasher $hash,
2024-03-19 22:48:12 +00:00
private UserService $userService,
2022-06-10 10:47:46 +00:00
private TokenManager $tokenManager,
private ?Authenticatable $user
) {
2018-08-22 19:46:36 +00:00
}
2020-09-13 22:04:07 +00:00
public function show()
{
2022-06-10 10:47:46 +00:00
return UserResource::make($this->user);
}
2016-05-30 05:50:59 +00:00
public function update(ProfileUpdateRequest $request)
{
2024-02-25 19:32:53 +00:00
static::disableInDemo(Response::HTTP_NO_CONTENT);
2024-03-30 16:49:25 +00:00
// If the user is not using SSO, we need to verify their current password.
throw_if(
!$this->user->is_sso && !$this->hash->check($request->current_password, $this->user->password),
ValidationException::withMessages(['current_password' => 'Invalid current password'])
);
2024-03-19 22:48:12 +00:00
$user = $this->userService->updateUser(
user: $this->user,
name: $request->name,
email: $request->email,
password: $request->new_password,
avatar: Str::startsWith($request->avatar, 'data:') ? $request->avatar : null
);
2020-09-13 22:04:07 +00:00
2024-03-19 22:48:12 +00:00
$response = UserResource::make($user)->response();
2022-06-10 10:47:46 +00:00
if ($request->new_password) {
2022-11-16 17:57:38 +00:00
$response->header(
'Authorization',
$this->tokenManager->refreshApiToken($request->bearerToken() ?: '')->plainTextToken
);
2022-06-10 10:47:46 +00:00
}
2022-06-10 10:47:46 +00:00
return $response;
2016-05-30 05:50:59 +00:00
}
}