AuthController.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019-04-29
  6. * Time: 9:54
  7. */
  8. namespace App\Http\Controllers\V1;
  9. use App\Shop;
  10. use App\ShopAccount;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\Auth;
  13. use Illuminate\Support\Facades\Validator;
  14. use Tymon\JWTAuth\Token;
  15. use Tymon\JWTAuth\Facades\JWTAuth;
  16. use App\Transformers\LoginTransformer;
  17. use League\Fractal\Manager;
  18. use League\Fractal\Resource\Item;
  19. use Tymon\JWTAuth\Facades\JWTFactory;
  20. class AuthController extends Controller {
  21. public function __construct(JWTAuth $jwt)
  22. {
  23. }
  24. public function refresh(Request $request)
  25. {
  26. $user = Auth::user();
  27. $user->token = Auth::refresh();
  28. $user->token_ttl = config('jwt.ttl');
  29. $user->is_password = !empty($user->password)?1:0;
  30. $fractal = new Manager();
  31. $res = new Item($user,new LoginTransformer());
  32. $array = $fractal->createData($res)->toArray();
  33. //同一类型登陆只允许登陆一个
  34. return $this->jsonSuccess($array);
  35. }
  36. /**
  37. * 登出
  38. * @return mixed
  39. */
  40. public function logout()
  41. {
  42. Auth::logout();
  43. return $this->jsonSuccess([],'登出成功');
  44. }
  45. //登陆
  46. public function login(Request $request){
  47. $data = $request->all();
  48. $validator = Validator::make($data, [
  49. 'account' => 'required|max:50',
  50. 'password' => 'required|max:32',
  51. ]);
  52. if ($validator->fails()) {
  53. return $this->response->error($validator->errors()->first(), 500);
  54. }
  55. $account = ShopAccount::where(['account'=>$data['account'],'status'=>1])->first();
  56. if(!$account){
  57. return $this->response->error('登录失败,请重试', 500);
  58. }
  59. $shop = Shop::where(['shop_id'=>$account->shop_id,'status'=>1])->first();
  60. if(!$shop){
  61. return $this->response->error('登录失败,该商家不存在或已禁用', 500);
  62. }
  63. $token = Auth::attempt(['account'=>$request->get('account'),'password'=>$request->get('password')]);
  64. if(!$token){
  65. return $this->response->error('登陆失败', 500);
  66. }else{
  67. $shopAccount = Auth::user();
  68. $factory = JWTFactory::customClaims(['shop'=>['uid'=>$shopAccount->id,'username'=>$shopAccount->account,'shop_id'=>$shopAccount->shop_id,'sign'=>md5($shopAccount->id).config('customer.jwt_secret')],'type'=>2]);
  69. $payload = $factory->make();
  70. $token = JWTAuth::encode($payload);
  71. $shopAccount->token = $token;
  72. $shopAccount->token_ttl = config('jwt.ttl');
  73. //如果有绑定微信,显示微信open_id
  74. $fractal = new Manager();
  75. $res = new Item($shopAccount,new LoginTransformer());
  76. $array = $fractal->createData($res)->toArray();
  77. //日志
  78. return $array;
  79. }
  80. }
  81. }