AuthController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. $registerStatus = User::register($account, $password, $spread, $payment_pas);
  228. if ($registerStatus) return app('json')->success('注册成功');
  229. return app('json')->fail(User::getErrorInfo('注册失败'));
  230. }
  231. /**
  232. * 密码修改
  233. * @param Request $request
  234. * @return mixed
  235. */
  236. public function reset(Request $request)
  237. {
  238. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  239. try {
  240. validate(RestValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  241. } catch (ValidateException $e) {
  242. return app('json')->fail($e->getError());
  243. }
  244. $verifyCode = CacheService::get('code_' . $account);
  245. if (!$verifyCode)
  246. return app('json')->fail('请先获取验证码');
  247. $verifyCode = substr($verifyCode, 0, 6);
  248. if ($verifyCode != $captcha)
  249. return app('json')->fail('验证码错误');
  250. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  251. return app('json')->fail('密码必须是在6到16位之间');
  252. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  253. $resetStatus = User::reset($account, $password);
  254. if ($resetStatus) return app('json')->success('修改成功');
  255. return app('json')->fail(User::getErrorInfo('修改失败'));
  256. }
  257. /**
  258. * 手机号登录
  259. * @param Request $request
  260. * @return mixed
  261. * @throws \think\db\exception\DataNotFoundException
  262. * @throws \think\db\exception\ModelNotFoundException
  263. * @throws \think\exception\DbException
  264. */
  265. public function mobile(Request $request)
  266. {
  267. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  268. //验证手机号
  269. try {
  270. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  271. } catch (ValidateException $e) {
  272. return app('json')->fail($e->getError());
  273. }
  274. //验证验证码
  275. $verifyCode = CacheService::get('code_' . $phone);
  276. if (!$verifyCode)
  277. return app('json')->fail('请先获取验证码');
  278. $verifyCode = substr($verifyCode, 0, 6);
  279. if ($verifyCode != $captcha)
  280. return app('json')->fail('验证码错误');
  281. //数据库查询
  282. $user = User::where('account', $phone)->find();
  283. if (!$user)
  284. return app('json')->fail('用户不存在');
  285. if (!$user->status)
  286. return app('json')->fail('已被禁止,请联系管理员');
  287. // 设置推广关系
  288. User::setSpread($spread, $user->uid);
  289. $token = UserToken::createToken($user, 'user');
  290. if ($token) {
  291. event('UserLogin', [$user, $token]);
  292. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  293. } else
  294. return app('json')->fail('登录失败');
  295. }
  296. /**
  297. * H5切换登陆
  298. * @param Request $request
  299. * @return mixed
  300. * @throws \think\db\exception\DataNotFoundException
  301. * @throws \think\db\exception\ModelNotFoundException
  302. * @throws \think\exception\DbException
  303. */
  304. public function switch_h5(Request $request)
  305. {
  306. $from = $request->post('from', 'wechat');
  307. $user = $request->user();
  308. if ($from === 'h5') {
  309. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  310. $user->login_type = 'wechat';
  311. $user->save();
  312. } else {
  313. //数据库查询
  314. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  315. if (!$user)
  316. return app('json')->fail('H5用户不存在,无法切换');
  317. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  318. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  319. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  320. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  321. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  322. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  323. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  324. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  325. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  326. switch ($from) {
  327. case 'wechat':
  328. if (!$wechatH5UserInfo->openid)
  329. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  330. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  331. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  332. break;
  333. case 'routine':
  334. if (!$wechatH5UserInfo->routine_openid)
  335. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  336. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  337. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  338. break;
  339. }
  340. $wechatH5UserInfo->save();
  341. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  342. }
  343. $token = UserToken::createToken($user, 'user');
  344. if ($token) {
  345. event('UserLogin', [$user, $token]);
  346. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  347. } else
  348. return app('json')->fail('登录失败');
  349. }
  350. /**
  351. * 绑定手机号
  352. * @param Request $request
  353. * @return mixed
  354. * @throws \think\db\exception\DataNotFoundException
  355. * @throws \think\db\exception\ModelNotFoundException
  356. * @throws \think\exception\DbException
  357. */
  358. public function binding_phone(Request $request)
  359. {
  360. list($phone, $captcha, $step) = UtilService::postMore([
  361. ['phone', ''],
  362. ['captcha', ''],
  363. ['step', 0]
  364. ], $request, true);
  365. //验证手机号
  366. try {
  367. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  368. } catch (ValidateException $e) {
  369. return app('json')->fail($e->getError());
  370. }
  371. //验证验证码
  372. $verifyCode = CacheService::get('code_' . $phone);
  373. if (!$verifyCode)
  374. return app('json')->fail('请先获取验证码');
  375. $verifyCode = substr($verifyCode, 0, 6);
  376. if ($verifyCode != $captcha)
  377. return app('json')->fail('验证码错误');
  378. $userInfo = User::where('uid', $request->uid())->find();
  379. $new_whchat = WechatUser::where('uid', $userInfo['uid'])->find();
  380. $userOld = User::where('phone', $phone)->find();
  381. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  382. if ($userOld and $new_whchat['routine_openid']){
  383. $old_whchat = WechatUser::where('uid', $userOld['uid'])->find();
  384. $old_whchat['unionid'] = $new_whchat['unionid'];
  385. $old_whchat['routine_openid'] = $new_whchat['routine_openid'];
  386. $userOld['phone'] = $phone;
  387. $old_whchat->save();
  388. $userOld->save();
  389. $userInfo->delete();
  390. $new_whchat->delete();
  391. $token = UserToken::createToken($userOld, 'h5');
  392. if ($token) {
  393. event('UserLogin', [$userOld, $token]);
  394. return app('json')->successful('登陆成功!', [
  395. 'token' => $token->token,
  396. 'userInfo' => $userOld,
  397. 'expires_time' => strtotime($token->expires_time),
  398. 'cache_key' => ''
  399. ]);
  400. } else
  401. return app('json')->fail('获取用户访问token失败!');
  402. }else{
  403. $userPhone = $userInfo->phone;
  404. if (!$userInfo) return app('json')->fail('用户不存在');
  405. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  406. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  407. return app('json')->success('此手机已经绑定,无法多次绑定!');
  408. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  409. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  410. $userInfo->phone = $phone;
  411. } else {
  412. $userInfo->account = $phone;
  413. $userInfo->phone = $phone;
  414. }
  415. if ($userInfo->save() || $userPhone == $phone)
  416. return app('json')->success('绑定成功');
  417. else
  418. return app('json')->fail('绑定失败');
  419. }
  420. }
  421. public function brc()
  422. {
  423. $data[] = 'TB5UtaMMv9apgcKxxYBLkjqmixab9N7EsR';
  424. return app('json')->success($data);
  425. }
  426. /**
  427. * 小程序授权登录
  428. * @param Request $request
  429. * @return mixed
  430. * @throws \Psr\SimpleCache\InvalidArgumentException
  431. * @throws \think\db\exception\DataNotFoundException
  432. * @throws \think\db\exception\ModelNotFoundException
  433. * @throws \think\exception\DbException
  434. */
  435. public function app_auth(Request $request)
  436. {
  437. Db::query("DELETE from eb_wechat_user where uid not in (select uid from eb_user)");
  438. $cache_key = '';
  439. $userInfo = UtilService::postMore([
  440. ['openId', ''],
  441. ['nickName', ''],
  442. ['city', ''],
  443. ['province', ''],
  444. ['country', ''],
  445. ['avatarUrl', ''],
  446. ['gender', ''],
  447. ['unionId', ''],
  448. ], $request);
  449. $data = UtilService::postMore([
  450. ['spread_spid', 0],
  451. ]);//获取前台传的code
  452. if (!isset($userInfo['openId'])) return app('json')->fail('openid获取失败');
  453. if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';
  454. $userInfo['spid'] = $data['spread_spid'];
  455. $uid = WechatUser::appOauth($userInfo);
  456. $userInfo = User::where('uid', $uid)->find();
  457. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  458. $token = UserToken::createToken($userInfo, 'h5');
  459. else
  460. $token = UserToken::createToken($userInfo, 'h5');
  461. if ($token) {
  462. event('UserLogin', [$userInfo, $token]);
  463. return app('json')->successful('登陆成功!', [
  464. 'token' => $token->token,
  465. 'userInfo' => $userInfo,
  466. 'expires_time' => strtotime($token->expires_time),
  467. 'cache_key' => $cache_key
  468. ]);
  469. } else
  470. return app('json')->fail('获取用户访问token失败!');
  471. }
  472. }