AuthController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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', $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. * H5注册新用户
  226. * @param Request $request
  227. * @return mixed
  228. */
  229. public function register(Request $request)
  230. {
  231. list($account, $captcha, $password, $spread) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['spread', 0]], $request, true);
  232. try {
  233. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  234. } catch (ValidateException $e) {
  235. return app('json')->fail($e->getError());
  236. }
  237. $verifyCode = CacheService::get('code_' . $account);
  238. if (!$verifyCode)
  239. return app('json')->fail('请先获取验证码');
  240. $verifyCode = substr($verifyCode, 0, 6);
  241. if ($verifyCode != $captcha)
  242. return app('json')->fail('验证码错误');
  243. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  244. return app('json')->fail('密码必须是在6到16位之间');
  245. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  246. $registerStatus = User::register($account, $password, $spread);
  247. if ($registerStatus) return app('json')->success('注册成功');
  248. return app('json')->fail(User::getErrorInfo('注册失败'));
  249. }
  250. /**
  251. * 密码修改
  252. * @param Request $request
  253. * @return mixed
  254. */
  255. public function reset(Request $request)
  256. {
  257. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $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. $resetStatus = User::reset($account, $password);
  273. if ($resetStatus) return app('json')->success('修改成功');
  274. return app('json')->fail(User::getErrorInfo('修改失败'));
  275. }
  276. /**
  277. * 手机号登录
  278. * @param Request $request
  279. * @return mixed
  280. * @throws \think\db\exception\DataNotFoundException
  281. * @throws \think\db\exception\ModelNotFoundException
  282. * @throws \think\exception\DbException
  283. */
  284. public function mobile(Request $request)
  285. {
  286. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  287. //验证手机号
  288. try {
  289. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  290. } catch (ValidateException $e) {
  291. return app('json')->fail($e->getError());
  292. }
  293. //验证验证码
  294. $verifyCode = CacheService::get('code_' . $phone);
  295. if (!$verifyCode)
  296. return app('json')->fail('请先获取验证码');
  297. $verifyCode = substr($verifyCode, 0, 6);
  298. if ($verifyCode != $captcha)
  299. return app('json')->fail('验证码错误');
  300. //数据库查询
  301. $user = User::where('account', $phone)->find();
  302. if (!$user)
  303. return app('json')->fail('用户不存在');
  304. if (!$user->status)
  305. return app('json')->fail('已被禁止,请联系管理员');
  306. // 设置推广关系
  307. User::setSpread($spread, $user->uid);
  308. $token = UserToken::createToken($user, 'user');
  309. if ($token) {
  310. event('UserLogin', [$user, $token]);
  311. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  312. } else
  313. return app('json')->fail('登录失败');
  314. }
  315. /**
  316. * H5切换登陆
  317. * @param Request $request
  318. * @return mixed
  319. * @throws \think\db\exception\DataNotFoundException
  320. * @throws \think\db\exception\ModelNotFoundException
  321. * @throws \think\exception\DbException
  322. */
  323. public function switch_h5(Request $request)
  324. {
  325. $from = $request->post('from', 'wechat');
  326. $user = $request->user();
  327. if ($from === 'h5') {
  328. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  329. $user->login_type = 'wechat';
  330. $user->save();
  331. } else {
  332. //数据库查询
  333. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  334. if (!$user)
  335. return app('json')->fail('H5用户不存在,无法切换');
  336. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  337. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  338. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  339. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  340. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  341. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  342. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  343. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  344. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  345. switch ($from) {
  346. case 'wechat':
  347. if (!$wechatH5UserInfo->openid)
  348. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  349. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  350. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  351. break;
  352. case 'routine':
  353. if (!$wechatH5UserInfo->routine_openid)
  354. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  355. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  356. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  357. break;
  358. }
  359. $wechatH5UserInfo->save();
  360. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  361. }
  362. $token = UserToken::createToken($user, 'user');
  363. if ($token) {
  364. event('UserLogin', [$user, $token]);
  365. //退出上一个账号
  366. $request->tokenData()->delete();
  367. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  368. } else
  369. return app('json')->fail('登录失败');
  370. }
  371. /**
  372. * 绑定手机号
  373. * @param Request $request
  374. * @return mixed
  375. * @throws \think\db\exception\DataNotFoundException
  376. * @throws \think\db\exception\ModelNotFoundException
  377. * @throws \think\exception\DbException
  378. */
  379. public function binding_phone(Request $request)
  380. {
  381. list($phone, $captcha, $step) = UtilService::postMore([
  382. ['phone', ''],
  383. ['captcha', ''],
  384. ['step', 0]
  385. ], $request, true);
  386. //验证手机号
  387. try {
  388. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  389. } catch (ValidateException $e) {
  390. return app('json')->fail($e->getError());
  391. }
  392. //验证验证码
  393. $verifyCode = CacheService::get('code_' . $phone);
  394. if (!$verifyCode)
  395. return app('json')->fail('请先获取验证码');
  396. $verifyCode = substr($verifyCode, 0, 6);
  397. if ($verifyCode != $captcha)
  398. return app('json')->fail('验证码错误');
  399. $userInfo = User::where('uid', $request->uid())->find();
  400. $userPhone = $userInfo->phone;
  401. if (!$userInfo) return app('json')->fail('用户不存在');
  402. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  403. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  404. return app('json')->fail('此手机已经绑定,无法多次绑定!');
  405. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  406. if (!$step) return app('json')->fail('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  407. $userInfo->phone = $phone;
  408. } else {
  409. $userInfo->account = $phone;
  410. $userInfo->phone = $phone;
  411. }
  412. if ($userInfo->save() || $userPhone == $phone)
  413. return app('json')->success('绑定成功');
  414. else
  415. return app('json')->fail('绑定失败');
  416. }
  417. }