AuthController.php 18 KB

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