AuthController.php 17 KB

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