miduo_login/src/main/java/com/ljsd/controller/GetUserController.java

283 lines
10 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.ljsd.controller;
import com.alibaba.fastjson.JSONObject;
import com.ljsd.redis.RedisKey;
import com.ljsd.redis.RedisUtil;
import com.ljsd.util.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class GetUserController extends HttpServlet {
private final static String _COLLECTION_NAME = "user_info";
private static final Logger LOGGER = LoggerFactory.getLogger(GetUserController.class);
public static int isTestLan=0;
public static void initLanState(){
Properties properties = BaseGlobal.getInstance().properties;
isTestLan = Integer.parseInt(properties.getProperty("isTestLan"));
}
public GetUserController() {
super();
}
public void destroy() {
super.destroy();
}
/**
* openId 账号id
* version
* serverId
* token
* platform android、ios 3 跳过验证
* admin
* gid pid
*
*
*---verty--
* openid 和token校验
*
* ---return--
*
* uidopenid + serverid + platid
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String openId = request.getParameter("openId");
if (openId == null || openId.isEmpty()) {
response.sendError(400, "openId is empety");
return;
}
try {
String banInfo = BaseGlobal.getInstance().redisApp.get(RedisKey.Ban_Open_Id, openId, String.class, -1);
if (banInfo != null) {
String[] split = banInfo.split("\\|");
long currentTimeMillis = System.currentTimeMillis();
if (Long.parseLong(split[0]) > currentTimeMillis) {
DBObject res = new BasicDBObject();
res.put("errorCode", -1);
res.put("reason", banInfo);
PrintWriter out = response.getWriter();
out.print(res);
out.flush();
out.close();
LOGGER.info("doGet can not login Ban_Open_Id=>{} openId=>{} banInfo==null ? {}", RedisKey.Ban_Open_Id, openId, banInfo==null ? null : banInfo);
return;
} else {
BaseGlobal.getInstance().redisApp.del(RedisKey.Ban_Open_Id, openId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
String version = request.getParameter("version");
if (version == null) {
version="未知版本号";
}
String serverId = request.getParameter("serverId");
if (serverId == null || serverId.isEmpty()) {
response.sendError(400, "serverId is empety");
return;
}
String token = request.getParameter("token");
if (token == null || token.isEmpty()) {
response.sendError(400, "token is empety");
return;
}
String platform = request.getParameter("platform"); //平台类型
if (platform == null || platform.isEmpty()) {
response.sendError(400, "platform is empety");
return;
}
String admin = request.getParameter("admin"); //平台类型
String gid = request.getParameter("gid"); //gid
String pid = request.getParameter("pid"); //pid
/*if (StringUtils.checkIsEmpty(admin)) {
response.sendError(400, "platform is empety");
return;
}*/
LOGGER.info("the opendId = {},token={},platform={} admin=>{}",openId,token,platform,admin);
try {
boolean vertify = vertify(response, request, admin, platform, pid, openId, token);
if(!vertify){
return;
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
DBObject dbObject = new BasicDBObject();
dbObject.put("openId", openId);
dbObject.put("serverId", serverId);
dbObject.put("platform", platform);
int uid = 0;
List<DBObject> userInfos = BaseGlobal.getInstance().mongoDBPool.find(_COLLECTION_NAME, dbObject);
DBObject res = new BasicDBObject();
if (userInfos.size() == 0) {
uid = BaseGlobal.getInstance().mongoDBPool.inc("uid") + 10000000;
dbObject.put("uid", uid);
dbObject.put("_id", uid);
userInfos.add(dbObject);
if (gid != null && !gid.isEmpty()) {
dbObject.put("gid", gid);
}
if (pid != null && !pid.isEmpty()) {
dbObject.put("pid", pid);
}
BaseGlobal.getInstance().mongoDBPool.save(_COLLECTION_NAME, dbObject);
}
Random random = new Random();
int utoken = Math.abs(random.nextInt());
uid = (int) userInfos.get(0).get("uid");
res.put("uid", uid);
res.put("token", utoken);
res.put("errorCode", 0);
BaseGlobal.getInstance().redisApp.set(RedisKey.TOKEN, String.valueOf(uid), utoken, -1, false);
BaseGlobal.getInstance().redisApp.set(RedisKey.PIDGIDTEMP, String.valueOf(uid), pid+"#"+gid, -1, false);
PrintWriter out = response.getWriter();
out.print(res);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean vertify(HttpServletResponse response,HttpServletRequest request,String admin,String platform,String pid,String openId,String token){
try {
if(!KTSDKConstans.appsecret.equals(admin)) {
if (isTestLan == 1) { //test
boolean result = loginVerfifyByTestLan(openId, token);
if (!result) {
response.sendError(400, "verify fail");
LOGGER.error("test verify fail");
return false;
}
} else if (!"3".equals(platform)) {//正式 切不是pc
String sub_channel = request.getParameter("sub_channel");
boolean result = false;
if (sub_channel != null && !sub_channel.equals("")) {
if (sub_channel.equals("1000")) {
result = loginVerfify("MHT", openId, token, MHTSDKConstans.rhappid);
} else {
result = loginVerfify("MHT", openId, token, MHTSDKConstans.rhappidOnline);
}
}
if (!result) {
response.sendError(400, "verify fail");
LOGGER.error("verify fail");
return false;
}
}
}
// else {
// boolean result = loginVerfifyByTestLan(openId, token);
// if (!result) {
// response.sendError(400, "verify fail");
// LOGGER.error("test verify fail");
// return false;
// }
// }
}catch (Exception e){
e.printStackTrace();
}
return true;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public static boolean loginVerfify(String channelName,String openId,String token,String appId){
try{
String loginUrl = MHTSDKConstans.loginVerify;
Map<String, String> params = new HashMap<>();
params.put("sid", token);
params.put("appid", appId);
params.put("channellevel1", channelName);
String sign = getSign(getParamString(params), appId, MHTSDKConstans.secretKey);
params.put("sign", sign);
// loginUrl+"?"+"sid="+params.get("sid")+"&appid="+
String loginResult = HttpUtils.doPost(loginUrl,params);
if(loginResult == null || loginResult.isEmpty()){
return false;
}
return parseLoginResult(loginResult);
}catch(Exception e){
return false;
}
}
public static boolean loginVerfifyByTestLan(String openId,String token) throws Exception {
String tokenInRedis = BaseGlobal.getInstance().redisApp.get(RedisKey.LOGIN_TOKEN, openId, String.class, -1);
LOGGER.info("loginVerfifyByTestLan tokenInRedis={} client=>{}",tokenInRedis, token);
return token.equals(tokenInRedis);
}
private static boolean parseLoginResult(String orderResult){
try {
JSONObject jsonObject = JSONObject.parseObject(orderResult);
int state = jsonObject.getIntValue("code");
if(state != 200){
String content = jsonObject.getString("message");
LOGGER.info("parseLoginResult content={}",content);
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 构建签名
* sign=md5hex(paramString+md5hex(appid)+md5hex(secret))
* @return
*/
private static String getSign(String paramString,String appid,String secret){
return MD5Util.encrypByMd5(paramString + MD5Util.encrypByMd5(appid) + MD5Util.encrypByMd5(secret));
}
private static String getParamString(Map<String,String> param){
StringBuilder builder = new StringBuilder();
param.forEach((k,v)->{
if(builder.length()>0){
builder.append("&");
}
builder.append(k).append("=").append(v);
});
return builder.toString();
}
public static void main(String[] args) {
// boolean mht = loginVerfify("MHT", "2318137", "be385683efe228aadac0c8b5822a6fba");
}
}