AuthController.php 20 KB

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