AuthorizationController.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Http\Controllers;
  11. use App\Http\Resources\UserResource;
  12. use App\Repositories\Enums\ResponseCodeEnum;
  13. use Illuminate\Http\Request;
  14. use Jiannei\Response\Laravel\Support\Facades\Response;
  15. class AuthorizationController extends Controller
  16. {
  17. /**
  18. * Create a new AuthController instance.
  19. */
  20. public function __construct()
  21. {
  22. $this->middleware('auth:api', ['except' => ['store']]);
  23. }
  24. public function destroy()
  25. {
  26. auth()->logout();
  27. return Response::noContent();
  28. }
  29. public function show()
  30. {
  31. $user = auth()->userOrFail();
  32. return Response::success(new UserResource($user));
  33. }
  34. public function store(Request $request)
  35. {
  36. $this->validate($request, [
  37. 'email' => 'filled|email',
  38. 'name' => 'required_without:email',
  39. 'password' => 'required',
  40. ]);
  41. $credentials = request(['name', 'email', 'password']);
  42. if (!$token = auth()->attempt($credentials)) {
  43. Response::errorUnauthorized();
  44. }
  45. return $this->respondWithToken($token);
  46. }
  47. protected function respondWithToken($token)
  48. {
  49. return Response::success(
  50. [
  51. 'access_token' => $token,
  52. 'token_type' => 'bearer',
  53. 'expires_in' => auth()->factory()->getTTL() * 60,
  54. ],
  55. '',
  56. ResponseCodeEnum::SERVICE_LOGIN_SUCCESS
  57. );
  58. }
  59. public function update()
  60. {
  61. return $this->respondWithToken(auth()->refresh());
  62. }
  63. }