LoginController.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Http\Controllers\Passport;
  3. use Illuminate\Http\Request;
  4. use App\Http\Requests\Passport\LoginIndex;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\User;
  7. use Illuminate\Support\Facades\Redis;
  8. use App\Utils\Helper;
  9. class LoginController extends Controller
  10. {
  11. public function index (LoginIndex $request) {
  12. $email = $request->input('email');
  13. $password = $request->input('password');
  14. $user = User::where('email', $email)->first();
  15. if (!$user) {
  16. abort(500, '用户名或密码错误');
  17. }
  18. if (!password_verify($password, $user->password)) {
  19. abort(500, '用户名或密码错误');
  20. }
  21. $request->session()->put('email', $user->email);
  22. $request->session()->put('id', $user->id);
  23. if ($user->is_admin) {
  24. $request->session()->put('is_admin', true);
  25. }
  26. return response([
  27. 'data' => [
  28. 'is_admin' => $user->is_admin ? 2 : 1,
  29. 'token' => $user->token
  30. ]
  31. ]);
  32. }
  33. public function token2Login (Request $request) {
  34. if ($request->input('token')) {
  35. $user = User::where('token', $request->input('token'))->first();
  36. if (!$user) {
  37. return header('Location:' . config('v2board.app_url'));
  38. }
  39. $key = 'token2Login_' . Helper::guid();
  40. Redis::set($key, $user->id);
  41. Redis::expire($key, 600);
  42. $redirect = '/#/login?verify='. $key .'&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard');
  43. if (config('v2board.app_url')) {
  44. $location = config('v2board.app_url') . $redirect;
  45. } else {
  46. $location = url($redirect);
  47. }
  48. return header('Location:' . $location);
  49. }
  50. if ($request->input('verify')) {
  51. $key = 'token2Login_' . $request->input('verify');
  52. $userId = Redis::get($key);
  53. if (!$userId) {
  54. abort(500, '令牌有误');
  55. }
  56. $user = User::find($userId);
  57. if (!$user) {
  58. abort(500, '用户不存在');
  59. }
  60. $request->session()->put('email', $user->email);
  61. $request->session()->put('id', $user->id);
  62. if ($user->is_admin) {
  63. $request->session()->put('is_admin', true);
  64. }
  65. Redis::del($key);
  66. return response([
  67. 'data' => true
  68. ]);
  69. }
  70. }
  71. public function check (Request $request) {
  72. return response([
  73. 'data' => $request->session()->get('id') ? true : false
  74. ]);
  75. }
  76. }