AuthController.php 17 KB

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