AuthController.php 18 KB

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