AuthController.php 18 KB

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