LoginController.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Http\Controllers\AdminApi;
  3. use App\Http\Controllers\AdminController;
  4. use App\Models\UserModels\User;
  5. use App\Servers\Common\CommonServer;
  6. use App\Servers\Common\PassServer;
  7. use App\Servers\Common\RedisDataServer;
  8. class LoginController extends AdminController
  9. {
  10. /**
  11. * 后台登录
  12. * @return \Illuminate\Http\JsonResponse
  13. */
  14. function login(){
  15. // $type = request()->input('type',1);//登录类型 1密码2验证码
  16. $phone = request()->input('phone', '');//账号
  17. $password = request()->input('password', '123456');//密码
  18. $code = request()->input('code', '');//验证码
  19. // if(!in_array($type,[1,2])) return $this->apiResponseError('缺少必要参数');
  20. if (empty($phone)) return $this->apiResponseError( '登录手机号必填');
  21. if(!CommonServer::creatServer()->verifyPhoneNumber($phone)){
  22. return $this->apiResponseError( '手机号不正确');
  23. }
  24. if (empty($password)) return $this->apiResponseError( '登录密码必填');
  25. //获取用户信息
  26. $where = [['is_del',0], ['phone',$phone]];
  27. $user = User::where($where)->select(['id', 'password', 'encrypt', 'api_token','status'])->first();
  28. if (empty($user)) {
  29. return $this->apiResponseError('当前账户不存在');
  30. }
  31. if ($user['status'] == 2) {
  32. return $this->apiResponseError('账户已关闭');
  33. }
  34. //密码验证
  35. $pass_server = PassServer::creatServer($password, $user->{'encrypt'});
  36. if (!$pass_server->verifyPass($user->{'password'})) {
  37. return $this->apiResponseError('登陆密码错误');
  38. }
  39. //记录旧token
  40. $old_token = 'gw_adminLogin_' . $user['api_token'];
  41. //生成token
  42. $token = hash('sha256', $user['id'] . 'token' . time());
  43. $update['api_token'] = $token;
  44. //更新token
  45. $token_ret = $user->update($update);
  46. if(empty($token_ret)){
  47. return $this->apiResponseError('登陆信息更新失败');
  48. }
  49. //清除原token缓存
  50. if(RedisDataServer::creatServer()->getData($old_token,'json')){
  51. RedisDataServer::creatServer()->delData($old_token);
  52. }
  53. //获取用户信息
  54. $info = User::where('api_token', $token)->select(['id','name','phone'])->first();
  55. return $this->apiResponseSuccess('登录成功',['token'=>$token,'user'=>$info]);
  56. }
  57. /**
  58. * 退出登录
  59. * @return \Illuminate\Http\JsonResponse
  60. */
  61. public function logout()
  62. {
  63. $token = request()->input('api_token');
  64. if(empty($token)) $token = request()->header('ApiToken');
  65. //清除原token缓存
  66. RedisDataServer::creatServer()->delData( 'adminApiLogin_' . $token);
  67. User::where('api_token', $token)->update(['api_token'=>'']);
  68. return $this->apiResponseSuccess('退出成功');
  69. }
  70. }