AuthController.php 16 KB

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