AuthController.php 2.6 KB

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