AuthController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. namespace app\api\controller;
  3. use app\admin\model\sms\SmsRecord;
  4. use app\http\validates\user\RegisterValidates;
  5. use app\http\validates\user\RestValidates;
  6. use app\models\user\User;
  7. use app\models\user\UserToken;
  8. use app\models\user\WechatUser;
  9. use app\Request;
  10. use crmeb\jobs\TestJob;
  11. use crmeb\repositories\ShortLetterRepositories;
  12. use crmeb\services\CacheService;
  13. use crmeb\services\UtilService;
  14. use think\facade\Cache;
  15. use think\exception\ValidateException;
  16. use think\facade\Config;
  17. use think\facade\Queue;
  18. use think\facade\Session;
  19. /**微信小程序授权类
  20. * Class AuthController
  21. * @package app\api\controller
  22. */
  23. class AuthController
  24. {
  25. /**
  26. * H5账号登陆
  27. * @param Request $request
  28. * @return mixed
  29. * @throws \think\db\exception\DataNotFoundException
  30. * @throws \think\db\exception\ModelNotFoundException
  31. * @throws \think\exception\DbException
  32. */
  33. public function login(Request $request)
  34. {
  35. $user = User::where('account', $request->param('account'))->find();
  36. if ($user) {
  37. if ($user->pwd !== md5($request->param('password')))
  38. return app('json')->fail('账号或密码错误');
  39. if ($user->pwd === md5(123456))
  40. return app('json')->fail('请修改您的初始密码,再尝试登陆!');
  41. } else {
  42. return app('json')->fail('账号或密码错误');
  43. }
  44. if (!$user['status'])
  45. return app('json')->fail('已被禁止,请联系管理员');
  46. // 设置推广关系
  47. User::setSpread(intval($request->param('spread')), $user->uid);
  48. $token = UserToken::createToken($user, 'user');
  49. if ($token) {
  50. event('UserLogin', [$user, $token]);
  51. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  52. } else
  53. return app('json')->fail('登录失败');
  54. }
  55. /**
  56. * 退出登录
  57. * @param Request $request
  58. */
  59. public function logout(Request $request)
  60. {
  61. $request->tokenData()->delete();
  62. return app('json')->success('成功');
  63. }
  64. public function verifyCode()
  65. {
  66. $unique = password_hash(uniqid(true), PASSWORD_BCRYPT);
  67. Cache::set('sms.key.' . $unique, 0, 300);
  68. return app('json')->success(['key' => $unique]);
  69. }
  70. public function captcha(Request $request)
  71. {
  72. ob_clean();
  73. $rep = captcha();
  74. $key = app('session')->get('captcha.key');
  75. $uni = $request->get('key');
  76. if ($uni)
  77. Cache::set('sms.key.cap.' . $uni, $key, 300);
  78. return $rep;
  79. }
  80. /**
  81. * 验证验证码是否正确
  82. *
  83. * @param $uni
  84. * @param string $code
  85. * @return bool
  86. * @throws \Psr\SimpleCache\InvalidArgumentException
  87. */
  88. protected function checkCaptcha($uni, string $code): bool
  89. {
  90. $cacheName = 'sms.key.cap.' . $uni;
  91. if (!Cache::has($cacheName)) {
  92. return false;
  93. }
  94. $key = Cache::get($cacheName);
  95. $code = mb_strtolower($code, 'UTF-8');
  96. $res = password_verify($code, $key);
  97. if ($res) {
  98. Cache::delete($cacheName);
  99. }
  100. return $res;
  101. }
  102. /**
  103. * 验证码发送
  104. * @param Request $request
  105. * @return mixed
  106. */
  107. public function verify(Request $request)
  108. {
  109. list($phone, $type, $key, $code) = UtilService::postMore([['phone', 0], ['type', ''], ['key', ''], ['code', '']], $request, true);
  110. $temp = function ($item) {
  111. switch ($item) {
  112. case "register":
  113. return 'REGISTER';
  114. case "login":
  115. return 'LOGIN';
  116. case "reset":
  117. return 'RESET';
  118. case "reset_2":
  119. return 'RESET_2';
  120. case "trade":
  121. return 'TRADE';
  122. default:
  123. return 'DEFAULT';
  124. }
  125. };
  126. // $keyName = 'sms.key.' . $key;
  127. $nowKey = 'sms.' . date('YmdHi');
  128. //
  129. // if (!Cache::has($keyName))
  130. // return app('json')->make(401, '发送验证码失败');
  131. //
  132. // if (($num = Cache::get($keyName)) > 2) {
  133. // if (!$code)
  134. // return app('json')->make(402, '请输入验证码');
  135. //
  136. // if (!$this->checkCaptcha($key, $code))
  137. // return app('json')->fail('验证码输入有误');
  138. // }
  139. $total = 1;
  140. if ($has = Cache::has($nowKey)) {
  141. $total = Cache::get($nowKey);
  142. if ($total > Config::get('sms.maxMinuteCount', 20))
  143. return app('json')->success('已发送');
  144. }
  145. try {
  146. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  147. } catch (ValidateException $e) {
  148. return app('json')->fail($e->getError());
  149. }
  150. if (User::checkPhone($phone) && $type == 'register') return app('json')->fail('手机号已注册');
  151. if (!User::checkPhone($phone) && $type == 'login') return app('json')->fail('账号不存在!');
  152. $default = Config::get('sms.default', 'yunxin');
  153. $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
  154. $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
  155. $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
  156. $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
  157. // if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
  158. // return app('json')->fail('您今日发送得短信次数已经达到上限');
  159. // }
  160. if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
  161. return app('json')->fail('此IP今日发送次数已经达到上限');
  162. }
  163. $time = 60;
  164. // if (CacheService::get('code_' . $phone))
  165. // return app('json')->fail($time . '秒内有效');
  166. $code = rand(100000, 999999);
  167. $data['code'] = $code;
  168. $res = self::NewSmsSend($phone, $data, $temp($type));
  169. // $res = ShortLetterRepositories::send(true, $phone, $data, 'VERIFICATION_CODE');
  170. if ($res !== true)
  171. return app('json')->fail('短信平台验证码发送失败' . $res);
  172. CacheService::set('code_' . $phone, $code, $time);
  173. // Cache::set($keyName, $num + 1, 300);
  174. // Cache::set($nowKey, $total, 61);
  175. return app('json')->success('短信验证发送成功');
  176. }
  177. /**
  178. * 发送短信
  179. * @param string $phone 手机号码
  180. * @param array $data 模板替换内容
  181. * @param string $template 模板编号
  182. * @return bool|string
  183. * @throws DataNotFoundException
  184. * @throws ModelNotFoundException
  185. */
  186. public static function NewSmsSend(string $phone, array $data, string $template)
  187. {
  188. try {
  189. $res = ZjSMSServerService::send($phone, $data);
  190. // var_dump($res);
  191. // exit;
  192. if ($res['status'] != '200') {
  193. return $res['msg'];
  194. } else {
  195. SmsRecord::sendRecord($phone, $data['code'], $template, '');
  196. }
  197. return true;
  198. } catch (Exception $exception) {
  199. // Log::info($exception->getMessage());
  200. return $exception->getMessage();
  201. }
  202. }
  203. /**
  204. * H5注册新用户
  205. * @param Request $request
  206. * @return mixed
  207. */
  208. public function register(Request $request)
  209. {
  210. list($account, $captcha, $password, $spread, $payment_pas) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['spread', 0], ['payment_pas']], $request, true);
  211. try {
  212. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'payment_pas' => $payment_pas]);
  213. } catch (ValidateException $e) {
  214. return app('json')->fail($e->getError());
  215. }
  216. $verifyCode = CacheService::get('code_' . $account);
  217. if (!$verifyCode)
  218. return app('json')->fail('请先获取验证码');
  219. $verifyCode = substr($verifyCode, 0, 6);
  220. if ($verifyCode != $captcha)
  221. return app('json')->fail('验证码错误');
  222. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  223. return app('json')->fail('密码必须是在6到16位之间');
  224. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  225. $registerStatus = User::register($account, $password, $spread, $payment_pas);
  226. if ($registerStatus) return app('json')->success('注册成功');
  227. return app('json')->fail(User::getErrorInfo('注册失败'));
  228. }
  229. /**
  230. * 密码修改
  231. * @param Request $request
  232. * @return mixed
  233. */
  234. public function reset(Request $request)
  235. {
  236. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  237. try {
  238. validate(RestValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  239. } catch (ValidateException $e) {
  240. return app('json')->fail($e->getError());
  241. }
  242. $verifyCode = CacheService::get('code_' . $account);
  243. if (!$verifyCode)
  244. return app('json')->fail('请先获取验证码');
  245. $verifyCode = substr($verifyCode, 0, 6);
  246. if ($verifyCode != $captcha)
  247. return app('json')->fail('验证码错误');
  248. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  249. return app('json')->fail('密码必须是在6到16位之间');
  250. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  251. $resetStatus = User::reset($account, $password);
  252. if ($resetStatus) return app('json')->success('修改成功');
  253. return app('json')->fail(User::getErrorInfo('修改失败'));
  254. }
  255. /**
  256. * 手机号登录
  257. * @param Request $request
  258. * @return mixed
  259. * @throws \think\db\exception\DataNotFoundException
  260. * @throws \think\db\exception\ModelNotFoundException
  261. * @throws \think\exception\DbException
  262. */
  263. public function mobile(Request $request)
  264. {
  265. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  266. //验证手机号
  267. try {
  268. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  269. } catch (ValidateException $e) {
  270. return app('json')->fail($e->getError());
  271. }
  272. //验证验证码
  273. $verifyCode = CacheService::get('code_' . $phone);
  274. if (!$verifyCode)
  275. return app('json')->fail('请先获取验证码');
  276. $verifyCode = substr($verifyCode, 0, 6);
  277. if ($verifyCode != $captcha)
  278. return app('json')->fail('验证码错误');
  279. //数据库查询
  280. $user = User::where('account', $phone)->find();
  281. if (!$user)
  282. return app('json')->fail('用户不存在');
  283. if (!$user->status)
  284. return app('json')->fail('已被禁止,请联系管理员');
  285. // 设置推广关系
  286. User::setSpread($spread, $user->uid);
  287. $token = UserToken::createToken($user, 'user');
  288. if ($token) {
  289. event('UserLogin', [$user, $token]);
  290. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  291. } else
  292. return app('json')->fail('登录失败');
  293. }
  294. /**
  295. * H5切换登陆
  296. * @param Request $request
  297. * @return mixed
  298. * @throws \think\db\exception\DataNotFoundException
  299. * @throws \think\db\exception\ModelNotFoundException
  300. * @throws \think\exception\DbException
  301. */
  302. public function switch_h5(Request $request)
  303. {
  304. $from = $request->post('from', 'wechat');
  305. $user = $request->user();
  306. if ($from === 'h5') {
  307. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  308. $user->login_type = 'wechat';
  309. $user->save();
  310. } else {
  311. //数据库查询
  312. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  313. if (!$user)
  314. return app('json')->fail('H5用户不存在,无法切换');
  315. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  316. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  317. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  318. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  319. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  320. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  321. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  322. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  323. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  324. switch ($from) {
  325. case 'wechat':
  326. if (!$wechatH5UserInfo->openid)
  327. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  328. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  329. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  330. break;
  331. case 'routine':
  332. if (!$wechatH5UserInfo->routine_openid)
  333. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  334. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  335. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  336. break;
  337. }
  338. $wechatH5UserInfo->save();
  339. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  340. }
  341. $token = UserToken::createToken($user, 'user');
  342. if ($token) {
  343. event('UserLogin', [$user, $token]);
  344. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  345. } else
  346. return app('json')->fail('登录失败');
  347. }
  348. /**
  349. * 绑定手机号
  350. * @param Request $request
  351. * @return mixed
  352. * @throws \think\db\exception\DataNotFoundException
  353. * @throws \think\db\exception\ModelNotFoundException
  354. * @throws \think\exception\DbException
  355. */
  356. public function binding_phone(Request $request)
  357. {
  358. list($phone, $captcha, $step) = UtilService::postMore([
  359. ['phone', ''],
  360. ['captcha', ''],
  361. ['step', 0]
  362. ], $request, true);
  363. //验证手机号
  364. try {
  365. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  366. } catch (ValidateException $e) {
  367. return app('json')->fail($e->getError());
  368. }
  369. //验证验证码
  370. $verifyCode = CacheService::get('code_' . $phone);
  371. if (!$verifyCode)
  372. return app('json')->fail('请先获取验证码');
  373. $verifyCode = substr($verifyCode, 0, 6);
  374. if ($verifyCode != $captcha)
  375. return app('json')->fail('验证码错误');
  376. $userInfo = User::where('uid', $request->uid())->find();
  377. $userPhone = $userInfo->phone;
  378. if (!$userInfo) return app('json')->fail('用户不存在');
  379. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  380. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  381. return app('json')->success('此手机已经绑定,无法多次绑定!');
  382. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  383. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  384. $userInfo->phone = $phone;
  385. } else {
  386. $userInfo->account = $phone;
  387. $userInfo->phone = $phone;
  388. }
  389. if ($userInfo->save() || $userPhone == $phone)
  390. return app('json')->success('绑定成功');
  391. else
  392. return app('json')->fail('绑定失败');
  393. }
  394. }