AuthController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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, $key, $code) = UtilService::postMore([['phone', 0], ['type', ''], ['key', ''], ['code', '']], $request, true);
  109. // $keyName = 'sms.key.' . $key;
  110. $nowKey = 'sms.' . date('YmdHi');
  111. //
  112. // if (!Cache::has($keyName))
  113. // return app('json')->make(401, '发送验证码失败');
  114. //
  115. // if (($num = Cache::get($keyName)) > 2) {
  116. // if (!$code)
  117. // return app('json')->make(402, '请输入验证码');
  118. //
  119. // if (!$this->checkCaptcha($key, $code))
  120. // return app('json')->fail('验证码输入有误');
  121. // }
  122. $total = 1;
  123. if ($has = Cache::has($nowKey)) {
  124. $total = Cache::get($nowKey);
  125. if ($total > Config::get('sms.maxMinuteCount', 20))
  126. return app('json')->success('已发送');
  127. }
  128. try {
  129. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  130. } catch (ValidateException $e) {
  131. return app('json')->fail($e->getError());
  132. }
  133. if (User::checkPhone($phone) && $type == 'register') return app('json')->fail('手机号已注册');
  134. if (!User::checkPhone($phone) && $type == 'login') return app('json')->fail('账号不存在!');
  135. $default = Config::get('sms.default', 'yunxin');
  136. $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
  137. $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
  138. $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
  139. $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
  140. if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
  141. return app('json')->fail('您今日发送得短信次数已经达到上限');
  142. }
  143. if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
  144. return app('json')->fail('此IP今日发送次数已经达到上限');
  145. }
  146. $time = 60;
  147. if (CacheService::get('code_' . $phone))
  148. return app('json')->fail($time . '秒内有效');
  149. $code = rand(100000, 999999);
  150. $data['code'] = $code;
  151. $res = ShortLetterRepositories::Alisend(true, $phone, $data, 'VERIFICATION_CODE');
  152. if ($res !== true)
  153. return app('json')->fail('短信平台验证码发送失败' . $res);
  154. CacheService::set('code_' . $phone, $code, $time);
  155. // Cache::set($keyName, $num + 1, 300);
  156. Cache::set($nowKey, $total, 61);
  157. return app('json')->success('发送成功');
  158. }
  159. /**
  160. * H5注册新用户
  161. * @param Request $request
  162. * @return mixed
  163. */
  164. public function register(Request $request)
  165. {
  166. list($account, $captcha, $password, $spread) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['spread', 0]], $request, true);
  167. try {
  168. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  169. } catch (ValidateException $e) {
  170. return app('json')->fail($e->getError());
  171. }
  172. $verifyCode = CacheService::get('code_' . $account);
  173. if (!$verifyCode)
  174. return app('json')->fail('请先获取验证码');
  175. $verifyCode = substr($verifyCode, 0, 6);
  176. if ($verifyCode != $captcha)
  177. return app('json')->fail('验证码错误');
  178. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  179. return app('json')->fail('密码必须是在6到16位之间');
  180. // if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  181. $registerStatus = User::register($account, $password, $spread);
  182. if ($registerStatus) return app('json')->success('注册成功');
  183. return app('json')->fail(User::getErrorInfo('注册失败'));
  184. }
  185. /**
  186. * 密码修改
  187. * @param Request $request
  188. * @return mixed
  189. */
  190. public function reset(Request $request)
  191. {
  192. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  193. try {
  194. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  195. } catch (ValidateException $e) {
  196. return app('json')->fail($e->getError());
  197. }
  198. $verifyCode = CacheService::get('code_' . $account);
  199. if (!$verifyCode)
  200. return app('json')->fail('请先获取验证码');
  201. $verifyCode = substr($verifyCode, 0, 6);
  202. if ($verifyCode != $captcha)
  203. return app('json')->fail('验证码错误');
  204. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  205. return app('json')->fail('密码必须是在6到16位之间');
  206. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  207. $resetStatus = User::reset($account, $password);
  208. if ($resetStatus) return app('json')->success('修改成功');
  209. return app('json')->fail(User::getErrorInfo('修改失败'));
  210. }
  211. /**
  212. * 手机号登录
  213. * @param Request $request
  214. * @return mixed
  215. * @throws \think\db\exception\DataNotFoundException
  216. * @throws \think\db\exception\ModelNotFoundException
  217. * @throws \think\exception\DbException
  218. */
  219. public function mobile(Request $request)
  220. {
  221. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  222. //验证手机号
  223. try {
  224. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  225. } catch (ValidateException $e) {
  226. return app('json')->fail($e->getError());
  227. }
  228. //验证验证码
  229. $verifyCode = CacheService::get('code_' . $phone);
  230. if (!$verifyCode)
  231. return app('json')->fail('请先获取验证码');
  232. $verifyCode = substr($verifyCode, 0, 6);
  233. if ($verifyCode != $captcha)
  234. return app('json')->fail('验证码错误');
  235. //数据库查询
  236. $user = User::where('account', $phone)->find();
  237. if (!$user)
  238. return app('json')->fail('用户不存在');
  239. if (!$user->status)
  240. return app('json')->fail('已被禁止,请联系管理员');
  241. // 设置推广关系
  242. User::setSpread($spread, $user->uid);
  243. $token = UserToken::createToken($user, 'user');
  244. if ($token) {
  245. event('UserLogin', [$user, $token]);
  246. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  247. } else
  248. return app('json')->fail('登录失败');
  249. }
  250. /**
  251. * H5切换登陆
  252. * @param Request $request
  253. * @return mixed
  254. * @throws \think\db\exception\DataNotFoundException
  255. * @throws \think\db\exception\ModelNotFoundException
  256. * @throws \think\exception\DbException
  257. */
  258. public function switch_h5(Request $request)
  259. {
  260. $from = $request->post('from', 'wechat');
  261. $user = $request->user();
  262. if ($from === 'h5') {
  263. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  264. $user->login_type = 'wechat';
  265. $user->save();
  266. } else {
  267. //数据库查询
  268. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  269. if (!$user)
  270. return app('json')->fail('H5用户不存在,无法切换');
  271. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  272. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  273. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  274. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  275. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  276. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  277. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  278. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  279. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  280. switch ($from) {
  281. case 'wechat':
  282. if (!$wechatH5UserInfo->openid)
  283. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  284. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  285. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  286. break;
  287. case 'routine':
  288. if (!$wechatH5UserInfo->routine_openid)
  289. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  290. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  291. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  292. break;
  293. }
  294. $wechatH5UserInfo->save();
  295. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  296. }
  297. $token = UserToken::createToken($user, 'user');
  298. if ($token) {
  299. event('UserLogin', [$user, $token]);
  300. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  301. } else
  302. return app('json')->fail('登录失败');
  303. }
  304. /**
  305. * 绑定手机号
  306. * @param Request $request
  307. * @return mixed
  308. * @throws \think\db\exception\DataNotFoundException
  309. * @throws \think\db\exception\ModelNotFoundException
  310. * @throws \think\exception\DbException
  311. */
  312. public function binding_phone(Request $request)
  313. {
  314. list($phone, $captcha, $step) = UtilService::postMore([
  315. ['phone', ''],
  316. ['captcha', ''],
  317. ['step', 0]
  318. ], $request, true);
  319. //验证手机号
  320. try {
  321. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  322. } catch (ValidateException $e) {
  323. return app('json')->fail($e->getError());
  324. }
  325. //验证验证码
  326. $verifyCode = CacheService::get('code_' . $phone);
  327. if (!$verifyCode)
  328. return app('json')->fail('请先获取验证码');
  329. $verifyCode = substr($verifyCode, 0, 6);
  330. if ($verifyCode != $captcha)
  331. return app('json')->fail('验证码错误');
  332. $userInfo = User::where('uid', $request->uid())->find();
  333. $userPhone = $userInfo->phone;
  334. if (!$userInfo) return app('json')->fail('用户不存在');
  335. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  336. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  337. return app('json')->success('此手机已经绑定,无法多次绑定!');
  338. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  339. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  340. $userInfo->phone = $phone;
  341. } else {
  342. $userInfo->account = $phone;
  343. $userInfo->phone = $phone;
  344. }
  345. if ($userInfo->save() || $userPhone == $phone)
  346. return app('json')->success('绑定成功');
  347. else
  348. return app('json')->fail('绑定失败');
  349. }
  350. public static function h5Key()
  351. {
  352. $time = time();
  353. do {
  354. $key = md5($time . rand(1000, 9999));
  355. } while (CacheService::get($key . '_time'));
  356. CacheService::set($key . '_time', $time, 300);
  357. return app('json')->success('ok', compact('key', 'time'));
  358. }
  359. public static function h5Auth($key, Request $request)
  360. {
  361. if (!CacheService::get($key . '_time')) return app('json')->fail('二维码已过期,请刷新。');
  362. CacheService::set($key, trim(ltrim($request->header('Authori-zation'), 'Bearer')), 60);
  363. return app('json')->success('授权完成');
  364. }
  365. public static function h5Token($key)
  366. {
  367. $token = CacheService::get($key);
  368. if ($token) return app('json')->success('ok', compact('token'));
  369. return app('json')->fail('未授权');
  370. }
  371. }