AuthController.php 18 KB

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