User.php 16 KB

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