AuthController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. namespace app\api\controller;
  3. use app\admin\model\sms\SmsRecord;
  4. use app\http\validates\user\RegisterValidates;
  5. use app\http\validates\user\RestValidates;
  6. use app\models\user\User;
  7. use app\models\user\UserToken;
  8. use app\models\user\WechatUser;
  9. use app\Request;
  10. use crmeb\jobs\TestJob;
  11. use crmeb\repositories\ShortLetterRepositories;
  12. use crmeb\services\blockchain\BlockChianService;
  13. use crmeb\services\CacheService;
  14. use crmeb\services\UtilService;
  15. use think\facade\Cache;
  16. use think\exception\ValidateException;
  17. use think\facade\Config;
  18. use think\facade\Db;
  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 \think\db\exception\DataNotFoundException
  32. * @throws \think\db\exception\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. $user['last_time'] = time();
  53. $user->save();
  54. event('UserLogin', [$user, $token]);
  55. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  56. } else
  57. return app('json')->fail('登录失败');
  58. }
  59. /**
  60. * 退出登录
  61. * @param Request $request
  62. */
  63. public function logout(Request $request)
  64. {
  65. $request->tokenData()->delete();
  66. return app('json')->success('成功');
  67. }
  68. public function verifyCode()
  69. {
  70. $unique = password_hash(uniqid(true), PASSWORD_BCRYPT);
  71. Cache::set('sms.key.' . $unique, 0, 300);
  72. return app('json')->success(['key' => $unique]);
  73. }
  74. public function captcha(Request $request)
  75. {
  76. ob_clean();
  77. $rep = captcha();
  78. $key = app('session')->get('captcha.key');
  79. $uni = $request->get('key');
  80. if ($uni)
  81. Cache::set('sms.key.cap.' . $uni, $key, 300);
  82. return $rep;
  83. }
  84. /**
  85. * 验证验证码是否正确
  86. *
  87. * @param $uni
  88. * @param string $code
  89. * @return bool
  90. * @throws \Psr\SimpleCache\InvalidArgumentException
  91. */
  92. protected function checkCaptcha($uni, string $code): bool
  93. {
  94. $cacheName = 'sms.key.cap.' . $uni;
  95. if (!Cache::has($cacheName)) {
  96. return false;
  97. }
  98. $key = Cache::get($cacheName);
  99. $code = mb_strtolower($code, 'UTF-8');
  100. $res = password_verify($code, $key);
  101. if ($res) {
  102. Cache::delete($cacheName);
  103. }
  104. return $res;
  105. }
  106. /**
  107. * 验证码发送
  108. * @param Request $request
  109. * @return mixed
  110. */
  111. public function verify(Request $request)
  112. {
  113. list($phone, $type, $key, $code) = UtilService::postMore([['phone', 0], ['type', ''], ['key', ''], ['code', '']], $request, true);
  114. $temp = function ($item) {
  115. switch ($item) {
  116. case "register":
  117. return 'REGISTER';
  118. case "login":
  119. return 'LOGIN';
  120. case "reset":
  121. return 'RESET';
  122. case "reset_2":
  123. return 'RESET_2';
  124. case "trade":
  125. return 'TRADE';
  126. default:
  127. return 'DEFAULT';
  128. }
  129. };
  130. // $keyName = 'sms.key.' . $key;
  131. $nowKey = 'sms.' . date('YmdHi');
  132. //
  133. // if (!Cache::has($keyName))
  134. // return app('json')->make(401, '发送验证码失败');
  135. //
  136. // if (($num = Cache::get($keyName)) > 2) {
  137. // if (!$code)
  138. // return app('json')->make(402, '请输入验证码');
  139. //
  140. // if (!$this->checkCaptcha($key, $code))
  141. // return app('json')->fail('验证码输入有误');
  142. // }
  143. $total = 1;
  144. if ($has = Cache::has($nowKey)) {
  145. $total = Cache::get($nowKey);
  146. if ($total > Config::get('sms.maxMinuteCount', 20))
  147. return app('json')->success('已发送');
  148. }
  149. try {
  150. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  151. } catch (ValidateException $e) {
  152. return app('json')->fail($e->getError());
  153. }
  154. if (User::checkPhone($phone) && $type == 'register') return app('json')->fail('手机号已注册');
  155. if (!User::checkPhone($phone) && $type == 'login') return app('json')->fail('账号不存在!');
  156. $default = Config::get('sms.default', 'yunxin');
  157. $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
  158. $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
  159. $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
  160. $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
  161. // if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
  162. // return app('json')->fail('您今日发送得短信次数已经达到上限');
  163. // }
  164. if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
  165. return app('json')->fail('此IP今日发送次数已经达到上限');
  166. }
  167. $time = 300;
  168. // if (CacheService::get('code_' . $phone))
  169. // return app('json')->fail($time . '秒内有效');
  170. $code = rand(100000, 999999);
  171. $data['code'] = $code;
  172. $res = self::NewSmsSend($phone, $data, $temp($type));
  173. // $res = ShortLetterRepositories::send(true, $phone, $data, 'VERIFICATION_CODE');
  174. if ($res !== true)
  175. return app('json')->fail('短信平台验证码发送失败' . $res);
  176. CacheService::set('code_' . $phone, $code, $time);
  177. // Cache::set($keyName, $num + 1, 300);
  178. // Cache::set($nowKey, $total, 61);
  179. return app('json')->success('短信验证发送成功,有效期5分钟');
  180. }
  181. /**
  182. * 发送短信
  183. * @param string $phone 手机号码
  184. * @param array $data 模板替换内容
  185. * @param string $template 模板编号
  186. * @return bool|string
  187. * @throws DataNotFoundException
  188. * @throws ModelNotFoundException
  189. */
  190. public static function NewSmsSend(string $phone, array $data, string $template)
  191. {
  192. try {
  193. $res = ZjSMSServerService::send($phone, $data);
  194. // var_dump($res);
  195. // exit;
  196. if ($res['status'] != '200') {
  197. return $res['msg'];
  198. } else {
  199. SmsRecord::sendRecord($phone, $data['code'], $template, '');
  200. }
  201. return true;
  202. } catch (Exception $exception) {
  203. // Log::info($exception->getMessage());
  204. return $exception->getMessage();
  205. }
  206. }
  207. /**
  208. * H5注册新用户
  209. * @param Request $request
  210. * @return mixed
  211. */
  212. public function register(Request $request)
  213. {
  214. list($account, $captcha, $password, $spread, $payment_pas) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['spread', 0], ['payment_pas']], $request, true);
  215. try {
  216. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'payment_pas' => $payment_pas]);
  217. } catch (ValidateException $e) {
  218. return app('json')->fail($e->getError());
  219. }
  220. if (!$spread) return app('json')->fail('请填写邀请码');
  221. if (!User::where('uid', $spread)->find()) return app('json')->fail('邀请码用户不存在');
  222. $verifyCode = CacheService::get('code_' . $account);
  223. if (!$verifyCode)
  224. return app('json')->fail('请先获取验证码');
  225. $verifyCode = substr($verifyCode, 0, 6);
  226. if ($verifyCode != $captcha)
  227. return app('json')->fail('验证码错误');
  228. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  229. return app('json')->fail('密码必须是在6到16位之间');
  230. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  231. $registerStatus = User::register($account, $password, $spread, $payment_pas);
  232. if ($registerStatus) return app('json')->success('注册成功');
  233. return app('json')->fail(User::getErrorInfo('注册失败'));
  234. }
  235. /**
  236. * 密码修改
  237. * @param Request $request
  238. * @return mixed
  239. */
  240. public function reset(Request $request)
  241. {
  242. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  243. try {
  244. validate(RestValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  245. } catch (ValidateException $e) {
  246. return app('json')->fail($e->getError());
  247. }
  248. $verifyCode = CacheService::get('code_' . $account);
  249. if (!$verifyCode)
  250. return app('json')->fail('请先获取验证码');
  251. $verifyCode = substr($verifyCode, 0, 6);
  252. if ($verifyCode != $captcha)
  253. return app('json')->fail('验证码错误');
  254. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  255. return app('json')->fail('密码必须是在6到16位之间');
  256. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  257. $resetStatus = User::reset($account, $password);
  258. if ($resetStatus) return app('json')->success('修改成功');
  259. return app('json')->fail(User::getErrorInfo('修改失败'));
  260. }
  261. /**
  262. * 手机号登录
  263. * @param Request $request
  264. * @return mixed
  265. * @throws \think\db\exception\DataNotFoundException
  266. * @throws \think\db\exception\ModelNotFoundException
  267. * @throws \think\exception\DbException
  268. */
  269. public function mobile(Request $request)
  270. {
  271. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  272. //验证手机号
  273. try {
  274. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  275. } catch (ValidateException $e) {
  276. return app('json')->fail($e->getError());
  277. }
  278. //验证验证码
  279. $verifyCode = CacheService::get('code_' . $phone);
  280. if (!$verifyCode)
  281. return app('json')->fail('请先获取验证码');
  282. $verifyCode = substr($verifyCode, 0, 6);
  283. if ($verifyCode != $captcha)
  284. return app('json')->fail('验证码错误');
  285. //数据库查询
  286. $user = User::where('account', $phone)->find();
  287. if (!$user)
  288. return app('json')->fail('用户不存在');
  289. if (!$user->status)
  290. return app('json')->fail('已被禁止,请联系管理员');
  291. // 设置推广关系
  292. User::setSpread($spread, $user->uid);
  293. $token = UserToken::createToken($user, 'user');
  294. if ($token) {
  295. event('UserLogin', [$user, $token]);
  296. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  297. } else
  298. return app('json')->fail('登录失败');
  299. }
  300. /**
  301. * H5切换登陆
  302. * @param Request $request
  303. * @return mixed
  304. * @throws \think\db\exception\DataNotFoundException
  305. * @throws \think\db\exception\ModelNotFoundException
  306. * @throws \think\exception\DbException
  307. */
  308. public function switch_h5(Request $request)
  309. {
  310. $from = $request->post('from', 'wechat');
  311. $user = $request->user();
  312. if ($from === 'h5') {
  313. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  314. $user->login_type = 'wechat';
  315. $user->save();
  316. } else {
  317. //数据库查询
  318. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  319. if (!$user)
  320. return app('json')->fail('H5用户不存在,无法切换');
  321. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  322. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  323. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  324. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  325. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  326. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  327. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  328. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  329. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  330. switch ($from) {
  331. case 'wechat':
  332. if (!$wechatH5UserInfo->openid)
  333. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  334. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  335. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  336. break;
  337. case 'routine':
  338. if (!$wechatH5UserInfo->routine_openid)
  339. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  340. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  341. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  342. break;
  343. }
  344. $wechatH5UserInfo->save();
  345. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  346. }
  347. $token = UserToken::createToken($user, 'user');
  348. if ($token) {
  349. event('UserLogin', [$user, $token]);
  350. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  351. } else
  352. return app('json')->fail('登录失败');
  353. }
  354. /**
  355. * 绑定手机号
  356. * @param Request $request
  357. * @return mixed
  358. * @throws \think\db\exception\DataNotFoundException
  359. * @throws \think\db\exception\ModelNotFoundException
  360. * @throws \think\exception\DbException
  361. */
  362. public function binding_phone(Request $request)
  363. {
  364. list($phone, $captcha, $step) = UtilService::postMore([
  365. ['phone', ''],
  366. ['captcha', ''],
  367. ['step', 0]
  368. ], $request, true);
  369. //验证手机号
  370. try {
  371. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  372. } catch (ValidateException $e) {
  373. return app('json')->fail($e->getError());
  374. }
  375. //验证验证码
  376. $verifyCode = CacheService::get('code_' . $phone);
  377. if (!$verifyCode)
  378. return app('json')->fail('请先获取验证码');
  379. $verifyCode = substr($verifyCode, 0, 6);
  380. if ($verifyCode != $captcha)
  381. return app('json')->fail('验证码错误');
  382. $userInfo = User::where('uid', $request->uid())->find();
  383. $new_whchat = WechatUser::where('uid', $userInfo['uid'])->find();
  384. $userOld = User::where('phone', $phone)->find();
  385. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  386. if ($userOld and $new_whchat['routine_openid']){
  387. $old_whchat = WechatUser::where('uid', $userOld['uid'])->find();
  388. $old_whchat['unionid'] = $new_whchat['unionid'];
  389. $old_whchat['routine_openid'] = $new_whchat['routine_openid'];
  390. $userOld['phone'] = $phone;
  391. $old_whchat->save();
  392. $userOld->save();
  393. $userInfo->delete();
  394. $new_whchat->delete();
  395. $token = UserToken::createToken($userOld, 'h5');
  396. if ($token) {
  397. event('UserLogin', [$userOld, $token]);
  398. return app('json')->successful('登陆成功!', [
  399. 'token' => $token->token,
  400. 'userInfo' => $userOld,
  401. 'expires_time' => strtotime($token->expires_time),
  402. 'cache_key' => ''
  403. ]);
  404. } else
  405. return app('json')->fail('获取用户访问token失败!');
  406. }else{
  407. $userPhone = $userInfo->phone;
  408. if (!$userInfo) return app('json')->fail('用户不存在');
  409. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  410. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  411. return app('json')->success('此手机已经绑定,无法多次绑定!');
  412. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  413. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  414. $userInfo->phone = $phone;
  415. } else {
  416. $userInfo->account = $phone;
  417. $userInfo->phone = $phone;
  418. }
  419. if ($userInfo->save() || $userPhone == $phone)
  420. return app('json')->success('绑定成功');
  421. else
  422. return app('json')->fail('绑定失败');
  423. }
  424. }
  425. public function brc()
  426. {
  427. $data[] = 'TB5UtaMMv9apgcKxxYBLkjqmixab9N7EsR';
  428. return app('json')->success($data);
  429. }
  430. /**
  431. * 小程序授权登录
  432. * @param Request $request
  433. * @return mixed
  434. * @throws \Psr\SimpleCache\InvalidArgumentException
  435. * @throws \think\db\exception\DataNotFoundException
  436. * @throws \think\db\exception\ModelNotFoundException
  437. * @throws \think\exception\DbException
  438. */
  439. public function app_auth(Request $request)
  440. {
  441. Db::query("DELETE from eb_wechat_user where uid not in (select uid from eb_user)");
  442. $cache_key = '';
  443. $userInfo = UtilService::postMore([
  444. ['openId', ''],
  445. ['nickName', ''],
  446. ['city', ''],
  447. ['province', ''],
  448. ['country', ''],
  449. ['avatarUrl', ''],
  450. ['gender', ''],
  451. ['unionId', ''],
  452. ], $request);
  453. $data = UtilService::postMore([
  454. ['spread_spid', 0],
  455. ]);//获取前台传的code
  456. if (!isset($userInfo['openId'])) return app('json')->fail('openid获取失败');
  457. if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';
  458. $userInfo['spid'] = $data['spread_spid'];
  459. $uid = WechatUser::appOauth($userInfo);
  460. $userInfo = User::where('uid', $uid)->find();
  461. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  462. $token = UserToken::createToken($userInfo, 'h5');
  463. else
  464. $token = UserToken::createToken($userInfo, 'h5');
  465. if ($token) {
  466. event('UserLogin', [$userInfo, $token]);
  467. return app('json')->successful('登陆成功!', [
  468. 'token' => $token->token,
  469. 'userInfo' => $userInfo,
  470. 'expires_time' => strtotime($token->expires_time),
  471. 'cache_key' => $cache_key
  472. ]);
  473. } else
  474. return app('json')->fail('获取用户访问token失败!');
  475. }
  476. }