AuthController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. /**
  183. * 密码修改
  184. * @param Request $request
  185. * @return mixed
  186. */
  187. public function reset(Request $request)
  188. {
  189. list($account, $captcha, $password) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', '']], $request, true);
  190. try {
  191. validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password]);
  192. } catch (ValidateException $e) {
  193. return app('json')->fail($e->getError());
  194. }
  195. $verifyCode = CacheService::get('code_' . $account);
  196. if (!$verifyCode)
  197. return app('json')->fail('请先获取验证码');
  198. $verifyCode = substr($verifyCode, 0, 6);
  199. if ($verifyCode != $captcha)
  200. return app('json')->fail('验证码错误');
  201. if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
  202. return app('json')->fail('密码必须是在6到16位之间');
  203. if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
  204. $resetStatus = User::reset($account, $password);
  205. if ($resetStatus) return app('json')->success('修改成功');
  206. return app('json')->fail(User::getErrorInfo('修改失败'));
  207. }
  208. /**
  209. * 手机号登录
  210. * @param Request $request
  211. * @return mixed
  212. * @throws \think\db\exception\DataNotFoundException
  213. * @throws \think\db\exception\ModelNotFoundException
  214. * @throws \think\exception\DbException
  215. */
  216. public function mobile(Request $request)
  217. {
  218. list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
  219. //验证手机号
  220. try {
  221. validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
  222. } catch (ValidateException $e) {
  223. return app('json')->fail($e->getError());
  224. }
  225. //验证验证码
  226. $verifyCode = CacheService::get('code_' . $phone);
  227. if (!$verifyCode)
  228. return app('json')->fail('请先获取验证码');
  229. $verifyCode = substr($verifyCode, 0, 6);
  230. if ($verifyCode != $captcha)
  231. return app('json')->fail('验证码错误');
  232. //数据库查询
  233. $user = User::where('account', $phone)->find();
  234. if (!$user)
  235. return app('json')->fail('用户不存在');
  236. if (!$user->status)
  237. return app('json')->fail('已被禁止,请联系管理员');
  238. // 设置推广关系
  239. User::setSpread($spread, $user->uid);
  240. $token = UserToken::createToken($user, 'user');
  241. if ($token) {
  242. event('UserLogin', [$user, $token]);
  243. return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
  244. } else
  245. return app('json')->fail('登录失败');
  246. }
  247. /**
  248. * H5切换登陆
  249. * @param Request $request
  250. * @return mixed
  251. * @throws \think\db\exception\DataNotFoundException
  252. * @throws \think\db\exception\ModelNotFoundException
  253. * @throws \think\exception\DbException
  254. */
  255. public function switch_h5(Request $request)
  256. {
  257. $from = $request->post('from', 'wechat');
  258. $user = $request->user();
  259. if ($from === 'h5') {
  260. $user = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find();
  261. $user->login_type = 'wechat';
  262. $user->save();
  263. } else {
  264. //数据库查询
  265. $user = User::where('account|phone', $user['phone'])->where('user_type', 'h5')->find();
  266. if (!$user)
  267. return app('json')->fail('H5用户不存在,无法切换');
  268. if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
  269. $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
  270. $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
  271. if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
  272. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  273. if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
  274. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  275. if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
  276. return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
  277. switch ($from) {
  278. case 'wechat':
  279. if (!$wechatH5UserInfo->openid)
  280. $wechatH5UserInfo->openid = $wechatUserInfo->openid;
  281. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  282. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  283. break;
  284. case 'routine':
  285. if (!$wechatH5UserInfo->routine_openid)
  286. $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
  287. if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
  288. $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
  289. break;
  290. }
  291. $wechatH5UserInfo->save();
  292. User::where('uid', $request->uid())->update(['login_type' => 'h5']);
  293. }
  294. $token = UserToken::createToken($user, 'user');
  295. if ($token) {
  296. event('UserLogin', [$user, $token]);
  297. return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
  298. } else
  299. return app('json')->fail('登录失败');
  300. }
  301. /**
  302. * 绑定手机号
  303. * @param Request $request
  304. * @return mixed
  305. * @throws \think\db\exception\DataNotFoundException
  306. * @throws \think\db\exception\ModelNotFoundException
  307. * @throws \think\exception\DbException
  308. */
  309. public function binding_phone(Request $request)
  310. {
  311. list($phone, $captcha, $step) = UtilService::postMore([
  312. ['phone', ''],
  313. ['captcha', ''],
  314. ['step', 0]
  315. ], $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. $userInfo = User::where('uid', $request->uid())->find();
  330. $userPhone = $userInfo->phone;
  331. if (!$userInfo) return app('json')->fail('用户不存在');
  332. if ($userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码!');
  333. if (User::where('phone', $phone)->where('user_type', '<>', 'h5')->count())
  334. return app('json')->success('此手机已经绑定,无法多次绑定!');
  335. if (User::where('account', $phone)->where('phone', $phone)->where('user_type', 'h5')->find()) {
  336. if (!$step) return app('json')->success('H5已有账号是否绑定此账号上', ['is_bind' => 1]);
  337. $userInfo->phone = $phone;
  338. } else {
  339. $userInfo->account = $phone;
  340. $userInfo->phone = $phone;
  341. }
  342. if ($userInfo->save() || $userPhone == $phone)
  343. return app('json')->success('绑定成功');
  344. else
  345. return app('json')->fail('绑定失败');
  346. }
  347. }