重写登录优化

master
ELF 5 years ago
parent ef1518566a
commit 8c2e9ee179

@ -1,198 +1,148 @@
<?php
namespace Base\Service;
use Base\Tool\TaskClient;
use Think\Log;
use Base\Tool\Redis;
/**
*
* @todo 未完成
*/
class UserService
{
public function isBan($ip, $deviceNum)
{
$ban = M('device_bans','tab_')->select(['id'])->where(['tag' => ['in', [$ip, $deviceNum]]])->limit(1)->find();
if (empty($ban)) {
return false;
}
return true;
}
public function login()
public function loginSdk($params)
{
#获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
$user = json_decode(base64_decode(file_get_contents("php://input")), true);
#判断数据是否为空
if (empty($user)) {
$this -> set_message(1001, "fail", "登录数据不能为空");
if ($this->loginLimit($params)) {
$this->resetLoginLimit();
return ['status' => false, 'message' => '登录人数过多,请稍后再试'];
}
$account = $params['account'];
$password = $params['password'];
$gameId = $params['game_id'];
$account = $params['account'] ?? '';
$password = $params['password'] ?? '';
$gameId = $params['game_id'] ?? 0;
$sdkVersion = $params['sdk_version'];
$deviceNum = $params['unique_code'];
$ip = get_client_ip();
if ($this->isBan($ip, $user['unique_code'])) {
$this->set_message(1004, "fail", "设备已被禁用");
}
$deviceNum = $params['unique_code'] ?? '';
$clientIp = get_client_ip();
$game = M('game', 'tab_')->where(['game_id' => $gameId])->find();
$user = M('user', 'tab_')->where(['account' => $account])->find();
if (empty($user)) {
$this->set_message(1005, "fail", "账号或密码错误");
$result = $this->doLogin($account, $password, $game, ['client_ip' => $clientIp, 'device_num' => $deviceNum]);
if (!$result['status']) {
$this->resetLoginLimit();
return ['status' => false, 'message' => $result['message']];
}
$user = $result['data']['user'];
$userApi = new MemberApi();
$result = $userApi->login_sdk($account, $password, 1, $gameId, $game['game_name'], $sdkVersion, $deviceNum);
$noticeCount = $this->getNoticeCount();
$this->addUserPlay($user, $game, $clientIp);
$res_msg = array();
switch ($result) {
case - 1:
// $log['remarks'] = '扶持号被禁用';
// log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
case - 2:
// $log['remarks'] = '密码错误';
// log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
default:
if (is_array($result)) {
$user["user_id"] = $result['user_id'];
$user['puid'] = 0;
$this -> add_user_play($user);
$platform = $this -> get_platform($user['user_id']);
$small_list = $this -> small_list($user['user_id'], $user['game_id']);
$small_list[] = array('is_platform' => $platform, 'user_id' => $user['user_id'], 'account' => $user['account'], 'user_account' => $user['account']);
$user_res = M('User', 'tab_') -> where(['account' => $user['account']]) -> find();
$unread_count = 0;
$time = time();
$notice = M('notice', 'tab_')->where('start_time < ' . $time . ' AND game_id = ' . $user['game_id']. ' AND (end_time = 0 OR end_time >' . $time . ')')->getField('id',true);
if(!empty($notice))
{
$unread_count += count($notice);
$where['notice_id'] = ['in', implode(',', $notice)];
$where['user_id'] = $user['user_id'];
$where['is_read'] = 1;
$notice_read_count = M('notice_read', 'tab_')->where($where)->count();
$unread_count -= $notice_read_count;
}
$unread_count += M('share_record', 'tab_') -> where(['invite_id' => $user['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
$unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $user['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
$notice_count = $unread_count;
$buddies_request = get_buddies_unagree_count($user['user_id']);
$unread_count += $buddies_request;
$userToken = $result['user_token'];
$res_msg = array(
"status" => 200,
"return_code" => "success",
"return_msg" => "登录成功",
"user_id" => $user["user_id"],
"account" => $user["account"],
"nickname" => $user_res["nickname"] ? $user_res["nickname"] : $user["account"],
"sex" => $user_res["sex"] ? $user_res["sex"] : 0,
"is_platform" => $platform,
"token" => $result['token'],
"user_token" => $userToken,
"OTP_token" => think_encrypt(json_encode(array('uid' => $user["user_id"], 'time' => time())), 1),
'is_uc' => 0,
"is_open_small_account" => C('IS_OPEN_SMALL_ACCOUNT'),
'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
'small_list' => $small_list,
'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
'android_packagename' => C('WEB_AND_PACKAGENAME'),
'site_status' => C('SDK_SITE_STATUS'),
'head_img' => !empty($user_res['head_img']) ? $user_res['head_img'] : '',
'unread_count' => $unread_count,
'notice_count' => $notice_count,
'request_count' => $buddies_request,
);
// 通知后台 TASK_URLhttp://47.111.118.107:9501
$url = C('TASK_URL')."/game-event/login";
try {
post_async($url, [
'form_params' => [
'game_id' => $user["game_id"],
'user_id' => $user["user_id"],
'login_time' => time()
]
]);
} catch(\Exception $e) {
}
} else {
// $log['remarks'] = '未知错误';
// log_action($log);
$this -> set_message(1028, "fail", "未知错误");
$response = [
'status' => 200,
'return_code' => 'success',
'return_msg' => '登录成功',
'user_id' => $user['id'],
'account' => $user['account'],
'nickname' => $user['nickname'] ? $user['nickname'] : $user['account'],
'sex' => $user['sex'] ? $user['sex'] : 0,
'is_platform' => $user['is_platform'],
'token' => $result['data']['token'],
'user_token' => $result['data']['user_token'],
'OTP_token' => think_encrypt(json_encode(array('uid' => $user['id'], 'time' => time())), 1),
'is_uc' => 0,
'is_open_small_account' => C('IS_OPEN_SMALL_ACCOUNT'),
'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
'small_list' => [],
'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
'android_packagename' => C('WEB_AND_PACKAGENAME'),
'site_status' => C('SDK_SITE_STATUS'),
'head_img' => !empty($user['head_img']) ? $user['head_img'] : '',
'unread_count' => $noticeCount,
'notice_count' => $noticeCount,
'request_count' => 0,
];
}
break;
$this->resetLoginLimit();
return ['status' => true, 'message' => '登录成功', 'data' => $data];
}
protected function isBan($ip, $deviceNum)
{
$ban = M('device_bans','tab_')->select(['id'])->where(['tag' => ['in', [$ip, $deviceNum]]])->limit(1)->find();
if (empty($ban)) {
return false;
}
$log['uid'] = $user['user_id'];
// log_action($log);
echo base64_encode(json_encode($res_msg));
return true;
}
protected function doLogin($user, $game, $clientIp, $deviceNum)
protected function doLogin($account, $password, $game, $params = [])
{
$clientIp = $params['client_ip'] ?? get_client_ip();
$deviceNum = $params['device_num'] ?? '';
if ($this->isBan($clientIp, $deviceNum)) {
return ['status' => false, 'message' => '设备已被禁用'];
}
$user = M('user', 'tab_')->where(['account' => $account])->find();
/* 获取用户数据 */
if (empty($user) || $user['lock_status'] != 1 && $user['check_status'] != 1) {
return null;
return ['status' => false, 'message' => '账号或密码错误'];
}
if (think_ucenter_md5($password, UC_AUTH_KEY) === $user['password']) {
return null;
return ['status' => false, 'message' => '账号或密码错误'];
}
$userData = [];
if (!$user['device_number']) {
$userData['device_number'] = $deviceNum;
}
$testResource = M('test_resource','tab_')->select(['device_number'])->where("user_id=%s and apply_status=2", $user['id'])->find(); //测试资源(扶持号)
$testResource = M('test_resource','tab_')->select(['device_number'])->where('user_id=%s and apply_status=2', $user['id'])->find(); //测试资源(扶持号)
if ($testResource) {
if ($this->isIpWarning($user, $testResource, $deviceNum)) {
$this->ipWarningLog($user, $testResource, $deviceNum);
}
if ($this->isDeviceError($user, $testResource, $deviceNum)) {
$userData['last_device_number'] = $deviceNum;
$userData['lock_status'] = 0 ;
$this->deviceErrorLog($user, $testResource, $deviceNum);
return null;
}
if ($this->isIpWarning($user, $testResource, $deviceNum)) {
$this->ipWarningLog($user, $testResource, $deviceNum);
return ['status' => false, 'message' => '该账号已被禁用'];
}
}
$userData["id"] = $uid;
$userData["login_time"] = NOW_TIME;
$userData["login_ip"] = $clientIp;
$userData["last_login_ip"] = $clientIp;
$userData["last_device_number"] = $deviceNum;
$userData["token"] = $this->generateToken($uid,$account,$password);
$result = $this->getLoginToken($user, $game, $password);
if (!$result) {
return ['status' => false, 'message' => '系统异常'];
}
[$token, $userToken] = $result;
$userData = [];
if (!$user['device_number']) {
$userData['device_number'] = $deviceNum;
}
$userData['login_time'] = NOW_TIME;
$userData['login_ip'] = $clientIp;
$userData['last_login_ip'] = $clientIp;
$userData['last_device_number'] = $deviceNum;
if(!$user['fgame_id']) {
$userData['fgame_id'] = $game['id'];
$userData['fgame_name'] = $game['game_name'];
}
$userData['token'] = $token;
$status = M('user', 'tab_')->where(['id' => $user['id']])->save($userData);
if ($status) {
return ['status' => false, 'message' => '登录异常'];
}
$userToken = 0;
if($testResource) { //扶持号
if($user['device_number'] && $unique_code && $user['device_number'] != $unique_code){ //#当前登录设备信息与历史登录设备信息不一致,触发账户冻结
$this->sdklogin_device_error($user,$test_resource,$unique_code);
$this->sdklogin_ip_error($user,$test_resource,get_client_ip());
return -1;//扶持号被禁用
}else{
$token = $this->sdklogin_update($user,$account,$password,$user['fgame_id'],$game_id,$game_name,$unique_code,$userToken); //更新用户登录信息
$this->user_login_record2($user,$type,$game_id,$game_name,$sdk_version);
$this->sdklogin_ip_error($user,$test_resource,get_client_ip());
return array("user_id"=>$user['id'],"token"=>$token, "user_token" => $userToken); //登录成功返回用户ID
}
}else{
$token = $this->sdklogin_update($user,$account,$password,$user['fgame_id'],$game_id,$game_name,$unique_code,$userToken); //更新用户登录信息
$this->user_login_record2($user,$type,$game_id,$game_name,$sdk_version);
return array("user_id"=>$user['id'],"token"=>$token, "user_token" => $userToken); //登录成功返回用户ID
$this->addUserLoginRecord($user, $game, $clientIp, $deviceNum);
$this->addGameUserLoginRecord($user, $game, $clientIp, $deviceNum);
if (!$user['device_type']) {
$this->oaDeviceTypeUpdate($user, $game);
}
$data = [
'user' => $user,
'token' => $token,
'user_token' => $userToken,
];
return ['status' => true, 'message' => '登录异常', 'data' => $data];
}
protected function isDeviceError($user, $testResource, $deviceNum)
@ -215,15 +165,15 @@ class UserService
$data['promote_id'] = $testResource['promote_id'];
$data['promote_account'] = $testResource['promote_account'];
$data['type'] = 2;
$data['detail'] = "登录设备号异常,本次异常设备号:" . $deviceNum . ",历史登录设备号:" . $user['device_number'];
$data['detail'] = '登录设备号异常,本次异常设备号:' . $deviceNum . ',历史登录设备号:' . $user['device_number'];
$data['create_time'] = NOW_TIME;
M('protect_log','tab_')->add($data);
}
protected function isIpWarning($user, $testResource, $deviceNum)
{
$newResult = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$clientIp);
$oldResult = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$user['login_ip']);
$newResult = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$clientIp);
$oldResult = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$user['login_ip']);
$newResult = json_decode($newResult, true);
$oldResult = json_decode($oldResult, true);
if($newResult['data']['city'] != $oldResult['data']['city']) {
@ -245,7 +195,7 @@ class UserService
$data['promote_id'] = $testResource['promote_id'];
$data['promote_account'] =$testResource['promote_account'];
$data['type'] = 1;
$data['detail'] = "登录IP异常本次异常IP" . $clientIp . "历史登录IP" . $user['login_ip'];
$data['detail'] = '登录IP异常本次异常IP' . $clientIp . '历史登录IP' . $user['login_ip'];
$data['create_time'] = NOW_TIME;
M('protect_log','tab_')->add($data);
}
@ -256,112 +206,80 @@ class UserService
return $token;
}
protected function sdklogin_update($user, $account, $password, $user_fgame_id, $game_id, $game_name, $unique_code='', &$userToken=''){
$model = M('User','tab_');
$uid = $user['id'];
$data["id"] = $uid;
$data["login_time"] = NOW_TIME;
$data["login_ip"] = get_client_ip();
// $data["device_number"] = $unique_code;
$data["last_login_ip"] = $user['login_ip'];
$data["last_device_number"] = $user['device_number'] ? $user['device_number'] : '';
$data["token"] = $this->generateToken($uid,$account,$password);
M('user_token','tab_')->startTrans();
$userToken = $this->generateToken($uid,$account,$password).uniqid().rand(1000, 9999);
$relationGameId = M('game', 'tab_')->where([
'id' => $game_id
])->getField('relation_game_id');
$userTokens = M('user_token','tab_')->where([
'user_id' => $uid,
'game_id' => $game_id
])->find();
if (!$userTokens) {
$r = M('user_token', 'tab_')->add([
'user_id' => $uid,
'game_id' => $game_id,
'relation_game_id' => $relationGameId,
protected function getLoginToken($user, $game, $password)
{
$token = $this->generateToken($user['id'], $user['account'], $password);
$userToken = $this->generateToken($user['id'], $user['account'], $password) . uniqid() . rand(1000, 9999);
$record = M('user_token','tab_')->where(['user_id' => $user['id'], 'game_id' => $game['id']])->find();
if (!$record) {
M('user_token', 'tab_')->add([
'user_id' => $user['id'],
'game_id' => $game['id'],
'relation_game_id' => $game['relation_game_id'],
'user_token' => $userToken,
'login_cnt' => 1,
'create_time' => time(),
'update_time' => time()
]);
if (!$r) {
M('user_token','tab_')->rollback();
$msg = array(
"status" => 5,
"return_code" => 5,
"return_msg" => "数据出错",
"msg" => '1'
);
echo base64_encode(json_encode($msg));
exit();
}
$r = M('user_token', 'tab_')->where([
'user_id' => $uid,
'relation_game_id' => $relationGameId
]);
M('user_token', 'tab_')->where([
'user_id' => $user['id'],
'relation_game_id' => $game['relation_game_id']
])->save([
'user_token' => $userToken,
'login_cnt' => $userTokens['login_cnt'] + 1,
'login_cnt' => $record['login_cnt'] + 1,
'update_time' => time()
]);
if ($r === false) {
M('user_token','tab_')->rollback();
$msg = array(
"status" => 5,
"return_code" => 5,
"return_msg" => "数据出错2",
"msg" => '1'
);
echo base64_encode(json_encode($msg));
exit();
}
} else {
$r = M('user_token', 'tab_')->where([
M('user_token', 'tab_')->where([
'user_id' => $uid,
'game_id|relation_game_id' => $relationGameId
'game_id|relation_game_id' => $game['relation_game_id']
])->save([
'user_token' => $userToken,
'login_cnt' => $userTokens['login_cnt'] + 1,
'login_cnt' => $record['login_cnt'] + 1,
'update_time' => time()
]);
if ($r === false) {
M('user_token','tab_')->rollback();
exit();
}
}
M('user_token','tab_')->commit();
if($user_fgame_id){
$model->save($data);
}else{
$data['fgame_id']=$game_id;
$data['fgame_name']=$game_name;
$model->save($data);
$device_type = M('User','tab_')->where(['id' => $user['id']])->getField('device_type');
if(empty($device_type)){
$gameServer = substr($game_name, -10, 9);
if($gameServer == '安卓版'){
$arr['device_type'] = 'Android';
} elseif($gameServer == '苹果版') {
$arr['device_type'] = 'IOS';
}
$arr['time'] = time();
$arr['account'] = $account;
ksort($arr);
reset($arr);
$sign = md5(http_build_query($arr) . C('GET_INFO_KEY'));
$arr['sign'] = $sign;
$reData = curl_post('http://oa.76ba.com/api/wanmeng/deviceTypeUpdate',$arr);
}
return [$token, $userToken];
}
public function oaDeviceTypeUpdate($user, $game)
{
$gameServer = substr($game['game_name'], -10, 9);
if($gameServer == '安卓版'){
$arr['device_type'] = 'Android';
} elseif($gameServer == '苹果版') {
$arr['device_type'] = 'IOS';
}
return $data["token"];
$arr['time'] = time();
$arr['account'] = $user['account'];
ksort($arr);
reset($arr);
$sign = md5(http_build_query($arr) . C('GET_INFO_KEY'));
$arr['sign'] = $sign;
$reData = curl_post('http://oa.76ba.com/api/wanmeng/deviceTypeUpdate', $arr);
}
protected function addUserLoginRecord($user, $game, $clientIp, $deviceNum){
$data = [
'user_id' => $user['id'],
'user_account' => $user['account'],
'user_nickname' => $user['nickname'],
'game_id' => $game['id'],
'promote_id' => $user['promote_id'],
'game_name' => $game['game_name'],
'sdk_version' => $game['sdk_version'],
'type' => 1,
'server_id' => null,
'server_name' => null,
'login_time' => NOW_TIME,
'login_ip' => $clientIp,
'lpuid' => $user['puid'],
];
return M('user_login_record','tab_')->add($data);
}
public function saveUserGameLoginRecord($user, $game, $clientIp, $deviceNum){
protected function addUserGameLoginRecord($user, $game, $clientIp, $deviceNum){
$data = [
'user_id' => $user['id'],
'user_account' => $user['account'],
@ -379,4 +297,91 @@ class UserService
];
return M('user_game_login_record','tab_')->add($data);
}
protected function dispatchLoginEvent($params)
{
try {
$client = new TaskClient();
$client->post('/game-event/login', $params);
} catch(\Exception $e) {
}
}
protected function addUserPlay($user, $game, $clientIp)
{
$user_play = M('user_play', 'tab_');
$map['game_id'] = $game['id'];
$map['user_id'] = $user['id'];
$map['sdk_version'] = $game['sdk_version'];
$userPlay = M('user_play', 'tab_')->where($map)->find();
if (empty($userPlay)) {
$data = [];
$data['user_id'] = $user['user_id'];
$data['user_account'] = $user['account'];
$data['user_nickname'] = $user['nickname'];
$data['game_id'] = $user['game_id'];
$data['game_appid'] = $user['game_appid'];
$data['game_name'] = $game['game_name'];
$data['server_id'] = 0;
$data['server_name'] = '';
$data['role_id'] = 0;
$data['parent_id'] = $user['parent_id'];
$data['parent_name'] = $user['parent_name'];
$data['role_name'] = '';
$data['role_level'] = 0;
$data['bind_balance'] = 0;
$data['promote_id'] = $user['promote_id'];
$data['promote_account'] = $user['promote_account'];
$data['play_time'] = time();
$data['play_ip'] = $clientIp;
$data['sdk_version'] = $game['sdk_version'];
$data['ppuid'] = $user['puid'] == '' ? 0 : $user['puid'];
$data['check_time'] = time();
$data['create_time'] = time();
$userPlay->add($data);
}
}
protected function getNoticeCount()
{
$noticeCount = 0;
$time = time();
$noticeIds = M('notice', 'tab_')
->where('start_time < ' . $time . ' AND game_id = ' . $user['game_id']. ' AND (end_time = 0 OR end_time >' . $time . ')')
->getField('id',true);
if(!empty($noticeIds))
{
$noticeCount += count($noticeIds);
$where['notice_id'] = ['in', implode(',', $noticeIds)];
$where['user_id'] = $user['id'];
$where['is_read'] = 1;
$noticeReadCount = M('notice_read', 'tab_')->where($where)->count();
$noticeCount -= $noticeReadCount;
}
return $noticeCount;
}
protected function loginLimit($params)
{
$isLoginLimit = intval(C('LOGIN_LIMIT_OPEN', null, 1));
if ($isLoginLimit == 0) {
return false;
}
$loginLimitNum = C('LOGIN_LIMIT_NUM', null, 300);
$count = Redis::incr(Redis::KEY_LOGIN_LIMIT);
if ($count >= $loginLimitNum) {
Log::write('login_limit:' . date('Y-m-d H:i:s') . ' ---- ' . $count, 'INFO', '', C('LOG_PATH')."login_limit.log");
return true;
}
return false;
}
protected function resetLoginLimit()
{
$isLoginLimit = intval(C('LOGIN_LIMIT_OPEN', null, 1));
if ($isLoginLimit != 0) {
Redis::decr(Redis::KEY_LOGIN_LIMIT);
}
}
}

@ -14,10 +14,28 @@ use Think\Log;
use Sdk\Model\SmsLogModel;
use Base\Tool\TaskClient;
use Base\Tool\Redis;
use Base\Service\UserService;
class UserController extends BaseController
{
public function user_login_new()
{
$params = json_decode(base64_decode(file_get_contents("php://input")), true);
if (empty($user)) {
$this -> set_message(1001, "fail", "登录数据不能为空");
}
$userService = new UserService();
$result = $userService->loginSdk($params);
if ($result['status']) {
echo base64_encode(json_encode($result['data']));
} else {
$this->set_message(1001, "fail", "登录数据不能为空");
}
}
public function isBan($ip, $deviceNum)
{
$ban = M('device_bans','tab_')->field(['id'])->where(['tag' => ['in', [$ip, $deviceNum]]])->limit(1)->find();

Loading…
Cancel
Save