AuthController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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\redis\SystemCarousel;
  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\CacheService;
  13. use crmeb\services\UtilService;
  14. use think\facade\Cache;
  15. use think\exception\ValidateException;
  16. use think\facade\Config;
  17. use think\facade\Queue;
  18. use think\facade\Session;
  19. /**微信小程序授权类
  20. * Class AuthController
  21. * @package app\api\controller
  22. */
  23. class AuthController
  24. {
  25. /**
  26. * @api {post} /login H5账号登陆
  27. * @apiName Login
  28. * @apiGroup Login
  29. *
  30. * @apiBody {string} account 輸入帐号.
  31. * @apiBody {string} password 輸入密碼(明文).
  32. * @apiBody {int} [spread] 上级 UID
  33. *
  34. * @apiSuccessExample Success-Response:
  35. * HTTP/1.1 200 OK
  36. * {
  37. * "token": "xxxcvc",
  38. * "expires_time": "2000-11-01 08:09:10"
  39. * }
  40. *
  41. * @apiErrorExample {json} Error-Response:
  42. * {
  43. * "status":400,
  44. * "msg": ["账号或密码错误", "已被禁止,请联系管理员","登录失败"]
  45. * }
  46. */
  47. public function login(Request $request)
  48. {
  49. $user = User::where('account', $request->param('account'))->find();
  50. if ($user) {
  51. if ($user->pwd !== md5($request->param('password')))
  52. return app('json')->fail('账号或密码错误');
  53. if ($user->pwd === md5(123456))
  54. return app('json')->fail('请修改您的初始密码,再尝试登陆!');
  55. } else {
  56. return app('json')->fail('账号或密码错误');
  57. }
  58. if (!$user['status'])
  59. return app('json')->fail('已被禁止,请联系管理员');
  60. // 设置推广关系
  61. User::setSpread(intval($request->param('spread')), $user->uid);
  62. $token = UserToken::createToken($user, 'user');
  63. if ($token) {
  64. event('UserLogin', [$user, $token]);
  65. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  66. } else
  67. return app('json')->fail('登录失败');
  68. }
  69. /**
  70. * @api {get} /logout 退出登录
  71. * @apiName Logout
  72. * @apiGroup User
  73. *
  74. * @apiSuccessExample Success-Response:
  75. * HTTP/1.1 200 OK
  76. * {
  77. * "status": 200
  78. * "msg": "成功"
  79. * }
  80. *
  81. * @apiErrorExample Error-Response:
  82. * {
  83. * "status": 410000,
  84. * "msg": "请登录"
  85. * }
  86. */
  87. public function logout(Request $request)
  88. {
  89. $request->tokenData()->delete();
  90. return app('json')->success('成功');
  91. }
  92. /**
  93. * @api {get} /verify_code 获取发短信的 KEY
  94. * @apiName GetVerificationCode
  95. * @apiGroup Login
  96. *
  97. * @apiSuccessExample Success-Response:
  98. * {
  99. * "status": 200,
  100. * "key": "dfsdfdsfdg"
  101. * }
  102. *
  103. * @apiDeprecated 先获取 key 再发短信没用,并不能防止客户端脚本。起码要先获取验证码,用户输入验证码再发短信。
  104. * 因为现在短信平台都有防攻击机制,这方面的功能暂时不做。
  105. */
  106. public function verifyCode()
  107. {
  108. $unique = password_hash(uniqid(true), PASSWORD_BCRYPT);
  109. Cache::set('sms.key.' . $unique, 0, 300);
  110. return app('json')->success(['key' => $unique]);
  111. }
  112. /**
  113. * @api {get} /sms_captcha 获取发送短信的验证码
  114. * @apiName GetSmsCaptcha
  115. * @apiGroup Login
  116. *
  117. * @apiSuccessExample Success-Response:
  118. * 二进制图片信息
  119. *
  120. * @apiDeprecated: 不再返回二进制信息,对于简单的二维码,直接返回 base64 编码的图片内容
  121. */
  122. public function captcha(Request $request)
  123. {
  124. ob_clean();
  125. $rep = captcha();
  126. $key = app('session')->get('captcha.key');
  127. $uni = $request->get('key');
  128. if ($uni)
  129. Cache::set('sms.key.cap.' . $uni, $key, 300);
  130. return $rep;
  131. }
  132. /**
  133. * 验证验证码是否正确
  134. *
  135. * @param $uni
  136. * @param string $code
  137. * @return bool
  138. * @throws \Psr\SimpleCache\InvalidArgumentException
  139. */
  140. protected function checkCaptcha($uni, string $code): bool
  141. {
  142. $cacheName = 'sms.key.cap.' . $uni;
  143. if (!Cache::has($cacheName)) {
  144. return false;
  145. }
  146. $key = Cache::get($cacheName);
  147. $code = mb_strtolower($code, 'UTF-8');
  148. $res = password_verify($code, $key);
  149. if ($res) {
  150. Cache::delete($cacheName);
  151. }
  152. return $res;
  153. }
  154. /**
  155. * @api {post} /register/verify 验证码发送SMS
  156. * @apiName PostRegisterVerify
  157. * @apiGroup Login
  158. *
  159. * @apiBody {string} phone 手机号
  160. * @apiBody {string="register","login"} type
  161. * @apiBody {string} code 用户识别验证码后的值
  162. * @apiBody {string} key 通过 /verify_code 得到的 KEY
  163. *
  164. * @apiSuccessExample:
  165. * {
  166. * "status": 200,
  167. * "msg": "发送成功"
  168. * }
  169. * @apiErrorExample:
  170. * {
  171. * "status": 400,
  172. * "msg": "error msg"
  173. * }
  174. */
  175. public function verify(Request $request)
  176. {
  177. list($phone, $type, $key, $code) = UtilService::postMore([
  178. ['phone', ''],
  179. ['type', ''],
  180. ['key', ''],
  181. ['code', '']], $request, true);
  182. $keyName = 'sms.key.' . $key;
  183. $nowKey = 'sms.' . date('YmdHi');
  184. if (!Cache::has($keyName))
  185. return app('json')->make(401, '发送验证码失败');
  186. if (($num = Cache::get($keyName)) > 2) {
  187. if (!$code)
  188. return app('json')->make(402, '请输入验证码');
  189. if (!$this->checkCaptcha($key, $code))
  190. return app('json')->fail('验证码输入有误');
  191. }
  192. $total = 1;
  193. if ($has = Cache::has($nowKey)) {
  194. $total = Cache::get($nowKey);
  195. if ($total > Config::get('sms.maxMinuteCount', 20))
  196. return app('json')->success('已发送');
  197. }
  198. try {
  199. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  200. } catch (ValidateException $e) {
  201. return app('json')->fail($e->getError());
  202. }
  203. if (User::checkPhone($phone) && $type == 'register') return app('json')->fail('手机号已注册');
  204. if (!User::checkPhone($phone) && $type == 'login') return app('json')->fail('账号不存在!');
  205. $default = Config::get('sms.default', 'yunxin');
  206. $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
  207. $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
  208. $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
  209. $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
  210. if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
  211. return app('json')->fail('您今日发送得短信次数已经达到上限');
  212. }
  213. if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
  214. return app('json')->fail('此IP今日发送次数已经达到上限');
  215. }
  216. $time = 60;
  217. if (CacheService::get('code_' . $phone))
  218. return app('json')->fail($time . '秒内有效');
  219. $code = rand(100000, 999999);
  220. $data['code'] = $code;
  221. $res = ShortLetterRepositories::send(true, $phone, $data, 'VERIFICATION_CODE');
  222. if ($res !== true)
  223. return app('json')->fail('短信平台验证码发送失败' . $res);
  224. CacheService::set('code_' . $phone, $code, $time);
  225. Cache::set($keyName, $num + 1, 300);
  226. Cache::set($nowKey, $total, 61);
  227. return app('json')->success('发送成功');
  228. }
  229. /**
  230. * @api {post} /register H5注册新用户
  231. * @apiName PostRegister
  232. * @apiGroup Login
  233. *
  234. * @apiBody {string} account 帐号,手机号
  235. * @apiBody {string} captcha 短信验证码
  236. * @apiBody {string{6,16}} password 密码
  237. * @apiBody {int} [spread] 推广上级
  238. *
  239. * @apiSuccessExample:
  240. * {
  241. * "status": 200,
  242. * "msg": "注册成功"
  243. * }
  244. * @apiErrorExample:
  245. * {
  246. * "status": 400,
  247. * "msg": "error msg"
  248. * }
  249. */
  250. public function register(Request $request)
  251. {
  252. list($account, $captcha, $password, $spread) = UtilService::postMore([
  253. ['account', ''],
  254. ['captcha', ''],
  255. ['password', ''],
  256. ['spread', 0]], $request, true);
  257. try {
  258. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  259. } catch (ValidateException $e) {
  260. return app('json')->fail($e->getError());
  261. }
  262. $verifyCode = CacheService::get('code_' . $account);
  263. if (!$verifyCode)
  264. return app('json')->fail('请先获取验证码');
  265. $verifyCode = substr($verifyCode, 0, 6);
  266. if ($verifyCode != $captcha)
  267. return app('json')->fail('验证码错误');
  268. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  269. return app('json')->fail('密码必须是在6到16位之间');
  270. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  271. $registerStatus = User::register($account, $password, $spread);
  272. if ($registerStatus) return app('json')->success('注册成功');
  273. return app('json')->fail(User::getErrorInfo('注册失败'));
  274. }
  275. /**
  276. * @api {post} /register/reset 重置密码
  277. * @apiName PostRegisterReset
  278. * @apiGroup Login
  279. *
  280. * @apiBody {string} account 帐号手机号
  281. * @apiBody {string} captcha 短信验证码
  282. * @apiBody {string} password 新密码
  283. *
  284. * @apiSuccessExample:
  285. * {
  286. * "status": 200,
  287. * "msg": "修改成功"
  288. * }
  289. * @apiErrorExample:
  290. * {
  291. * "status": 400,
  292. * "msg": "error msg"
  293. * }
  294. */
  295. public function reset(Request $request)
  296. {
  297. list($account, $captcha, $password) = UtilService::postMore([
  298. ['account', ''],
  299. ['captcha', ''],
  300. ['password', '']], $request, true);
  301. try {
  302. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  303. } catch (ValidateException $e) {
  304. return app('json')->fail($e->getError());
  305. }
  306. $verifyCode = CacheService::get('code_' . $account);
  307. if (!$verifyCode)
  308. return app('json')->fail('请先获取验证码');
  309. $verifyCode = substr($verifyCode, 0, 6);
  310. if ($verifyCode != $captcha)
  311. return app('json')->fail('验证码错误');
  312. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  313. return app('json')->fail('密码必须是在6到16位之间');
  314. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  315. $resetStatus = User::reset($account, $password);
  316. if ($resetStatus) return app('json')->success('修改成功');
  317. return app('json')->fail(User::getErrorInfo('修改失败'));
  318. }
  319. /**
  320. * @api {post} /login/mobile 手机号登录
  321. * @apiName PostLoginMobile
  322. * @apiGroup Login
  323. *
  324. * @apiBody {string} phone: 手机号
  325. * @apiBody {string} captcha: 验证码
  326. * @apiBody {int} [spread]: 推广上级
  327. *
  328. * @apiSuccessExample Success-Response:
  329. * {
  330. * "token": "xxdfgfgfg",
  331. * "expires_time": "2020-01-01 10:11:23"
  332. * }
  333. *
  334. * @apiErrorExample Error-Response:
  335. * {
  336. * "status": 400,
  337. * "msg": "error msg"
  338. * }
  339. */
  340. public function mobile(Request $request)
  341. {
  342. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  343. //验证手机号
  344. try {
  345. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  346. } catch (ValidateException $e) {
  347. return app('json')->fail($e->getError());
  348. }
  349. //验证验证码
  350. $verifyCode = CacheService::get('code_' . $phone);
  351. if (!$verifyCode)
  352. return app('json')->fail('请先获取验证码');
  353. $verifyCode = substr($verifyCode, 0, 6);
  354. if ($verifyCode != $captcha)
  355. return app('json')->fail('验证码错误');
  356. //数据库查询
  357. $user = User::where('account', $phone)->find();
  358. if (!$user)
  359. return app('json')->fail('用户不存在');
  360. if (!$user->status)
  361. return app('json')->fail('已被禁止,请联系管理员');
  362. // 设置推广关系
  363. User::setSpread($spread, $user->uid);
  364. $token = UserToken::createToken($user, 'user');
  365. if ($token) {
  366. event('UserLogin', [$user, $token]);
  367. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  368. } else
  369. return app('json')->fail('登录失败');
  370. }
  371. /**
  372. * @api {post} /switch_h5 H5切换帐号登陆
  373. * @apiName SwitchH5
  374. * @apiGroup User
  375. *
  376. * @apiBody {string} from 客户端类型 h5
  377. *
  378. * @apiSuccessExample Success-Response:
  379. * {
  380. * "userinfo": {
  381. * },
  382. * "token": "xxdfdg",
  383. * "expires_time": ""
  384. * }
  385. * @apiErrorExample Error-Response:
  386. * {
  387. * "status": 400,
  388. * "msg": "error msg"
  389. * }
  390. *
  391. * @apiDeprecated 不用切换帐号,切啥切?退出重新登录
  392. */
  393. public function switch_h5(Request $request)
  394. {
  395. $from = $request->post('from', 'wechat');
  396. $user = $request->user();
  397. if ($from === 'h5') {
  398. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  399. $user->login_type = 'wechat';
  400. $user->save();
  401. } else {
  402. //数据库查询
  403. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  404. if (!$user)
  405. return app('json')->fail('H5用户不存在,无法切换');
  406. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  407. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  408. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  409. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  410. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  411. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  412. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  413. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  414. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  415. switch ($from) {
  416. case 'wechat':
  417. if (!$wechatH5UserInfo->openid)
  418. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  419. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  420. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  421. break;
  422. case 'routine':
  423. if (!$wechatH5UserInfo->routine_openid)
  424. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  425. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  426. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  427. break;
  428. }
  429. $wechatH5UserInfo->save();
  430. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  431. }
  432. $token = UserToken::createToken($user, 'user');
  433. if ($token) {
  434. event('UserLogin', [$user, $token]);
  435. //退出上一个账号
  436. $request->tokenData()->delete();
  437. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  438. } else
  439. return app('json')->fail('登录失败');
  440. }
  441. /**
  442. * @api {post} /binding 绑定手机号
  443. * @apiName PostBinding
  444. * @apiGroup User
  445. *
  446. * @apiBody {string} phone 绑定的手机号
  447. * @apiBody {string} captcha 验证码
  448. * @apiBody {int} [step] 已绑定是否支持重复绑定 1 支持 0 不支持
  449. *
  450. * @apiSuccessExample:
  451. * {
  452. * "status": 200
  453. * }
  454. *
  455. * @apiErrorExample:
  456. * {
  457. * "status": 400,
  458. * "msg": "error msg"
  459. * }
  460. */
  461. public function binding_phone(Request $request)
  462. {
  463. list($phone, $captcha, $step) = UtilService::postMore([
  464. ['phone', ''],
  465. ['captcha', ''],
  466. ['step', 0]
  467. ], $request, true);
  468. //验证手机号
  469. try {
  470. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  471. } catch (ValidateException $e) {
  472. return app('json')->fail($e->getError());
  473. }
  474. //验证验证码
  475. $verifyCode = CacheService::get('code_' . $phone);
  476. if (!$verifyCode)
  477. return app('json')->fail('请先获取验证码');
  478. $verifyCode = substr($verifyCode, 0, 6);
  479. if ($verifyCode != $captcha)
  480. return app('json')->fail('验证码错误');
  481. $userInfo = User::where('uid', $request->uid())->find();
  482. $userPhone = $userInfo->phone;
  483. if (!$userInfo) return app('json')->fail('用户不存在');
  484. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  485. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  486. return app('json')->fail('此手机已经绑定,无法多次绑定!');
  487. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  488. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  489. $userInfo->phone = $phone;
  490. } else {
  491. $userInfo->account = $phone;
  492. $userInfo->phone = $phone;
  493. }
  494. if ($userInfo->save() || $userPhone == $phone)
  495. return app('json')->success('绑定成功');
  496. else
  497. return app('json')->fail('绑定失败');
  498. }
  499. /**
  500. * @api {get} /notifications 不登录模拟推送
  501. * @apiName GetNotifications
  502. * @apiGroup Message
  503. *
  504. * @apiSuccessExample Succeed
  505. * {
  506. * "status": 200,
  507. * "msg": "ok",
  508. * "data": {
  509. * "carousel": [
  510. * {
  511. * "id": 1,
  512. * "info": "text",
  513. * "url": "page/boards",
  514. * "wap_url": "h5 front router",
  515. * "show": '2'
  516. * }
  517. * ]
  518. * }
  519. * }
  520. *
  521. * @apiErrorExample Failed
  522. * {
  523. * "status": 200,
  524. * "msg": "ok",
  525. * "data": {
  526. * "carousel": []
  527. * }
  528. * }
  529. */
  530. public function notifications(Request $request)
  531. {
  532. // 跑马灯
  533. $carousel = SystemCarousel::getFirst(20);
  534. return app('json')->successful(compact('carousel'));
  535. }
  536. }