AuthController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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) ? 60 : 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. $res = ShortLetterRepositories::SMSSend($phone, $data, $temp($type));
  183. } else {
  184. //发邮件
  185. $res = ShortLetterRepositories::EmailSend($phone, $data);
  186. }
  187. //发短信
  188. if ($res !== true)
  189. return app('json')->fail('验证码发送失败' . $res);
  190. CacheService::set('code_' . $phone, $code, $time);
  191. // Cache::set($keyName, $num + 1, 300);
  192. Cache::set($nowKey, $total, 61);
  193. return app('json')->success('发送成功');
  194. }
  195. /**
  196. * H5注册新用户
  197. * @param Request $request
  198. * @return mixed
  199. * @throws DataNotFoundException
  200. * @throws DbException
  201. * @throws ModelNotFoundException
  202. */
  203. public function register(Request $request)
  204. {
  205. list($phone, $email, $captcha, $password, $check_psw, $trade_password, $check_trade_psw, $invite_code) = UtilService::postMore([['phone', ''], ['email', ''], ['captcha', ''], ['password', ''], ['check_psw'], ['trade_password', ''], ['check_trade_psw', ''], ['invite_code', '']], $request, true);
  206. try {
  207. validate(RegisterValidates::class)->scene('register')->check(['phone' => $phone, 'email' => $email, 'captcha' => $captcha, 'password' => $password, 'trade_password' => $trade_password]);
  208. } catch (ValidateException $e) {
  209. return app('json')->fail($e->getError());
  210. }
  211. if ($password != $check_psw) {
  212. return app('json')->fail('两次输入的密码不一致');
  213. }
  214. if ($trade_password != $check_trade_psw) {
  215. return app('json')->fail('两次输入的交易密码不一致');
  216. }
  217. if (!$invite_code && User::count() > 0) return app('json')->fail('请输入邀请码');
  218. if ($phone) {
  219. if (!$captcha) {
  220. return app('json')->fail('请输入验证码');
  221. }
  222. $verifyCode = CacheService::get('code_' . $phone);
  223. if (!$verifyCode)
  224. return app('json')->fail('请先获取验证码');
  225. $verifyCode = substr($verifyCode, 0, 6);
  226. if ($verifyCode != $captcha)
  227. return app('json')->fail('验证码错误');
  228. }
  229. if (!$phone && !$email) {
  230. return app('json')->fail('请输入对应注册方式的账号');
  231. }
  232. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  233. return app('json')->fail('密码必须是在6到16位之间');
  234. if (strlen(trim($trade_password)) < 6 || strlen(trim($trade_password)) > 6 || !is_numeric($trade_password))
  235. return app('json')->fail('交易密码为6位数字');
  236. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  237. if ($trade_password == '123456') return app('json')->fail('交易密码太过简单,请输入较为复杂的密码');
  238. $spread = User::where('invite_code', $invite_code)->value('uid') ?: 0;
  239. // if ($spread == 0) return app('json')->fail('请输入有效的邀请码');
  240. $registerStatus = User::register($phone ? $phone : $email, $password, $trade_password, $spread);
  241. if ($registerStatus) return app('json')->success('注册成功');
  242. return app('json')->fail(User::getErrorInfo('注册失败'));
  243. }
  244. /**
  245. * 密码修改
  246. * @param Request $request
  247. * @return mixed
  248. */
  249. public function reset(Request $request)
  250. {
  251. list($account, $captcha, $password, $password2, $type) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['password2', ''], ['type', 1]], $request, true);
  252. try {
  253. validate(RegisterValidates::class)->scene('reset')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'password2' => $password2]);
  254. } catch (ValidateException $e) {
  255. return app('json')->fail($e->getError());
  256. }
  257. $verifyCode = CacheService::get('code_' . $account);
  258. if (!$verifyCode)
  259. return app('json')->fail('请先获取验证码');
  260. $verifyCode = substr($verifyCode, 0, 6);
  261. if ($verifyCode != $captcha)
  262. return app('json')->fail('验证码错误');
  263. if ($password != $password2)
  264. return app('json')->fail('两次输入的密码不一致');
  265. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  266. return app('json')->fail('密码必须是在6到16位之间');
  267. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  268. $resetStatus = User::reset($account, $password, $type);
  269. if ($resetStatus) return app('json')->success('修改成功');
  270. return app('json')->fail(User::getErrorInfo('修改失败'));
  271. }
  272. /**
  273. * 手机号登录
  274. * @param Request $request
  275. * @return mixed
  276. * @throws DataNotFoundException
  277. * @throws ModelNotFoundException
  278. * @throws \think\exception\DbException
  279. */
  280. public function mobile(Request $request)
  281. {
  282. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  283. //验证手机号
  284. try {
  285. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  286. } catch (ValidateException $e) {
  287. return app('json')->fail($e->getError());
  288. }
  289. //验证验证码
  290. $verifyCode = CacheService::get('code_' . $phone);
  291. if (!$verifyCode)
  292. return app('json')->fail('请先获取验证码');
  293. $verifyCode = substr($verifyCode, 0, 6);
  294. if ($verifyCode != $captcha)
  295. return app('json')->fail('验证码错误');
  296. //数据库查询
  297. $user = User::where('account', $phone)->find();
  298. if (!$user)
  299. return app('json')->fail('用户不存在');
  300. if (!$user->status)
  301. return app('json')->fail('已被禁止,请联系管理员');
  302. // 设置推广关系
  303. User::setSpread($spread, $user->uid);
  304. $token = UserToken::createToken($user, 'user');
  305. if ($token) {
  306. event('UserLogin', [$user, $token]);
  307. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  308. } else
  309. return app('json')->fail('登录失败');
  310. }
  311. /**
  312. * H5切换登陆
  313. * @param Request $request
  314. * @return mixed
  315. * @throws DataNotFoundException
  316. * @throws ModelNotFoundException
  317. * @throws \think\exception\DbException
  318. */
  319. public function switch_h5(Request $request)
  320. {
  321. $from = $request->post('from', 'wechat');
  322. $user = $request->user();
  323. if ($from === 'h5') {
  324. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  325. $user->login_type = 'wechat';
  326. $user->save();
  327. } else {
  328. //数据库查询
  329. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  330. if (!$user)
  331. return app('json')->fail('H5用户不存在,无法切换');
  332. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  333. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  334. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  335. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  336. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  337. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  338. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  339. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  340. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  341. switch ($from) {
  342. case 'wechat':
  343. if (!$wechatH5UserInfo->openid)
  344. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  345. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  346. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  347. break;
  348. case 'routine':
  349. if (!$wechatH5UserInfo->routine_openid)
  350. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  351. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  352. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  353. break;
  354. }
  355. $wechatH5UserInfo->save();
  356. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  357. }
  358. $token = UserToken::createToken($user, 'user');
  359. if ($token) {
  360. event('UserLogin', [$user, $token]);
  361. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  362. } else
  363. return app('json')->fail('登录失败');
  364. }
  365. /**
  366. * 绑定手机号
  367. * @param Request $request
  368. * @return mixed
  369. * @throws DataNotFoundException
  370. * @throws ModelNotFoundException
  371. * @throws \think\exception\DbException
  372. */
  373. public function binding_phone(Request $request)
  374. {
  375. list($phone, $captcha, $step) = UtilService::postMore([
  376. ['phone', ''],
  377. ['captcha', ''],
  378. ['step', 0]
  379. ], $request, true);
  380. //验证手机号
  381. try {
  382. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  383. } catch (ValidateException $e) {
  384. return app('json')->fail($e->getError());
  385. }
  386. //验证验证码
  387. $verifyCode = CacheService::get('code_' . $phone);
  388. if (!$verifyCode)
  389. return app('json')->fail('请先获取验证码');
  390. $verifyCode = substr($verifyCode, 0, 6);
  391. if ($verifyCode != $captcha)
  392. return app('json')->fail('验证码错误');
  393. $userInfo = User::where('uid', $request->uid())->find();
  394. $userPhone = $userInfo->phone;
  395. if (!$userInfo) return app('json')->fail('用户不存在');
  396. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  397. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  398. return app('json')->success('此手机已经绑定,无法多次绑定!');
  399. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  400. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  401. $userInfo->phone = $phone;
  402. } else {
  403. $userInfo->account = $phone;
  404. $userInfo->phone = $phone;
  405. }
  406. if ($userInfo->save() || $userPhone == $phone)
  407. return app('json')->success('绑定成功');
  408. else
  409. return app('json')->fail('绑定失败');
  410. }
  411. }