AuthController.php 18 KB

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