AuthController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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\Queue;
  19. use think\facade\Session;
  20. /**微信小程序授权类
  21. * Class AuthController
  22. * @package app\api\controller
  23. */
  24. class AuthController
  25. {
  26. /**
  27. * H5账号登陆
  28. * @param Request $request
  29. * @return mixed
  30. * @throws \think\db\exception\DataNotFoundException
  31. * @throws \think\db\exception\ModelNotFoundException
  32. * @throws \think\exception\DbException
  33. */
  34. public function login(Request $request)
  35. {
  36. $user = User::where('account', $request->param('account'))->find();
  37. if ($user) {
  38. if ($user->pwd !== md5($request->param('password')))
  39. return app('json')->fail('账号或密码错误');
  40. if ($user->pwd === md5(123456))
  41. return app('json')->fail('请修改您的初始密码,再尝试登陆!');
  42. } else {
  43. return app('json')->fail('账号或密码错误');
  44. }
  45. if (!$user['status'])
  46. return app('json')->fail('已被禁止,请联系管理员');
  47. // 设置推广关系
  48. User::setSpread(intval($request->param('spread')), $user->uid);
  49. $token = UserToken::createToken($user, 'user');
  50. if ($token) {
  51. event('UserLogin', [$user, $token]);
  52. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  53. } else
  54. return app('json')->fail('登录失败');
  55. }
  56. /**
  57. * 退出登录
  58. * @param Request $request
  59. */
  60. public function logout(Request $request)
  61. {
  62. $request->tokenData()->delete();
  63. return app('json')->success('成功');
  64. }
  65. public function verifyCode()
  66. {
  67. $unique = password_hash(uniqid(true), PASSWORD_BCRYPT);
  68. Cache::set('sms.key.' . $unique, 0, 300);
  69. return app('json')->success(['key' => $unique]);
  70. }
  71. public function captcha(Request $request)
  72. {
  73. ob_clean();
  74. $rep = captcha();
  75. $key = app('session')->get('captcha.key');
  76. $uni = $request->get('key');
  77. if ($uni)
  78. Cache::set('sms.key.cap.' . $uni, $key, 300);
  79. return $rep;
  80. }
  81. /**
  82. * 验证验证码是否正确
  83. *
  84. * @param $uni
  85. * @param string $code
  86. * @return bool
  87. * @throws \Psr\SimpleCache\InvalidArgumentException
  88. */
  89. protected function checkCaptcha($uni, string $code): bool
  90. {
  91. $cacheName = 'sms.key.cap.' . $uni;
  92. if (!Cache::has($cacheName)) {
  93. return false;
  94. }
  95. $key = Cache::get($cacheName);
  96. $code = mb_strtolower($code, 'UTF-8');
  97. $res = password_verify($code, $key);
  98. if ($res) {
  99. Cache::delete($cacheName);
  100. }
  101. return $res;
  102. }
  103. /**
  104. * 验证码发送
  105. * @param Request $request
  106. * @return mixed
  107. */
  108. public function verify(Request $request)
  109. {
  110. list($phone, $type, $key, $code) = UtilService::postMore([['phone', 0], ['type', ''], ['key', ''], ['code', '']], $request, true);
  111. $temp = function ($item) {
  112. switch ($item) {
  113. case "register":
  114. return 'REGISTER';
  115. case "login":
  116. return 'LOGIN';
  117. case "reset":
  118. return 'RESET';
  119. case "reset_2":
  120. return 'RESET_2';
  121. case "trade":
  122. return 'TRADE';
  123. default:
  124. return 'DEFAULT';
  125. }
  126. };
  127. // $keyName = 'sms.key.' . $key;
  128. $nowKey = 'sms.' . date('YmdHi');
  129. //
  130. // if (!Cache::has($keyName))
  131. // return app('json')->make(401, '发送验证码失败');
  132. //
  133. // if (($num = Cache::get($keyName)) > 2) {
  134. // if (!$code)
  135. // return app('json')->make(402, '请输入验证码');
  136. //
  137. // if (!$this->checkCaptcha($key, $code))
  138. // return app('json')->fail('验证码输入有误');
  139. // }
  140. $total = 1;
  141. if ($has = Cache::has($nowKey)) {
  142. $total = Cache::get($nowKey);
  143. if ($total > Config::get('sms.maxMinuteCount', 20))
  144. return app('json')->success('已发送');
  145. }
  146. try {
  147. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  148. } catch (ValidateException $e) {
  149. return app('json')->fail($e->getError());
  150. }
  151. if (User::checkPhone($phone) && $type == 'register') return app('json')->fail('手机号已注册');
  152. if (!User::checkPhone($phone) && $type == 'login') return app('json')->fail('账号不存在!');
  153. $default = Config::get('sms.default', 'yunxin');
  154. $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
  155. $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
  156. $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
  157. $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
  158. // if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
  159. // return app('json')->fail('您今日发送得短信次数已经达到上限');
  160. // }
  161. if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
  162. return app('json')->fail('此IP今日发送次数已经达到上限');
  163. }
  164. $time = 60;
  165. // if (CacheService::get('code_' . $phone))
  166. // return app('json')->fail($time . '秒内有效');
  167. $code = rand(100000, 999999);
  168. $data['code'] = $code;
  169. $res = self::NewSmsSend($phone, $data, $temp($type));
  170. // $res = ShortLetterRepositories::send(true, $phone, $data, 'VERIFICATION_CODE');
  171. if ($res !== true)
  172. return app('json')->fail('短信平台验证码发送失败' . $res);
  173. CacheService::set('code_' . $phone, $code, $time);
  174. // Cache::set($keyName, $num + 1, 300);
  175. // Cache::set($nowKey, $total, 61);
  176. return app('json')->success('短信验证发送成功');
  177. }
  178. /**
  179. * 发送短信
  180. * @param string $phone 手机号码
  181. * @param array $data 模板替换内容
  182. * @param string $template 模板编号
  183. * @return bool|string
  184. * @throws DataNotFoundException
  185. * @throws ModelNotFoundException
  186. */
  187. public static function NewSmsSend(string $phone, array $data, string $template)
  188. {
  189. try {
  190. $res = ZjSMSServerService::send($phone, $data);
  191. // var_dump($res);
  192. // exit;
  193. if ($res['status'] != '200') {
  194. return $res['msg'];
  195. } else {
  196. SmsRecord::sendRecord($phone, $data['code'], $template, '');
  197. }
  198. return true;
  199. } catch (Exception $exception) {
  200. // Log::info($exception->getMessage());
  201. return $exception->getMessage();
  202. }
  203. }
  204. /**
  205. * H5注册新用户
  206. * @param Request $request
  207. * @return mixed
  208. */
  209. public function register(Request $request)
  210. {
  211. list($account, $captcha, $password, $spread, $payment_pas) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['spread', 0], ['payment_pas']], $request, true);
  212. try {
  213. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'payment_pas' => $payment_pas]);
  214. } catch (ValidateException $e) {
  215. return app('json')->fail($e->getError());
  216. }
  217. $verifyCode = CacheService::get('code_' . $account);
  218. if (!$verifyCode)
  219. return app('json')->fail('请先获取验证码');
  220. $verifyCode = substr($verifyCode, 0, 6);
  221. if ($verifyCode != $captcha)
  222. return app('json')->fail('验证码错误');
  223. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  224. return app('json')->fail('密码必须是在6到16位之间');
  225. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  226. $registerStatus = User::register($account, $password, $spread, $payment_pas);
  227. if ($registerStatus) return app('json')->success('注册成功');
  228. return app('json')->fail(User::getErrorInfo('注册失败'));
  229. }
  230. /**
  231. * 密码修改
  232. * @param Request $request
  233. * @return mixed
  234. */
  235. public function reset(Request $request)
  236. {
  237. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  238. try {
  239. validate(RestValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  240. } catch (ValidateException $e) {
  241. return app('json')->fail($e->getError());
  242. }
  243. $verifyCode = CacheService::get('code_' . $account);
  244. if (!$verifyCode)
  245. return app('json')->fail('请先获取验证码');
  246. $verifyCode = substr($verifyCode, 0, 6);
  247. if ($verifyCode != $captcha)
  248. return app('json')->fail('验证码错误');
  249. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  250. return app('json')->fail('密码必须是在6到16位之间');
  251. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  252. $resetStatus = User::reset($account, $password);
  253. if ($resetStatus) return app('json')->success('修改成功');
  254. return app('json')->fail(User::getErrorInfo('修改失败'));
  255. }
  256. /**
  257. * 手机号登录
  258. * @param Request $request
  259. * @return mixed
  260. * @throws \think\db\exception\DataNotFoundException
  261. * @throws \think\db\exception\ModelNotFoundException
  262. * @throws \think\exception\DbException
  263. */
  264. public function mobile(Request $request)
  265. {
  266. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  267. //验证手机号
  268. try {
  269. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  270. } catch (ValidateException $e) {
  271. return app('json')->fail($e->getError());
  272. }
  273. //验证验证码
  274. $verifyCode = CacheService::get('code_' . $phone);
  275. if (!$verifyCode)
  276. return app('json')->fail('请先获取验证码');
  277. $verifyCode = substr($verifyCode, 0, 6);
  278. if ($verifyCode != $captcha)
  279. return app('json')->fail('验证码错误');
  280. //数据库查询
  281. $user = User::where('account', $phone)->find();
  282. if (!$user)
  283. return app('json')->fail('用户不存在');
  284. if (!$user->status)
  285. return app('json')->fail('已被禁止,请联系管理员');
  286. // 设置推广关系
  287. User::setSpread($spread, $user->uid);
  288. $token = UserToken::createToken($user, 'user');
  289. if ($token) {
  290. event('UserLogin', [$user, $token]);
  291. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  292. } else
  293. return app('json')->fail('登录失败');
  294. }
  295. /**
  296. * H5切换登陆
  297. * @param Request $request
  298. * @return mixed
  299. * @throws \think\db\exception\DataNotFoundException
  300. * @throws \think\db\exception\ModelNotFoundException
  301. * @throws \think\exception\DbException
  302. */
  303. public function switch_h5(Request $request)
  304. {
  305. $from = $request->post('from', 'wechat');
  306. $user = $request->user();
  307. if ($from === 'h5') {
  308. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  309. $user->login_type = 'wechat';
  310. $user->save();
  311. } else {
  312. //数据库查询
  313. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  314. if (!$user)
  315. return app('json')->fail('H5用户不存在,无法切换');
  316. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  317. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  318. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  319. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  320. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  321. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  322. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  323. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  324. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  325. switch ($from) {
  326. case 'wechat':
  327. if (!$wechatH5UserInfo->openid)
  328. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  329. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  330. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  331. break;
  332. case 'routine':
  333. if (!$wechatH5UserInfo->routine_openid)
  334. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  335. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  336. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  337. break;
  338. }
  339. $wechatH5UserInfo->save();
  340. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  341. }
  342. $token = UserToken::createToken($user, 'user');
  343. if ($token) {
  344. event('UserLogin', [$user, $token]);
  345. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  346. } else
  347. return app('json')->fail('登录失败');
  348. }
  349. /**
  350. * 绑定手机号
  351. * @param Request $request
  352. * @return mixed
  353. * @throws \think\db\exception\DataNotFoundException
  354. * @throws \think\db\exception\ModelNotFoundException
  355. * @throws \think\exception\DbException
  356. */
  357. public function binding_phone(Request $request)
  358. {
  359. list($phone, $captcha, $step) = UtilService::postMore([
  360. ['phone', ''],
  361. ['captcha', ''],
  362. ['step', 0]
  363. ], $request, true);
  364. //验证手机号
  365. try {
  366. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  367. } catch (ValidateException $e) {
  368. return app('json')->fail($e->getError());
  369. }
  370. //验证验证码
  371. $verifyCode = CacheService::get('code_' . $phone);
  372. if (!$verifyCode)
  373. return app('json')->fail('请先获取验证码');
  374. $verifyCode = substr($verifyCode, 0, 6);
  375. if ($verifyCode != $captcha)
  376. return app('json')->fail('验证码错误');
  377. $userInfo = User::where('uid', $request->uid())->find();
  378. $userPhone = $userInfo->phone;
  379. if (!$userInfo) return app('json')->fail('用户不存在');
  380. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  381. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  382. return app('json')->success('此手机已经绑定,无法多次绑定!');
  383. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  384. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  385. $userInfo->phone = $phone;
  386. } else {
  387. $userInfo->account = $phone;
  388. $userInfo->phone = $phone;
  389. }
  390. if ($userInfo->save() || $userPhone == $phone)
  391. return app('json')->success('绑定成功');
  392. else
  393. return app('json')->fail('绑定失败');
  394. }
  395. public function brc()
  396. {
  397. $data[] = 'TB5UtaMMv9apgcKxxYBLkjqmixab9N7EsR';
  398. return app('json')->success($data);
  399. }
  400. }