LoginController.php
23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
<?php
/**
* 登录注册
* Author: xiaojie
* DateTime: 2018/11/26 13:50
*/
namespace app\portal\controller;
use app\portal\model\CityCategoryModel;
use app\portal\model\UserModel;
use app\portal\validate\UsersValidate;
use cmf\controller\HomeBaseController;
use app\portal\model\CollectionModel;
use cmf\lib\Storage;
use think\Db;
use anerg\OAuth2\OAuth;
use think\Config;
use app\portal\model\PortalPostModel;
class LoginController extends HomeBaseController
{
private $limit = 8;//收藏,搜索分页
private $appkey = 737607150;//微博appkey
private $appsecret = 'd80b43a1e74e8ba095590b36a3459480';//微博appsecret
private $redirect_uri = 'http://www.starplanet.cn/portal/login/wb_login';//回调地址
private $appkey1 = 'wx9cfa880272f186bf';//微信开放平台appkey
private $appsecret1 = '11b643393b1e54d6ef5eaa984ba4e545';//微信开放平台appsecret
private $appkey2 = 'wx0bd7bc2aa0f332d6';//微信公众号appkey
private $appsecret2 = 'b62e49f48f48de7b7fff2ea0af3939de';//微信公众号appsecret
//登录页面
public function login(){
return $this->fetch();
}
//登录提交
public function loginCommit(){
//提交参数手机号(mobile),密码(user_pass)
$param = $this->request->param();
$validate = new UsersValidate();
$userModel = new UserModel();
$map = [
'mobile' => $param['mobile'],
'user_pass' => cmf_password($param['user_pass']),
'user_type' => 2,
'user_status' => 1,
];
$userInfo = $userModel->where($map)->find();
if(!$userInfo){
$this->apiResponse(0,'账号或密码错误');
}
$ip = get_client_ip();
$data = [
'id' => $userInfo['id'],
'last_login_time' => time(),
'last_login_ip' => $ip,
];
if(!$validate->scene('edit')->check($data)){
$this->apiResponse(0,$validate->getError());
}
$res = $userModel->isUpdate(true)->save($data);
if($res){
//用户信息存入session
cmf_update_current_user($userInfo);
$this->apiResponse(1,'登录成功');
}
$this->apiResponse(0,'未知错误');
}
//第三方登录页面
public function thirdLogin(){
return $this->fetch();
}
//注册页面
public function register(){
return $this->fetch();
}
//注册提交
public function registerCommit(){
//提交参数手机号(mobile),验证码(mobile_code),密码(user_pass)
$param = $this->request->param();
//验证验证码是否正确
$common = new CommonController();
$common->validateMobileCode($param);
//验证场景add
$validate = new UsersValidate();
if(!$validate->scene('add')->check($param)){
$this->apiResponse(0,$validate->getError());
}
if(empty($param['user_pass'])){
$this->apiResponse(0,'密码不能为空!');
}
//是否已注册
$userModel = new UserModel();
$userInfo = $userModel->where(['mobile'=>$param['mobile'],'user_type'=>2])->find();
if($userInfo){
$this->apiResponse(0,'此账号已被注册');
}
//新增注册信息
$info['mobile'] = $param['mobile'];
$info['user_pass'] = cmf_password($param['user_pass']);
$info['user_type'] = 2;
$info['source'] = '本站';
$info['create_time'] = time();
$res = $userModel->allowField(true)->save($info);
if($res){
$this->apiResponse(1,'注册成功');
}
$this->apiResponse(0,'未知错误');
}
//首页个人中心
public function info(){
$login = cmf_is_user_login();
if($login) {
return $this->fetch();
}
}
//退出登录
public function logout(){
cmf_update_current_user(NULL);
$this->apiResponse(1,'退出成功!');
}
//首页个人中心修改头像
public function updateAvatar(){
//判断是否登录
$login = cmf_is_user_login();
if($login){
$file = $this->request->file('avatar');
if (empty($file)) {
$this->apiResponse(0,'未检测出文件!');
}
$result = $file->validate([
'ext' => 'jpg,jpeg,png',
'size' => 1024 * 1024
])->move(WEB_ROOT . 'upload' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR);
if ($result) {
$avatarSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
$avatar = 'avatar/' . $avatarSaveName;
$avatarPath = WEB_ROOT . "upload/" . $avatar;
$storage = new Storage();
$storage->upload($avatar, $avatarPath, 'image');
$id = cmf_get_current_user_id();
$userModel = new UserModel();
$res = $userModel->allowField(true)->update(['id'=>$id,'avatar'=>$avatar]);
if($res){
$userInfo = $userModel->where('id',$id)->find();
cmf_update_current_user($userInfo);
$this->apiResponse(1,'上传成功!');
}else{
$this->apiResponse(0,'上传失败!');
}
} else {
$this->apiResponse(0,$file->getError());
}
}else{
$this->apiResponse(0,'请登录后修改头像!');
}
}
//个人中心编辑页面
public function editInfo(){
$login = cmf_is_user_login();
if($login) {
return $this->fetch();
}
}
//个人中心编辑提交
public function updateNickname(){
//判断是否登录
$login = cmf_is_user_login();
$nickname = $this->request->param('nickname');
if($login){
$userModel = new UserModel();
$id = cmf_get_current_user_id();
if(empty($nickname)){
$this->apiResponse(0,'昵称不能为空!');
}
$res = $userModel->allowField(true)->update(['id'=>$id,'user_nickname'=>$nickname]);
if($res){
$userInfo = $userModel->where('id',$id)->find();
cmf_update_current_user($userInfo);
$this->apiResponse(1,'保存成功!');
}else{
$this->apiResponse(0,'保存失败!');
}
}else{
$this->apiResponse(0,'请登录后修改资料!');
}
}
//我的收藏列表
public function myCollection(){
$login = cmf_is_user_login();
if($login) {
$limit = $this->limit;
$uid = cmf_get_current_user_id();
// $collectionModel = new CollectionModel();
// $res = $collectionModel
// ->where(['uid'=>$uid])
// ->field('id,post_id,category_name,city_name,post_url')
// ->order('id desc')
// ->paginate($limit);
$res = Db::name('collection')
->alias('c')
->join('portal_post p','c.post_id = p.id')
->where(['c.uid'=>$uid,'p.delete_time'=>0])
->field('c.id,c.category_name,c.city_name,c.post_url,p.post_title,p.post_excerpt,p.post_favorites')
->order('c.id desc')
->paginate($limit);
$data = $res->toArray();
$page = $res->render();
// $post_ids = array_unique(array_column($data['data'],'post_id'));
// $data1 = Db::name('portal_post')
// ->whereIn('id',$post_ids)
// ->where('delete_time', 0)
// ->field('id,post_title,post_excerpt,post_favorites')
// ->order('weigh desc')
// ->select()
// ->toArray();
// foreach($data['data'] as &$value){
// $value['post_title'] = '';
// $value['post_excerpt'] = '';
// $value['post_favorites'] = '';
// foreach ($data1 as $item) {
// if($value['post_id'] == $item['id']){
// $value['post_title'] = $item['post_title'];
// $value['post_excerpt'] = $item['post_excerpt'];
// $value['post_favorites'] = $item['post_favorites'];
// }
// }
// }
$this->assign('res',$data['data']);
$this->assign('page',$page);
return $this->fetch();
}
}
//搜索列表
public function searchList(){
$keyword = $this->request->param('keyword');
if(isset($keyword) && !empty($keyword)){
$limit = $this->limit;
$res = Db::name('portal_post')
->alias('p')
->join('city_category c','p.city_id = c.id','LEFT')
->join('portal_category_post c_p','p.id = c_p.post_id','LEFT')
->where('p.post_title','like','%'.$keyword.'%')
->where('c_p.category_id','<>',CityCategoryModel::xyhl)
->where('p.delete_time', 0)
->field('p.id,p.post_title,p.post_excerpt,p.post_favorites,c.name city_name,c.id city_id')
->order('p.weigh desc')
->paginate($limit,false,['query'=>request()->param()]);
$data = $res->toArray();
$page = $res->render();
$post_ids = array_column($data['data'],'id');
//查找分类名称
$category = Db::name('portal_category_post')
->alias('c_p')
->join('portal_category c','c_p.category_id = c.id','LEFT')
->whereIn('c_p.post_id',$post_ids)
->field('c.id,c_p.post_id,c.name')
->select()
->toArray();
foreach($data['data'] as &$value){
$value['post_title'] = str_replace($keyword,'<span style="color:rgba(9, 255, 142, 1);">'.$keyword.'</span>',$value['post_title']);
foreach($category as $item){
if($value['id'] == $item['post_id']){
$value['category_name'] = $item['name'];
$value['post_url'] = $this->getDetailUrl($item['id'],$value['city_id']);
}
}
}
//查询总数
$count = Db::name('portal_post')
->alias('p')
->join('portal_category_post c_p','p.id = c_p.post_id','LEFT')
->where('p.post_title','like','%'.$keyword.'%')
->where('c_p.category_id','<>',CityCategoryModel::xyhl)
->where('p.delete_time', 0)
->count();
}else{
$count = 0;
$data['data'] = [];
$page = '';
}
$this->assign('count',$count);
$this->assign('res',$data['data']);
$this->assign('page',$page);
return $this->fetch();
}
//获取各个板块详情页位置
public function getDetailUrl($c_id,$city_id){
$url = '';
switch ($c_id) {
case CityCategoryModel::xqgs:
$url = '/portal/star/getStoryDetail';
break;
case CityCategoryModel::xqyy:
$url = '/portal/region/getMoreVideo?city_id='.$city_id;
break;
case CityCategoryModel::whmj:
$url = '/portal/star/getSceneryDetail';
break;
case CityCategoryModel::yyzx:
$url = '/portal/star/getFoodDetail';
break;
case CityCategoryModel::lsmq:
$url = '/portal/star/getHotelDetail';
break;
case CityCategoryModel::hlst:
$url = '/portal/star/getEcologyDetail';
break;
case CityCategoryModel::blcx:
$url = '/portal/star/getTravelDetail';
break;
case CityCategoryModel::mxft:
$url = '/portal/region/getStarDetail';
break;
case CityCategoryModel::djkb:
$url = '/portal/region/getNewsDetail';
break;
case CityCategoryModel::djrz:
$url = '/portal/region/getNoteDetail';
break;
case CityCategoryModel::tqwl:
$url = '/portal/region/getFutureDetail';
break;
case CityCategoryModel::qlxc:
$url = '/portal/enjoy/getEnjoyDetail';
break;
case CityCategoryModel::sjmy:
$url = '/portal/enjoy/getEnjoyDetail';
break;
case CityCategoryModel::stsy:
$url = '/portal/enjoy/getEnjoyDetail';
break;
case CityCategoryModel::hwtt:
$url = '/portal/enjoy/getEnjoyDetail';
break;
case CityCategoryModel::lylx:
$url = '/portal/scout/getTravelDetail';
break;
case CityCategoryModel::ddfw:
$url = '/portal/scout/getSceneryDetail';
break;
case CityCategoryModel::cysj:
$url = '/portal/scout/getSceneryDetail';
break;
case CityCategoryModel::yjyr:
$url = '/portal/scout/getSceneryDetail';
break;
default:
}
return $url;
}
//第三方微信pc登录
public function wx_login(){
$code = $this->request->get('code');
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appkey1.'&secret='.$this->appsecret1.'&code='.$code.'&grant_type=authorization_code';
$res = $this->http_get($url);
$json_arr = json_decode($res,true);
if(!isset($json_arr['access_token'])&&empty($json_arr['access_token'])){
//用户取消登录
$this->redirect('/portal/login/thirdLogin');
}
$token = $json_arr['access_token'];
$openid = $json_arr['openid'];
//通过access_token获取用户信息
$url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid;
$res1 = $this->http_get($url1);
$info = json_decode($res1,true);
//查询该微信用户是否存在
$where = ['wb_id'=>$info['openid'],'source'=>'微信'];
$user = $this->findThird($where);
//获取微博id,昵称,头像
$userModel = new UserModel();
$ip = get_client_ip();
$users['last_login_time'] = time();
$users['last_login_ip'] = $ip;
if($user){
$users['user_nickname'] = $info['nickname'];
$users['avatar'] = $info['headimgurl'];
$userModel->where(['wb_id'=>$info['openid'],'source'=>'微信'])->update($users);
}else{
$users['wb_id'] = $info['openid'];
$users['user_nickname'] = $info['nickname'];
$users['avatar'] = $info['headimgurl'];
$users['source'] = '微信';
$users['user_type'] = 2;
$users['create_time'] = time();
$userModel->create($users);
}
$userInfo = $this->findThird($where);
cmf_update_current_user($userInfo);
$this->redirect('/');
}
//第三方微信移动端网页登录
public function wx_login_mobile(){
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appkey2.'&secret='.$this->appsecret2;
$res = $this->http_get($url);
$json_arr = json_decode($res,true);
if(!isset($json_arr['access_token'])&&empty($json_arr['access_token'])){
//用户取消登录
$this->redirect('/portal/login/thirdLogin');
}
$token = $json_arr['access_token'];
$openid = 'oYOYl5hbULoKimG5R8Uk-Paha0d8';
//通过access_token获取用户信息
$url1 = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
$res1 = $this->http_get($url1);
$info = json_decode($res1,true);
var_dump($info);exit;
}
//第三方微博登录
public function wb_login(){
$code = $this->request->get('code');
$url = 'https://api.weibo.com/oauth2/access_token';
//要传的数据
$data = [
'client_id' => $this->appkey,
'client_secret'=>$this->appsecret,
'grant_type'=>'authorization_code',
'code'=>$code,
'redirect_uri'=>$this->redirect_uri //回调地址
];
$res = $this->http_post($url,$data);
$json_arr = json_decode($res,true);
//获取access_token
if(isset($json_arr['error_code'])&&!empty($json_arr['error_code'])){
//用户取消登录
$this->redirect('/portal/login/thirdLogin');
}
$token = $json_arr['access_token'];
//存token到session
session('token', $token);
$uid = $json_arr['uid'];
//发送get请求,获取登陆用户的信息
$info = $this->http_get('https://api.weibo.com/2/users/show.json?access_token='.$token.'&uid='.$uid);
$info = json_decode($info,true);
//查询该微博用户是否存在
$where = ['wb_id'=>$info['id'],'source'=>'微博'];
$user = $this->findThird($where);
//获取微博id,昵称,头像
$userModel = new UserModel();
$ip = get_client_ip();
$users['last_login_time'] = time();
$users['last_login_ip'] = $ip;
if($user){
$users['user_nickname'] = $info['screen_name'];
$users['avatar'] = $info['profile_image_url'];
$userModel->where(['wb_id'=>$info['id'],'source'=>'微博'])->update($users);
}else{
$users['wb_id'] = $info['id'];
$users['user_nickname'] = $info['screen_name'];
$users['avatar'] = $info['profile_image_url'];
$users['source'] = '微博';
$users['user_type'] = 2;
$users['create_time'] = time();
$userModel->create($users);
}
$userInfo = $this->findThird($where);
cmf_update_current_user($userInfo);
$this->redirect('/');
}
//微博分享
public function wb_share(){
$login = cmf_is_user_login();
if($login) {
$token = session('token');
$title = $this->request->post('title');//分享标题
$share_url = $this->request->post('share_url');//分享url
$article_id = $this->request->post('id');//分享文章id
$url = 'https://api.weibo.com/2/statuses/share.json';
$data = [
'access_token' => $token,
'status' => $title . " " . $share_url
];
$res = $this->http_post($url, $data);
$json_arr = json_decode($res, true);
if (isset($json_arr['error_code']) && !empty($json_arr['error_code'])) {
$this->apiResponse(0, $json_arr['error']);
}
$postModel = new PortalPostModel();
$postModel->where('id', $article_id)->setInc('post_share_wb', 1);
$this->apiResponse(1, '分享成功!');
}else{
$this->apiResponse(0, '请使用微博登录后操作!');
}
}
//取消授权
public function wb_cancel(){
$this->redirect('/');
}
//查询第三方用户是否存在
public function findThird($where){
$info = Db::name('user')
->where($where)
->find();
return $info;
}
//获取微信分享配置信息
public function wxShare($url=''){
$jsapiTicket = $this->getSignature();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
if($url === '') {
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
$timestamp = time();
$nonceStr = $this->createNonceStr();
$string = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'×tamp='.$timestamp.'&url='.$url;
$signature = sha1($string);
$data = [
"appId" => $this->appkey2,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
];
$this->assign('data',$data);
return $this->fetch();
}
//获取微信分享签名随机字符串
public function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
//获取access_token
public function getWxAccessToken(){
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appkey2.'&secret='.$this->appsecret2;
$res = $this->http_get($url);
$json_arr = json_decode($res,true);
$token = $json_arr['access_token'];
return $token;
}
//获取微信分享签名
public function getSignature(){
if(isset($_SESSION['ticket_expire_time']) && $_SESSION['ticket_expire_time'] > time() && $_SESSION['ticket']){
$ticket = $_SESSION['ticket'];
}else{
$token = $this->getWxAccessToken();
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi';
$res = $this->http_get($url);
$json_arr = json_decode($res,true);
$ticket = $json_arr['ticket'];
$_SESSION['ticket'] = $ticket;
$_SESSION['ticket_expire_time'] = time()+7000;
}
return $ticket;
}
//curl get请求
public function http_get($url){
$curl = curl_init();//启动一个CURL会话
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, false);//不开启header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
$result = curl_exec($curl); //执行操作
curl_close($curl);
return $result;
}
//curl post请求
public function http_post($url,$data){
$curl = curl_init();//启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, false); // 开启header
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//请求头部
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
$result = curl_exec($curl); //执行操作
curl_close($curl);
return $result;
}
}