AuthController.php 16 KB

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