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

55 lines
1.5 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\UserLoginRequest;
2020-09-06 18:21:39 +00:00
use App\Models\User;
use App\Repositories\UserRepository;
use App\Services\TokenManager;
use Illuminate\Contracts\Auth\Authenticatable;
2021-05-21 11:50:23 +00:00
use Illuminate\Foundation\Auth\ThrottlesLogins;
2020-09-06 18:21:39 +00:00
use Illuminate\Hashing\HashManager;
2022-11-16 17:57:38 +00:00
use Illuminate\Http\Request;
2020-09-06 18:21:39 +00:00
use Illuminate\Http\Response;
2016-05-30 05:50:59 +00:00
class AuthController extends Controller
{
2021-05-21 11:50:23 +00:00
use ThrottlesLogins;
2022-07-29 06:47:10 +00:00
/** @param User $user */
2020-09-06 18:21:39 +00:00
public function __construct(
2022-07-29 06:47:10 +00:00
private UserRepository $userRepository,
private HashManager $hash,
private TokenManager $tokenManager,
private ?Authenticatable $user
2020-09-06 21:20:42 +00:00
) {
2018-08-31 13:47:15 +00:00
}
2016-05-30 05:50:59 +00:00
public function login(UserLoginRequest $request)
{
2020-12-22 23:01:49 +00:00
/** @var User|null $user */
2020-09-06 18:21:39 +00:00
$user = $this->userRepository->getFirstWhere('email', $request->email);
if (!$user || !$this->hash->check($request->password, $user->password)) {
abort(Response::HTTP_UNAUTHORIZED, 'Invalid credentials');
}
2016-05-30 05:50:59 +00:00
2022-11-16 17:57:38 +00:00
$token = $this->tokenManager->createCompositionToken($user);
2020-09-06 18:21:39 +00:00
return response()->json([
2022-11-16 17:57:38 +00:00
'token' => $token->apiToken,
'audio-token' => $token->audioToken,
2020-09-06 18:21:39 +00:00
]);
2016-05-30 05:50:59 +00:00
}
2022-11-16 17:57:38 +00:00
public function logout(Request $request)
2016-05-30 05:50:59 +00:00
{
2022-11-16 17:57:38 +00:00
if ($this->user) {
attempt(fn () => $this->tokenManager->deleteCompositionToken($request->bearerToken()));
}
2016-05-30 05:50:59 +00:00
return response()->noContent();
2016-05-30 05:50:59 +00:00
}
}