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;
|
|
|
|
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
|
|
|
|
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()
|
|
|
|
{
|
2022-07-29 06:47:10 +00:00
|
|
|
if ($this->user) {
|
|
|
|
$this->tokenManager->destroyTokens($this->user);
|
2022-07-28 05:51:34 +00:00
|
|
|
}
|
2016-05-30 05:50:59 +00:00
|
|
|
|
2021-12-06 17:07:43 +00:00
|
|
|
return response()->noContent();
|
2016-05-30 05:50:59 +00:00
|
|
|
}
|
|
|
|
}
|