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

55 lines
1.4 KiB
PHP
Raw Normal View History

2016-05-30 05:50:59 +00:00
<?php
namespace App\Http\Controllers\API;
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;
use Illuminate\Hashing\HashManager;
use Illuminate\Http\Response;
2016-05-30 05:50:59 +00:00
class AuthController extends Controller
{
2020-09-06 18:21:39 +00:00
private $userRepository;
private $hash;
private $tokenManager;
2018-08-31 13:47:15 +00:00
2020-09-06 18:21:39 +00:00
/** @var User|null */
private $currentUser;
public function __construct(
UserRepository $userRepository,
HashManager $hash,
TokenManager $tokenManager,
?Authenticatable $currentUser
2020-09-06 21:20:42 +00:00
) {
2020-09-06 18:21:39 +00:00
$this->userRepository = $userRepository;
$this->hash = $hash;
$this->currentUser = $currentUser;
$this->tokenManager = $tokenManager;
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
2020-09-06 18:21:39 +00:00
return response()->json([
2020-09-06 21:20:42 +00:00
'token' => $this->tokenManager->createToken($user)->plainTextToken,
2020-09-06 18:21:39 +00:00
]);
2016-05-30 05:50:59 +00:00
}
public function logout()
{
2020-09-06 18:21:39 +00:00
$this->tokenManager->destroyTokens($this->currentUser);
2016-05-30 05:50:59 +00:00
2020-09-13 22:04:07 +00:00
return response()->json(null, Response::HTTP_NO_CONTENT);
2016-05-30 05:50:59 +00:00
}
}