AuthController.php 19 KB

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