2016-05-30 05:50:59 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Controllers\API;
|
|
|
|
|
|
|
|
use App\Http\Requests\API\UserLoginRequest;
|
|
|
|
use Exception;
|
2017-06-04 01:30:45 +00:00
|
|
|
use Illuminate\Http\JsonResponse;
|
2018-08-31 13:47:15 +00:00
|
|
|
use Illuminate\Log\Logger;
|
|
|
|
use Tymon\JWTAuth\JWTAuth;
|
2016-05-30 05:50:59 +00:00
|
|
|
|
2018-12-09 21:24:43 +00:00
|
|
|
/**
|
|
|
|
* @group 1. Authentication
|
|
|
|
*/
|
2016-05-30 05:50:59 +00:00
|
|
|
class AuthController extends Controller
|
|
|
|
{
|
2018-08-31 13:47:15 +00:00
|
|
|
private $auth;
|
|
|
|
private $logger;
|
|
|
|
|
|
|
|
public function __construct(JWTAuth $auth, Logger $logger)
|
|
|
|
{
|
|
|
|
$this->auth = $auth;
|
|
|
|
$this->logger = $logger;
|
|
|
|
}
|
|
|
|
|
2016-05-30 05:50:59 +00:00
|
|
|
/**
|
2020-04-07 21:41:30 +00:00
|
|
|
* Log a user in.
|
2016-05-30 05:50:59 +00:00
|
|
|
*
|
2018-12-09 21:24:43 +00:00
|
|
|
* Koel uses [JSON Web Tokens](https://jwt.io/) (JWT) for authentication.
|
|
|
|
* After the user has been authenticated, a random "token" will be returned.
|
|
|
|
* This token should then be saved in a local storage and used as an `Authorization: Bearer` header
|
|
|
|
* for consecutive calls.
|
|
|
|
*
|
|
|
|
* Notice: The token is valid for a week, after that the user will need to log in again.
|
|
|
|
*
|
|
|
|
* @bodyParam email string required The user's email. Example: john@doe.com
|
|
|
|
* @bodyParam password string required The password. Example: SoSecureMuchW0w
|
|
|
|
*
|
|
|
|
* @response {
|
|
|
|
* "token": "<a-random-string>"
|
|
|
|
* }
|
|
|
|
* @reponse 401 {
|
|
|
|
* "message": "Invalid credentials"
|
|
|
|
* }
|
|
|
|
*
|
2017-06-04 01:30:45 +00:00
|
|
|
* @return JsonResponse
|
2016-05-30 05:50:59 +00:00
|
|
|
*/
|
|
|
|
public function login(UserLoginRequest $request)
|
|
|
|
{
|
2018-08-31 13:47:15 +00:00
|
|
|
$token = $this->auth->attempt($request->only('email', 'password'));
|
2017-12-09 18:34:27 +00:00
|
|
|
abort_unless($token, 401, 'Invalid credentials');
|
2016-05-30 05:50:59 +00:00
|
|
|
|
|
|
|
return response()->json(compact('token'));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-04-07 21:41:30 +00:00
|
|
|
* Log the current user out.
|
2016-05-30 05:50:59 +00:00
|
|
|
*
|
2017-06-04 01:30:45 +00:00
|
|
|
* @return JsonResponse
|
2016-05-30 05:50:59 +00:00
|
|
|
*/
|
|
|
|
public function logout()
|
|
|
|
{
|
2018-08-31 13:47:15 +00:00
|
|
|
if ($token = $this->auth->getToken()) {
|
2016-05-30 05:50:59 +00:00
|
|
|
try {
|
2018-08-31 13:47:15 +00:00
|
|
|
$this->auth->invalidate($token);
|
2016-05-30 05:50:59 +00:00
|
|
|
} catch (Exception $e) {
|
2018-08-31 13:47:15 +00:00
|
|
|
$this->logger->error($e);
|
2016-05-30 05:50:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return response()->json();
|
|
|
|
}
|
|
|
|
}
|