User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Ems;
  5. use app\common\library\Sms;
  6. use fast\Random;
  7. use think\Config;
  8. use think\Validate;
  9. use think\Db;
  10. use miniprogram\wxBizDataCrypt;
  11. /**
  12. * 会员接口
  13. */
  14. class User extends Api
  15. {
  16. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','wxMiniProgramLogin'];
  17. protected $noNeedRight = '*';
  18. public function _initialize()
  19. {
  20. parent::_initialize();
  21. if (!Config::get('fastadmin.usercenter')) {
  22. $this->error(__('User center already closed'));
  23. }
  24. }
  25. /**
  26. * 会员中心
  27. */
  28. public function index()
  29. {
  30. $this->success('', ['welcome' => $this->auth->nickname]);
  31. }
  32. /**
  33. * 会员登录
  34. *
  35. * @ApiMethod (POST)
  36. * @param string $account 账号
  37. * @param string $password 密码
  38. */
  39. public function login()
  40. {
  41. $account = $this->request->post('account');
  42. $password = $this->request->post('password');
  43. if (!$account || !$password) {
  44. $this->error(__('Invalid parameters'));
  45. }
  46. $ret = $this->auth->login($account, $password);
  47. if ($ret) {
  48. $data = ['userinfo' => $this->auth->getUserinfo()];
  49. $this->success(__('Logged in successful'), $data);
  50. } else {
  51. $this->error($this->auth->getError());
  52. }
  53. }
  54. /**
  55. * 手机验证码登录
  56. *
  57. * @ApiMethod (POST)
  58. * @param string $mobile 手机号
  59. * @param string $captcha 验证码
  60. */
  61. public function mobilelogin()
  62. {
  63. $mobile = $this->request->post('mobile');
  64. $captcha = $this->request->post('captcha');
  65. if (!$mobile || !$captcha) {
  66. $this->error(__('Invalid parameters'));
  67. }
  68. if (!Validate::regex($mobile, "^1\d{10}$")) {
  69. $this->error(__('Mobile is incorrect'));
  70. }
  71. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  72. $this->error(__('Captcha is incorrect'));
  73. }
  74. $user = \app\common\model\User::getByMobile($mobile);
  75. if ($user) {
  76. if ($user->status != 'normal') {
  77. $this->error(__('Account is locked'));
  78. }
  79. //如果已经有账号则直接登录
  80. $ret = $this->auth->direct($user->id);
  81. } else {
  82. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
  83. }
  84. if ($ret) {
  85. Sms::flush($mobile, 'mobilelogin');
  86. $data = ['userinfo' => $this->auth->getUserinfo()];
  87. $this->success(__('Logged in successful'), $data);
  88. } else {
  89. $this->error($this->auth->getError());
  90. }
  91. }
  92. /**
  93. * 注册会员
  94. *
  95. * @ApiMethod (POST)
  96. * @param string $username 用户名
  97. * @param string $password 密码
  98. * @param string $email 邮箱
  99. * @param string $mobile 手机号
  100. * @param string $code 验证码
  101. */
  102. public function register()
  103. {
  104. $username = $this->request->post('username');
  105. $password = $this->request->post('password');
  106. $email = $this->request->post('email');
  107. $mobile = $this->request->post('mobile');
  108. $code = $this->request->post('code');
  109. if (!$username || !$password) {
  110. $this->error(__('Invalid parameters'));
  111. }
  112. if ($email && !Validate::is($email, "email")) {
  113. $this->error(__('Email is incorrect'));
  114. }
  115. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  116. $this->error(__('Mobile is incorrect'));
  117. }
  118. $ret = Sms::check($mobile, $code, 'register');
  119. if (!$ret) {
  120. $this->error(__('Captcha is incorrect'));
  121. }
  122. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  123. if ($ret) {
  124. $data = ['userinfo' => $this->auth->getUserinfo()];
  125. $this->success(__('Sign up successful'), $data);
  126. } else {
  127. $this->error($this->auth->getError());
  128. }
  129. }
  130. /**
  131. * 退出登录
  132. * @ApiMethod (POST)
  133. */
  134. public function logout()
  135. {
  136. if (!$this->request->isPost()) {
  137. $this->error(__('Invalid parameters'));
  138. }
  139. $this->auth->logout();
  140. $this->success(__('Logout successful'));
  141. }
  142. /**
  143. * 修改会员个人信息
  144. *
  145. * @ApiMethod (POST)
  146. * @param string $avatar 头像地址
  147. * @param string $username 用户名
  148. * @param string $nickname 昵称
  149. * @param string $bio 个人简介
  150. */
  151. public function profile()
  152. {
  153. $user = $this->auth->getUser();
  154. $username = $this->request->post('username');
  155. $nickname = $this->request->post('nickname');
  156. $bio = $this->request->post('bio');
  157. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  158. if ($username) {
  159. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  160. if ($exists) {
  161. $this->error(__('Username already exists'));
  162. }
  163. $user->username = $username;
  164. }
  165. if ($nickname) {
  166. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  167. if ($exists) {
  168. $this->error(__('Nickname already exists'));
  169. }
  170. $user->nickname = $nickname;
  171. }
  172. $user->bio = $bio;
  173. $user->avatar = $avatar;
  174. $user->save();
  175. $this->success();
  176. }
  177. /**
  178. * 修改邮箱
  179. *
  180. * @ApiMethod (POST)
  181. * @param string $email 邮箱
  182. * @param string $captcha 验证码
  183. */
  184. public function changeemail()
  185. {
  186. $user = $this->auth->getUser();
  187. $email = $this->request->post('email');
  188. $captcha = $this->request->post('captcha');
  189. if (!$email || !$captcha) {
  190. $this->error(__('Invalid parameters'));
  191. }
  192. if (!Validate::is($email, "email")) {
  193. $this->error(__('Email is incorrect'));
  194. }
  195. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  196. $this->error(__('Email already exists'));
  197. }
  198. $result = Ems::check($email, $captcha, 'changeemail');
  199. if (!$result) {
  200. $this->error(__('Captcha is incorrect'));
  201. }
  202. $verification = $user->verification;
  203. $verification->email = 1;
  204. $user->verification = $verification;
  205. $user->email = $email;
  206. $user->save();
  207. Ems::flush($email, 'changeemail');
  208. $this->success();
  209. }
  210. /**
  211. * 修改手机号
  212. *
  213. * @ApiMethod (POST)
  214. * @param string $mobile 手机号
  215. * @param string $captcha 验证码
  216. */
  217. public function changemobile()
  218. {
  219. $user = $this->auth->getUser();
  220. $mobile = $this->request->post('mobile');
  221. $captcha = $this->request->post('captcha');
  222. if (!$mobile || !$captcha) {
  223. $this->error(__('Invalid parameters'));
  224. }
  225. if (!Validate::regex($mobile, "^1\d{10}$")) {
  226. $this->error(__('Mobile is incorrect'));
  227. }
  228. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  229. $this->error(__('Mobile already exists'));
  230. }
  231. $result = Sms::check($mobile, $captcha, 'changemobile');
  232. if (!$result) {
  233. $this->error(__('Captcha is incorrect'));
  234. }
  235. $verification = $user->verification;
  236. $verification->mobile = 1;
  237. $user->verification = $verification;
  238. $user->mobile = $mobile;
  239. $user->save();
  240. Sms::flush($mobile, 'changemobile');
  241. $this->success();
  242. }
  243. /**
  244. * 第三方登录
  245. *
  246. * @ApiMethod (POST)
  247. * @param string $platform 平台名称
  248. * @param string $code Code码
  249. */
  250. public function third()
  251. {
  252. $url = url('user/index');
  253. $platform = $this->request->post("platform");
  254. $code = $this->request->post("code");
  255. $config = get_addon_config('third');
  256. if (!$config || !isset($config[$platform])) {
  257. $this->error(__('Invalid parameters'));
  258. }
  259. $app = new \addons\third\library\Application($config);
  260. //通过code换access_token和绑定会员
  261. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  262. if ($result) {
  263. $loginret = \addons\third\library\Service::connect($platform, $result);
  264. if ($loginret) {
  265. $data = [
  266. 'userinfo' => $this->auth->getUserinfo(),
  267. 'thirdinfo' => $result
  268. ];
  269. $this->success(__('Logged in successful'), $data);
  270. }
  271. }
  272. $this->error(__('Operation failed'), $url);
  273. }
  274. /**
  275. * 重置密码
  276. *
  277. * @ApiMethod (POST)
  278. * @param string $mobile 手机号
  279. * @param string $newpassword 新密码
  280. * @param string $captcha 验证码
  281. */
  282. public function resetpwd()
  283. {
  284. $type = $this->request->post("type");
  285. $mobile = $this->request->post("mobile");
  286. $email = $this->request->post("email");
  287. $newpassword = $this->request->post("newpassword");
  288. $captcha = $this->request->post("captcha");
  289. if (!$newpassword || !$captcha) {
  290. $this->error(__('Invalid parameters'));
  291. }
  292. //验证Token
  293. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  294. $this->error(__('Password must be 6 to 30 characters'));
  295. }
  296. if ($type == 'mobile') {
  297. if (!Validate::regex($mobile, "^1\d{10}$")) {
  298. $this->error(__('Mobile is incorrect'));
  299. }
  300. $user = \app\common\model\User::getByMobile($mobile);
  301. if (!$user) {
  302. $this->error(__('User not found'));
  303. }
  304. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  305. if (!$ret) {
  306. $this->error(__('Captcha is incorrect'));
  307. }
  308. Sms::flush($mobile, 'resetpwd');
  309. } else {
  310. if (!Validate::is($email, "email")) {
  311. $this->error(__('Email is incorrect'));
  312. }
  313. $user = \app\common\model\User::getByEmail($email);
  314. if (!$user) {
  315. $this->error(__('User not found'));
  316. }
  317. $ret = Ems::check($email, $captcha, 'resetpwd');
  318. if (!$ret) {
  319. $this->error(__('Captcha is incorrect'));
  320. }
  321. Ems::flush($email, 'resetpwd');
  322. }
  323. //模拟一次登录
  324. $this->auth->direct($user->id);
  325. $ret = $this->auth->changepwd($newpassword, '', true);
  326. if ($ret) {
  327. $this->success(__('Reset password successful'));
  328. } else {
  329. $this->error($this->auth->getError());
  330. }
  331. }
  332. /**
  333. * 获取用户openid
  334. */
  335. public function getUserOpenid() {
  336. // code值
  337. $code = $this->request->param('code');
  338. if (!$code) {
  339. $this->error(__('Invalid parameters'));
  340. }
  341. $config = config('wxMiniProgram');
  342. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  343. $openidInfo = $this->getJson($getopenid);
  344. if(!isset($openidInfo['openid'])) {
  345. $this->error('用户openid获取失败',$openidInfo);
  346. }
  347. // 获取的结果存入数据库
  348. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  349. if($find) {
  350. $update = [];
  351. $update['sessionkey'] = $openidInfo['session_key'];
  352. $update['createtime'] = time();
  353. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  354. } else {
  355. $insert = [];
  356. $insert['sessionkey'] = $openidInfo['session_key'];
  357. $insert['openid'] = $openidInfo['openid'];
  358. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  359. $insert['createtime'] = time();
  360. $res = Db::name('user_sessionkey')->insertGetId($insert);
  361. }
  362. if($res !== false) {
  363. $this->success('获取成功',$openidInfo);
  364. } else {
  365. $this->error('获取失败');
  366. }
  367. }
  368. /**
  369. * 微信小程序登录
  370. */
  371. public function wxMiniProgramLogin() {
  372. $openid = $this->request->request('openid');// openid值
  373. $encryptedData = $this->request->request('encryptedData');// 加密数据
  374. $iv = $this->request->request('iv');// 加密算法
  375. $signature = $this->request->request('signature');// 签名验证
  376. $rawData = $this->request->request('rawData');// 签名验证
  377. $logintype = 2;// 登录方式:1=手机号,2=微信授权openid
  378. if (!$openid || !$encryptedData || !$iv) {
  379. $this->error(__('Invalid parameters'));
  380. }
  381. // 获取openid和sessionkey
  382. $config = config('wxMiniProgram');
  383. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  384. $openid = $openidInfo['openid'];
  385. $session_key = $openidInfo['sessionkey'];
  386. // // 数据签名校验
  387. // $signature2 = sha1($rawData . $session_key);
  388. // if ($signature != $signature2) {
  389. // $this->error(__('数据签名验证失败'));
  390. // }
  391. // 根据加密数据和加密算法获取用户信息
  392. $pc = new WXBizDataCrypt($config['appid'], $session_key);
  393. $data = '';
  394. $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
  395. if ($errCode != 0) {
  396. $this->error('解密失败',['code'=>$errCode]);
  397. }
  398. $data = json_decode($data,true);
  399. // 用户登录逻辑 === 开始
  400. if($logintype == 1) { // 手机号登录
  401. /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
  402. // 用户信息不存在时使用
  403. $extend = ["mobile"=>$data["purePhoneNumber"]];*/
  404. } else { // 微信授权openid登录
  405. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  406. // 用户信息不存在时使用
  407. $extend = [
  408. 'mini_openid' => $openid,
  409. 'nickname' => $data['nickName'],
  410. 'avatar' => $data['avatarUrl'],
  411. //'gender' => $data['gender']==1 ? 1 : 0,
  412. 'mini_sessionkey'=> $session_key,
  413. 'unionid' => $openidInfo['unionid'],
  414. //'mobile' => $data['purePhoneNumber'],
  415. ];
  416. }
  417. // 判断用户是否已经存在
  418. if($userInfo) { // 登录
  419. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  420. $res = $this->auth->direct($userInfo['id']);
  421. } else { // 注册
  422. // 先随机一个用户名,随后再变更为u+数字id
  423. $username = '';
  424. $password = '';
  425. /*Db::startTrans();
  426. try {*/
  427. // 默认注册一个会员
  428. $result = $this->auth->register($username, $password, '','', $extend);
  429. if (!$result) {
  430. $this->error("注册失败!");
  431. }
  432. /* Db::commit();
  433. } catch (PDOException $e) {
  434. Db::rollback();
  435. $this->auth->logout();
  436. return false;
  437. }*/
  438. // 写入登录Cookies和Token
  439. $res = $this->auth->direct($this->auth->id);
  440. }
  441. $userInfo = $this->userInfo('return');
  442. if($res) {
  443. $this->success("登录成功!",$userInfo);
  444. } else {
  445. $this->error("登录失败!");
  446. }
  447. }
  448. /**
  449. * json 请求
  450. * @param $url
  451. * @return mixed
  452. */
  453. private function getJson($url){
  454. $ch = curl_init();
  455. curl_setopt($ch, CURLOPT_URL, $url);
  456. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  457. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  458. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  459. $output = curl_exec($ch);
  460. curl_close($ch);
  461. return json_decode($output, true);
  462. }
  463. }