package com.yc.action.login;
|
|
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSONArray;
|
import com.google.gson.Gson;
|
import com.yc.action.BaseAction;
|
import com.yc.action.grid.GridUtils;
|
import com.yc.api.bean.Gfrom;
|
import com.yc.api.bean.QrScanType;
|
import com.yc.api.bean.attendance.AppSalesSetting;
|
import com.yc.api.controller.QrCodeController;
|
import com.yc.api.service.QrServiceIfc;
|
import com.yc.api.utils.VersionUtils;
|
import com.yc.entity.*;
|
import com.yc.entity.attachment.AttachmentEntity;
|
import com.yc.exception.ApplicationException;
|
import com.yc.exception.CallBackMessage;
|
import com.yc.factory.FactoryBean;
|
import com.yc.factory.InitSystem;
|
import com.yc.jpush.JpushAction;
|
import com.yc.listener.SessionListener;
|
import com.yc.multiData.MultiDataSource;
|
import com.yc.multiData.SpObserver;
|
import com.yc.open.utils.HttpClientUtil;
|
import com.yc.sdk.gaodemap.action.GdMapServiceInit;
|
import com.yc.sdk.gaodemap.api.GdMapService;
|
import com.yc.sdk.gaodemap.entity.GdErrorException;
|
import com.yc.sdk.gaodemap.entity.RegeoCodeEntity;
|
import com.yc.sdk.password.action.ChangePassword;
|
import com.yc.sdk.shopping.action.api.InvitationCode;
|
import com.yc.sdk.shopping.util.SettingKey;
|
import com.yc.sdk.weixinmp.util.UserAgentUtil;
|
import com.yc.sdk.weixinopen.entity.OpenComponentAppSetting;
|
import com.yc.service.BaseService;
|
import com.yc.service.demo.DemoIfc;
|
import com.yc.service.role.RoleIfc;
|
import com.yc.service.upload.AttachmentIfc;
|
import com.yc.service.user.LoginRecordIfc;
|
import com.yc.service.user.UserAccountServiceIfc;
|
import com.yc.utils.*;
|
import eu.bitwalker.useragentutils.UserAgent;
|
import me.chanjar.weixin.common.util.http.URIUtil;
|
import org.apache.commons.lang.StringUtils;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.util.EntityUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.dao.DataAccessException;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
import org.springframework.stereotype.Controller;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpSession;
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.PrintWriter;
|
import java.text.SimpleDateFormat;
|
import java.util.*;
|
import java.util.concurrent.TimeUnit;
|
import java.util.stream.Collectors;
|
|
//@Scope("request")
|
@Controller
|
public class LoginAction extends BaseAction {
|
@Autowired
|
private UserAccountServiceIfc userAccountService;
|
@Autowired
|
private LoginRecordIfc record;
|
@Autowired
|
private RoleIfc rIfc;
|
@Autowired
|
private DemoIfc demoIfc;
|
@Autowired
|
ThreadPoolTaskExecutor threadPoolExecutor;
|
final Logger log = LoggerFactory.getLogger(this.getClass());
|
private static String attachment_server = AttachmentConfig.get("attachment.server");
|
;
|
|
private int prossSN(String cltsn) {
|
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
|
try {
|
SpObserver.setDBtoDemo();
|
list = demoIfc.getInfoByCltSn(cltsn);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
int r = 0;
|
if (list != null && list.size() > 0) {
|
r = 1;
|
}
|
return r;
|
}
|
|
@RequestMapping("/login.do")
|
public String login(HttpServletRequest request, HttpServletResponse response) {
|
String userCode = request.getParameter("account");
|
if (userCode == null || "".equals(userCode)) {
|
userCode = (request.getAttribute("account") == null ? "" : (String) request.getAttribute("account"));
|
}
|
String password = request.getParameter("pwd");
|
if (password == null || "".equals(password)) {
|
password = (request.getAttribute("pwd") == null ? "" : (String) request.getAttribute("pwd"));
|
}
|
if (password != null && !"".equals(password)) {
|
password = EncodeUtil.replaceUrlChar(password);
|
}
|
|
String code = request.getParameter("code");
|
if (code == null || "".equals(code)) {
|
code = (request.getAttribute("code") == null ? "" : (String) request.getAttribute("code"));
|
}
|
boolean ch_userid = (request.getAttribute("isch_userid") == null ? false
|
: (Boolean) request.getAttribute("isch_userid"));
|
if (ch_userid)
|
password = "***";// 避开与密码相关
|
String dbId = "";
|
String dataBaseDis = "";
|
String isone = "";
|
Boolean isApp = false;
|
CallBackMessage callBackMessage = new CallBackMessage();
|
if (request.getParameter("isApp") != null || request.getAttribute("isApp") != null) {
|
isApp = true;// 手机app传过来 ;
|
}
|
String redirect = request.getParameter("redirect"); // 登录后重定向页面,Added by Johns Wang, 2016-02-17
|
// 处理通行证的情况
|
StringBuilder sb = new StringBuilder();
|
String cltsn = request.getParameter("cltsn");
|
if (cltsn == null)
|
cltsn = (String) request.getAttribute("cltsn"); // Added by Johns Wang, 2015-12-06。。……。。……..……
|
if (cltsn != null && !"".equalsIgnoreCase(cltsn)) {
|
int k = this.prossSN(cltsn);
|
if (k == 0) {
|
callBackMessage.setError("通行证已失效,请联络服务提供商!");
|
this.printJson(response, callBackMessage.toString());
|
return null;// 验证出错返回'
|
}
|
} else {
|
|
dbId = request.getParameter("dataName");// 数据源id
|
dataBaseDis = request.getParameter(SessionKey.DATABASE_DIS);
|
isone = request.getParameter("isone");// 只有一个数据源的情况
|
if (dbId == null)
|
dbId = (String) request.getAttribute("dataName"); // Added by Johns Wang, 2015-12-06
|
if (dataBaseDis == null)
|
dataBaseDis = (String) request.getAttribute(SessionKey.DATABASE_DIS); // Added by Johns Wang, 2015-12-06
|
|
// 从数据源取 系统名称 dataBaseDis ,added by Johns Wang, 2017-07-02
|
if (dataBaseDis == null) {
|
DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(dbId);
|
if (dataSourceEntity != null) {
|
dataBaseDis = dataSourceEntity.getSystemID();
|
}
|
}
|
|
if (isone == null)
|
isone = (String) request.getAttribute("isone"); // Added by Johns Wang, 2015-12-06
|
}
|
if (userCode != null && userCode.length() > 30) {//解密为明文
|
try {
|
userCode = ChangePassword.getDecryptPassword(EncodeUtil.replaceUrlChar(userCode));
|
} catch (Exception e) {
|
e.printStackTrace();
|
print2(response, this.getErrorMsg(e), redirect, isApp);
|
return null;// 验证出错返回'
|
|
}
|
}
|
HttpSession session = request.getSession();
|
String domain = request.getParameter("domain") != null ? request.getParameter("domain")
|
: (String) request.getAttribute("domain");
|
UserAccountEntity userAccount = null;
|
// -------处理原生APP登录,通过手机号,注册时的密码 by danaus 2018-8-24
|
// 1---有dbid的情况表明是通过选择一个数据源进行登录操作
|
if (VersionUtils.getAPPTypeName(request) != null) {// ios,adnroid调用
|
try {
|
InvitationCode invitationCode = (InvitationCode) FactoryBean.getBean("invitationCode");
|
// userCode代表手机号 (在方法 invitationCode.getDbList() 切换数据源 )
|
|
invitationCode.checkPasswordByTelephone(userCode, password, dbId);
|
// 通过数据源id和手机号取得用户usercode进行登录,这时候不需要密码验证
|
SpObserver.setDBtoInstance("_" + dbId);
|
userAccount = userAccountService.getUserInfoByTelephone(userCode);//userCode 手机号
|
if (userAccount != null) {
|
if(userAccount.isInActive()){
|
print2(response, "【" + userCode + "】手机号码已被停用,禁止登录本系统", redirect, isApp);
|
return null;// 验证出错返回
|
}
|
userAccount.setApp_userCode(userCode);
|
userAccount.setApp_Password(password);
|
userCode = userAccount.getUserCode();//转成ERP的usercode进行登陆
|
password = userAccount.getPassword();//转成ERP的密码进行登陆
|
ch_userid = true;
|
//---处理极光别名绑定过多(>10个)的情况,需要查询绑定数量,超过8个则需要删除最后一个,以保证客户端别名设置没问题
|
this.processJiguangAliases(userCode,dbId);
|
} else {
|
print2(response, "【" + userCode + "】手机号码未开通ERP系统服务,登录失败", redirect, isApp);
|
return null;// 验证出错返回'
|
}
|
} catch (DataAccessException e) {
|
e.printStackTrace();
|
print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), redirect, isApp);
|
return null;
|
} catch (Exception e) {
|
e.printStackTrace();
|
print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), redirect, isApp);
|
return null;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
//这里是短信登录 xin 2020-8-20 11:25:59
|
String phone = request.getParameter("telephone");
|
phone = (phone == null ? "" : phone);
|
String phoneCode = request.getParameter("phoneCode");
|
phoneCode = (phoneCode == null ? "" : phoneCode);
|
if (StringUtils.isBlank(userCode) && !StringUtils.isBlank(phone) && !StringUtils.isBlank(phoneCode)) {
|
try {
|
@SuppressWarnings("rawtypes")
|
RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
if (!redisTemplate.hasKey("CODE:" + phone + ":" + dbId)) {
|
print2(response, "验证码已失效,请重新获取验证码。", redirect, isApp);
|
return null;
|
}
|
if (!phoneCode.equals(redisTemplate.opsForValue().get("CODE:" + phone + ":" + dbId) + "")) {
|
print2(response, "验证码错误,请输入正确的验证码", redirect, isApp);
|
return null;
|
}
|
redisTemplate.delete("CODE:" + phone + ":" + dbId);//删除
|
SpObserver.setDBtoInstance("_" + dbId);
|
userAccount = userAccountService.getUserInfoByTelephone(phone);//phone 手机号
|
if (userAccount != null) {
|
if(userAccount.isInActive()){
|
print2(response, "【" + phone + "】手机号码已被停用,禁止登录本系统", redirect, isApp);
|
return null;// 验证出错返回'
|
}
|
userCode = userAccount.getUserCode();//转成ERP的usercode进行登陆
|
password = userAccount.getPassword();//转成ERP的密码进行登陆
|
} else {
|
print2(response, "【" + phone + "】手机号码未开通ERP系统服务,登录失败", redirect, isApp);
|
return null;// 验证出错返回'
|
}
|
} catch (Exception e) {
|
print2(response, this.getErrorMsg(e), redirect, isApp);
|
return null;// 验证出错返回'
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
//----------------
|
// --------
|
if (StringUtils.isBlank(dbId) && StringUtils.isBlank(isone)) {
|
sb.append("请选择一个系统!\\n");
|
} else {
|
if (!StringUtils.isBlank(isone))
|
dbId = isone;
|
session.setAttribute(SessionKey.DATA_BASE_ID, dbId);
|
session.setAttribute(SessionKey.DATABASE_DIS, dataBaseDis);
|
// 如果domain为空,则取默认的域名 by danaus 2021/4/12 11:18
|
if (org.apache.commons.lang3.StringUtils.isBlank(domain)) {
|
domain = SettingKey.getHostUrl(request);
|
}
|
session.setAttribute(SessionKey.DOMAIN, domain);
|
}
|
if (StringUtils.isBlank(userCode)) {
|
sb.append("账号不能为空\\n");
|
}
|
if (StringUtils.isBlank(password)) {
|
sb.append("密码不能为空\\n");
|
}
|
|
// 判断进行验证码校验*********************
|
boolean isValidateLogin = "true".equals(SystemConfig.getInstanse().get("isEnableValidateCode"));
|
;
|
if (isValidateLogin) {// 是否进行验证码验证
|
if (StringUtils.isBlank(code)) {
|
sb.append("验证码不能为空\\n");
|
} else {
|
String rand = (String) session.getAttribute("rand");// 对照验证码
|
if (!code.equalsIgnoreCase(rand)) {
|
sb.append("验证码不相符\\n");
|
}
|
}
|
}
|
// 判断进行验证码校验*********************
|
|
if (sb.length() > 0) {
|
print2(response, sb.toString(), redirect, isApp);
|
return null;// 验证出错返回'
|
}
|
try {
|
// --------------------
|
|
// 判断是否超出人数限制
|
if (SessionListener.checkUserLimit(request, dbId)) {
|
String s = "当前登录人数已超过系统最大登录人数,如有需要增加登录人数,请联系软件公司";
|
print2(response, s, redirect, isApp);
|
session.invalidate();
|
return null;// 验证出错返回'
|
}
|
// *** start ******* 读取加密锁的授权店铺数
|
|
// int scount=0;
|
// if(session.getAttribute(SessionKey.HAsP_sHOPCOUNT)!=null)
|
// scount=(Integer)session.getAttribute(SessionKey.HAsP_sHOPCOUNT);
|
// if(scount>0){
|
// // by danaus 13-5-4
|
// int shop=record.getShopCount();
|
// if(shop>scount){
|
// this.print(response, "<script>alert('检测到系统店铺数量超出所授权的店铺数量!');window.history.back();</script>");
|
// return null;//验证出错返回'
|
// }
|
// }
|
|
// *** end ***********
|
int recordeCount = 0;
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
recordeCount = record.getRecordCountIn10min(userCode); // 10分钟内不能登录
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
String ip = IPUtil.getIpAddr(request);
|
if (recordeCount >= 5) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
record.loginRecord(userCode, password, ip);// 登录次数过多再行登陆作为登录失败处理
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
print2(response, userCode + "在短时间内登录错误次数过多!请耐心的等10分钟后再登录!", redirect, isApp);
|
return null;// 验证出错返回
|
}
|
// 检查限制用户登录时间和登录IP
|
int s = 0;
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
s = userAccountService.checkUserLoginTimeAndIp(userCode, ip);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (s == 0) {
|
print2(response, "该用户只能在工作时间或固定场所使用本系统[" + ip + "]", redirect, isApp);
|
return null;
|
}
|
//
|
// 设置session
|
try {
|
if (userAccount == null) {
|
SpObserver.setDBtoInstance("_" + dbId);
|
userAccount = userAccountService.getUserInfoByUserCode(userCode);
|
|
if (userAccount == null) {
|
userAccount = userAccountService.getUserInfoByTelephone(userCode); //允许电话登录
|
}
|
|
if (userAccount == null) {
|
userAccount = userAccountService.getUserInfoByEmail(userCode); //允许邮箱号登录
|
}
|
}
|
}catch (Exception e){
|
this.print2(response, this.getErrorMsg(e), request.getParameter("redirect"), isApp);
|
return null;
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (userAccount == null) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
record.loginRecord(userCode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
|
}catch (Exception e){
|
this.print2(response, this.getErrorMsg(e), request.getParameter("redirect"), isApp);
|
return null;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (ch_userid) {
|
return "{\"ch_error\":\"ch_user_error\",\"info\":\"未开通ERP系统服务,登录失败!\"}";
|
} else {
|
this.print2(response, "未开通ERP系统服务,登录失败!", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
}
|
try {
|
if (!ch_userid && !userAccount.checkPassword(password)) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
record.loginRecord(userCode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
|
}catch (Exception e){
|
this.print2(response, this.getErrorMsg(e), request.getParameter("redirect"), isApp);
|
return null;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
this.print2(response, "用户密码不正确!", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
} catch (Exception ex) {
|
this.print2(response, ex.getMessage(), request.getParameter("redirect"), isApp);
|
return null;
|
}
|
// 判断用户登录时是否禁用
|
if (userAccount.isInActive()) {
|
this.print2(response, "用户账号已禁止登录!如有问题,请联系管理员", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
if (isApp) {
|
session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_APP);//app 类型
|
} else if (redirect != null && !"".equals(redirect)) { // 增加登录后重定向页面功能,added by Johns Wang, 2016-02-17
|
session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_MINIAPP);//miniapp 类型
|
} else {
|
session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_WEB);//web 类型
|
}
|
processLoginUserToSessionV2(ip, dbId, request, userAccount);
|
// --------------
|
// String ucode = account + Math.random();// 是为了区分用户重复问题,同一用户可以多人使用。
|
// session.setAttribute(SessionKey.SAIL_USERCODE, ucode);
|
// OnLineUser.setOnlineUser(dataString, ucode, session);
|
/*
|
* WebApplicationContext webApplicationContext =
|
* ContextLoader.getCurrentWebApplicationContext(); ServletContext
|
* servletContext =
|
* webApplicationContext.getServletContext();//取得ServletContext对象实例
|
* if((OnLineUser)servletContext.getAttribute("onlineuserlistener")==null) {
|
* OnLineUser onuser=new
|
* OnLineUser();//只设置一次,不同于上面日志文件的记录每次会话均设置。即当第一个客户连接到服务器时启动一个全局变量,
|
* 此后所有的客户将使用相同的上下文。 servletContext.setAttribute("onlineuserlistener",onuser);//
|
* 将监听器对象设置成ServletContext的属性,具有全局范围有效性,即所有的客户均可以取得它的实例。 }
|
* session.setAttribute("onlineuserlistener",(OnLineUser)servletContext.
|
* getAttribute("onlineuserlistener"));//取出此全局对象,并且将此对象绑定到某个会话中,
|
* 此举将促使监听器调用valueBound,计数器加一。
|
*/
|
// session.setAttribute(SessionKey.ONLINE_USERS, new OnLineUser());// 在线人数统计
|
// ------------------
|
if (isApp) {
|
QrServiceIfc qrServiceIfc = (QrServiceIfc) FactoryBean.getBean("qrService");
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
AppSalesSetting appSalesSetting = qrServiceIfc.getAppSalesOrderStyle();
|
//加到会话
|
session.setAttribute(SessionKey.APP_SALESORDER_MATCODE_LIST, appSalesSetting.getAppSalesOrderMatCodeList());
|
session.setAttribute(SessionKey.APP_SALESORDER_STYLE, appSalesSetting.getAppSalesOrderStyle());
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
Map<String, Object> map = new HashMap<String, Object>();
|
map.put("success", "ok");
|
map.put("sessionid", session.getId());
|
map.put("userName", userAccount.getUserName());
|
String avatarUnid = "";
|
if (userAccount.getAvatarUnid() != null && !"".equals(userAccount.getAvatarUnid())) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
|
String[] unids = userAccount.getAvatarUnid().split(";");
|
final AttachmentEntity attachmentEntity = attachmentIfc.getAttachmentEntity(unids[0], unids[1]);
|
avatarUnid = userAccount.getAvatarUnid() + ";" + attachmentEntity.getFileType();
|
} catch (Exception ex) {
|
callBackMessage.sendErrorMessage(ex.getMessage());
|
this.printJson(response, callBackMessage.toString());
|
return null;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
map.put("avatarUnid", avatarUnid);
|
map.put("attachment_server", attachment_server);
|
map.put("url", domain == null ? "" : domain);
|
if (request.getAttribute("postTokenV2") == null) {
|
map.put("token", genToken(userAccount.getApp_Password(), userAccount.getApp_userCode(), Integer.parseInt(dbId)));
|
}
|
|
//---增加扫码显示方式
|
|
QrScanType qrScanType = null;
|
//显示下单图标
|
int appSalesMenuIcon = 0;
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
qrScanType = qrServiceIfc.getQrScanType(userAccount.getUserCode(), userAccount.getUserName());
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
//---增加是否可以显示下单图标
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
|
List<Gfrom> list = baseService.getJdbcTemplate().query("select a.formid,a.formname from gform a where exists(select 1 from gfield b where a.formid = b.formid and b.fieldid in ( 'matcode','barcode','qrcode') and b.ScanCodeField = 1 )", new BeanPropertyRowMapper<>(Gfrom.class));
|
|
if (list != null && list.size() > 0) {
|
QrCodeController qrCodeController = (QrCodeController) FactoryBean.getBean("qrCodeController");
|
List tempList = qrCodeController.procFormLimit(request, list);
|
if (tempList != null && tempList.size() > 0) {
|
appSalesMenuIcon = 1;
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
map.put("sessionInfo", getSessionInfo(session));
|
map.put("userType", session.getAttribute(SessionKey.USERTYPE));
|
map.put("isStopSystem", session.getAttribute(SessionKey.isStopSystem));
|
map.put("isAdmin", ("SuperUser".equalsIgnoreCase(session.getAttribute(SessionKey.USERTYPE) + "") || "DeveloperUser".equalsIgnoreCase(session.getAttribute(SessionKey.USERTYPE) + "")) ? 1 : 0);//非普通用户都有所有权限
|
final DataSourceEntity dataSourceMap = MultiDataSource.getDataSourceMap(dbId);
|
map.put("isShowAttendance", dataSourceMap.isShowAttendanceButton() ? 1 : 0);//打卡
|
map.put("qrDisplayType", qrScanType.getScanMeterialAction());//扫码显示方式
|
map.put("appSalesMenuIcon", appSalesMenuIcon);//是否显示下单图标,0不显示,1显示
|
map.put("isRelatingMaterialWhenNewCustomer", qrScanType.getIsRelatingMaterialWhenNewCustomer());//是否关联客户
|
OpenComponentAppSetting openComponentAppSetting = OpenComponentAppSetting.defaultSettings();
|
map.put("mobileAppId", openComponentAppSetting == null ? null : openComponentAppSetting.getMobileAppId());//小程序id
|
map.put("mobileAppSecret", openComponentAppSetting == null ? null : openComponentAppSetting.getMobileAppSecret());//小程序MobileAppSecret
|
map.put("miniAppOrgId", dataSourceMap.getMiniAppOrgId());//小程序miniAppOrgId
|
map.put("isModifyPriceWhenScanQrCode", session.getAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE));
|
map.put("isModifyPriceWhenSalesOrder", session.getAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER));
|
map.put("isModifyPriceWhenPurchaseOrder", session.getAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER));
|
map.put("switchToPageWhenLogonApp", session.getAttribute(SessionKey.SWITCHTOPAGEWHENLOGONAPP));
|
map.put("selectNextDocumentWhenApproved", session.getAttribute(SessionKey.SELECTNEXTDOCUMENTWHENAPPROVED));
|
map.put("perssion", session.getAttribute(SessionKey.PERSSION));
|
this.printJson(response, GridUtils.toJson(map));
|
|
return null;
|
} else if (redirect != null && !"".equals(redirect)) { // 增加登录后重定向页面功能,added by Johns Wang, 2016-02-17
|
//return "redirect:" + redirect;
|
callBackMessage.sendSuccessMessage("登录成功");
|
callBackMessage.setData("{\"redirect\":\"" + redirect + "\"}");
|
this.printJson(response, callBackMessage.toString());
|
return null;
|
} else {
|
if (ch_userid)
|
return "{\"ok\":\"ch_user_ok\",\"info\":\"" + userCode + "\"}";
|
else {
|
callBackMessage.sendSuccessMessage("登录成功");
|
this.printJson(response, callBackMessage.toString());
|
return null;
|
}
|
}
|
}catch (IllegalStateException e) {
|
e.printStackTrace();
|
if (e.getMessage()!=null&&e.getMessage().contains("Session already invalidated")) {
|
sb.append("会话已过期,请关闭浏览器再重新登录系统\\n");
|
print2(response, sb.toString(), redirect, isApp);
|
System.out.println(this.getClass() + " sessionid:" + session.getId());
|
return null;// 会话已过期返回
|
} else {
|
e.printStackTrace();
|
print2(response, this.getErrorMsg(e), redirect, isApp);
|
return null;
|
}
|
} catch (DataAccessException e) {
|
e.printStackTrace();
|
//SQLException sql = (SQLException) e.getCause();
|
//return "/403.jsp?info=" + sql.getMessage();
|
this.print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), request.getParameter("redirect"), isApp);
|
return null;
|
} catch (NullPointerException e) {// 不存在此账号
|
e.printStackTrace();
|
proccError(userCode, password, request, response);
|
return null;
|
} catch (RuntimeException e) {
|
e.printStackTrace();
|
if (e.getLocalizedMessage()!=null&&e.getMessage().equals(SessionKey.DEMO_REF)) {
|
session.setAttribute(SessionKey.DEMO_REF, SessionKey.DEMO_REF);
|
this.print(response, "<script>alert('请生成正确的配置信息');window.location.href='/demo/demoList.jsp';</script>");
|
}else{
|
this.print2(response, this.getErrorMsg(e), request.getParameter("redirect"), isApp);
|
}
|
return null;
|
}catch (GdErrorException e) {// 不存在高德地图apiKey
|
e.printStackTrace();
|
this.print2(response, "高德地图KEY不存在,请在数据源里维护好", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
catch (Exception e) {// 不存在此账号
|
e.printStackTrace();
|
proccError(userCode, password, request, response);
|
return null;
|
}
|
}
|
|
private String genToken(String pwd, String usercode, int dbid) {
|
TokenInfo tokenInfo = new TokenInfo();
|
tokenInfo.setUsercode(usercode);
|
tokenInfo.setDbid(dbid);
|
try {
|
String key = "Lg_Token:" + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode();
|
|
RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
Object object = redisTemplate.opsForValue().get(key);
|
//if (object == null) {
|
//不存在则加到redis里,过期时间设置为12小时
|
final int OVERTIME = 12;
|
redisTemplate.opsForValue().set(key, pwd, OVERTIME, TimeUnit.HOURS);
|
//}
|
|
String token = AESUtils.encrypt(GridUtils.toJson(tokenInfo));//dbid+usercode加密返回给APP客户端保存
|
return token;
|
} catch (Exception ex) {
|
ex.printStackTrace();
|
return "";
|
}
|
}
|
|
public boolean processLoginUserToSession(String ip, String dbId, HttpSession session, UserAccountEntity userAccount) throws Exception {
|
// 设置权限
|
PerssionEntity perssionEntity = new PerssionEntity();
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
perssionEntity.setRole(rIfc.getRole(userAccount.getUserCode()));
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
perssionEntity.setPerssion(userAccountService.getUserProfiles(userAccount.getUserCode()));
|
// 保存会话 session信息
|
setSessionValues(dbId, userAccount, session, perssionEntity);
|
// 登录成功清除登录错误信息
|
record.clearLoginRecord(userAccount.getUserCode());
|
|
// 记录登录信息
|
userAccountService.loginLog(userAccount.getUserCode(), userAccount.getUserName(), ip, session.getId());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (userAccount.getDefaultSet() != null && !"".equals(userAccount.getDefaultSet())) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbId);
|
perssionEntity.setDefaultSet(userAccountService.getDefaultSet(userAccount.getDefaultSet()));
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
return true;
|
|
}
|
|
public boolean processLoginUserToSessionV2( String ip, String dbId, HttpServletRequest request, UserAccountEntity userAccount) throws Exception {
|
HttpSession session = request.getSession();
|
// 设置权限
|
try {
|
LoginUserEntity userEntity = new LoginUserEntity();
|
final DataSourceEntity dataSourceMap = MultiDataSource.getDataSourceMap(dbId);
|
userEntity.setDbid(dbId);
|
userEntity.setSystemDescribe(dataSourceMap.getSystemDescribe());
|
userEntity.setLogonDomain(request.getHeader("host"));
|
|
if (request.getParameter("isApp") != null || request.getAttribute("isApp") != null) {
|
// 手机app传过来
|
userEntity.setOSType(request.getHeader("x-app-type"));//ios,android
|
String equipmentCode = request.getHeader("x-app-equipmentCode");
|
userEntity.setEquipmentModel(equipmentCode);//设备型号
|
userEntity.setUserLoginType("app");
|
//--从设备型号提取生产商名称,
|
if (org.apache.commons.lang3.StringUtils.isNotBlank(equipmentCode)) {
|
String[] equipment = equipmentCode.split("\\s+?");//空格分隔,取第一个作为生产商
|
userEntity.setManufacturer(equipment[0]);
|
}
|
|
} else {
|
//pc ,小程序
|
int userLoginType = session.getAttribute(SessionKey.USER_LOGIN_TYPE)==null?1:Integer.parseInt(session.getAttribute(SessionKey.USER_LOGIN_TYPE)+"");
|
if (userLoginType==3) {
|
userEntity.setUserLoginType("minapp");
|
} else {
|
userEntity.setUserLoginType("web");
|
}
|
String userAgentString = UserAgentUtil.getUaInfo(request); // request.getHeader("User-Agent");
|
UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
|
String os = userAgent.getOperatingSystem().getGroup().getName();
|
//String osName = userAgent.getOperatingSystem().getName() ;
|
String manufacturer = userAgent.getOperatingSystem().getManufacturer().getName();
|
String model = UserAgentUtil.getPhoneModel(userAgentString);
|
//String mobileOS = UserAgentUtil.getMobileOS(userAgentString);
|
userEntity.setOSType(os);
|
userEntity.setManufacturer(manufacturer);
|
userEntity.setEquipmentModel(model);
|
userEntity.setUserAgent(userAgentString);
|
}
|
String longitude = request.getHeader("x-app-longitude");
|
String latitude = request.getHeader("x-app-latitude");
|
|
//---通过经纬度,IP 获取地理信息(国,省,市,区)
|
GdMapService gdMapService = GdMapServiceInit.getGdMapService(dataSourceMap.getGeoWebApiKey());
|
|
final RegeoCodeEntity regeo = gdMapService.getRegeoV2(longitude, latitude, ip);
|
if(regeo!=null) {
|
userEntity.setCountryName(regeo.getCountry());
|
userEntity.setProvinceName(regeo.getProvince());
|
userEntity.setCityName(regeo.getCity());
|
userEntity.setCountyName(regeo.getDistrict());
|
}
|
userEntity.setLongitude(longitude);
|
userEntity.setLatitude(latitude);
|
userEntity.setIp(ip);
|
|
PerssionEntity perssionEntity = new PerssionEntity();
|
SpObserver.setDBtoInstance("_" + dbId);
|
perssionEntity.setRole(rIfc.getRole(userAccount.getUserCode()));
|
perssionEntity.setPerssion(userAccountService.getUserProfiles(userAccount.getUserCode()));
|
if (userAccount.getDefaultSet() != null && !"".equals(userAccount.getDefaultSet())) {
|
perssionEntity.setDefaultSet(userAccountService.getDefaultSet(userAccount.getDefaultSet()));
|
}
|
|
// 保存会话 session信息
|
setSessionValues(dbId, userAccount, session, perssionEntity);
|
// 登录成功清除登录错误信息
|
record.clearLoginRecord(userAccount.getUserCode());
|
// 记录登录信息
|
userAccountService.loginLogV2(userAccount, userEntity, session.getId());
|
|
} finally{
|
SpObserver.setDBtoInstance();
|
}
|
return true;
|
// });
|
}
|
|
/**
|
* APP 自动登录接口
|
*
|
* @param request
|
* @param response
|
*/
|
@RequestMapping("/autoLogin.do")
|
public String autoLogin(String token, HttpServletRequest request, HttpServletResponse response) {
|
if (token == null || "".equalsIgnoreCase(token)) {
|
this.printJson(response, "{\"error\":\"token不能为空\"}");
|
return "";
|
}
|
try {
|
String value = AESUtils.decrypt(EncodeUtil.replaceUrlChar(token));//解密
|
Gson gson = new Gson();
|
TokenInfo tokenInfo = gson.fromJson(value, new com.google.gson.reflect.TypeToken<TokenInfo>() {
|
}.getType());
|
|
RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
Object object = redisTemplate.opsForValue().get("Lg_Token:" + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
|
if (object == null) {
|
this.printJson(response, "{\"error\":\"token已失效,请重新登录\"}");
|
return "";
|
}
|
|
String[] tokenStr = ((String) object).split("#");//0是密码,1是随机数
|
//进行登录操作
|
tokenInfo.setPwd(tokenStr[0]);
|
request.setAttribute("account", tokenInfo.getUsercode());
|
request.setAttribute("pwd", tokenInfo.getPwd());
|
request.setAttribute("isApp", "1");
|
request.setAttribute("dataName", tokenInfo.getDbid() + "");
|
request.setAttribute("isone", tokenInfo.getDbid() + "");
|
} catch (Exception ex) {
|
this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
|
return "";
|
}
|
return login(request, response);
|
}
|
|
@RequestMapping("/autoLoginV2.do")
|
/**
|
* by danaus 2020/1/13 9:59
|
*/
|
public String autoLoginV2(String token, HttpServletRequest request, HttpServletResponse response) {
|
CallBackMessage callBackMessage = new CallBackMessage();
|
if (token == null || "".equalsIgnoreCase(token)) {
|
this.printJson(response, callBackMessage.sendErrorMessage("token不能为空", -1));
|
return "";
|
}
|
try {
|
String value = AESUtils.decrypt(EncodeUtil.replaceUrlChar(token));//解密
|
Gson gson = new Gson();
|
TokenInfo tokenInfo = gson.fromJson(value, new com.google.gson.reflect.TypeToken<TokenInfo>() {
|
}.getType());
|
RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
//System.out.println("aaaaaa>>>>"+value);
|
//System.out.println("bbbbb>>>>"+InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
|
Object object = redisTemplate.opsForValue().get(InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
|
//System.out.println("cccc>>>>"+object);
|
if (object == null) {
|
//设置会话失效
|
request.getSession().invalidate();
|
this.printJson(response, callBackMessage.sendErrorMessage("token已失效,请重新登录", -1002));
|
return "";
|
}
|
//405调用需要刷新过期时间
|
if (request.getParameter("refresh") != null && "1".equalsIgnoreCase(request.getParameter("refresh"))) {
|
//刷新key过期时间
|
redisTemplate.opsForValue().getOperations().expire(InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode(), 12, TimeUnit.HOURS);
|
}
|
//验证token合法性,对比随机数
|
String[] tokenStr = ((String) object).split("#");//0是密码,1是随机数 by danaus 2020/9/24 10:18
|
// if (tokenStr[1] == null || "".equals(tokenStr[1]) || tokenInfo.getRand() != Double.parseDouble(tokenStr[1])) {
|
// this.printJson(response, callBackMessage.sendErrorMessage("不是合法的token", -1001));
|
// return null;
|
// }
|
//进行登录操作
|
tokenInfo.setPwd(tokenStr[0]);
|
request.setAttribute("account", tokenInfo.getUsercode());
|
request.setAttribute("pwd", tokenInfo.getPwd());
|
request.setAttribute("isApp", "1");
|
request.setAttribute("dataName", tokenInfo.getDbid() + "");
|
request.setAttribute("isone", tokenInfo.getDbid() + "");
|
request.setAttribute("postTokenV2", "1");//说明是通过V2版提交,之后在登录成功后就不返回token。
|
} catch (Exception ex) {
|
this.printJson(response, callBackMessage.sendErrorMessage(this.getErrorMsg(ex), -1));
|
return "";
|
}
|
return login(request, response);
|
}
|
|
/**
|
* 处理极光别名
|
* 先查询当前别名已绑定的设备数,如果超过8个则删除最后一个别人
|
* @param usercode
|
* @param dbid
|
*/
|
public void processJiguangAliases(String usercode,String dbid){
|
try {
|
//查询别名绑定的设备列表
|
String aliase=dbid+"_"+usercode;
|
String url = JpushAction.URL + "/v3/aliases/"+aliase+"?new_format=true";
|
final HttpGet httpGet = HttpClientUtil.CreateHttpGetByAuthorization(url, null, JpushAction.appKey, JpushAction.masterSecret);
|
CloseableHttpResponse response = HttpClientUtil.getClient().execute(httpGet);
|
if (response.getStatusLine().getStatusCode() == 200) {
|
final Map map = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"), Map.class);
|
|
List<JiGuangAliaseEntity> list= JSON.parseArray(map.get("data") + "",JiGuangAliaseEntity.class);
|
if(list!=null&&list.size()>8){
|
//--处理为只保留最新活跃天数的8个设备
|
StringJoiner joiner=new StringJoiner(",");
|
int index=0;
|
list= list.stream().sorted(Comparator.comparing(JiGuangAliaseEntity::getLast_online_date).reversed()).collect(Collectors.toList());
|
for (JiGuangAliaseEntity entity:list){
|
if(index>8){
|
joiner.add("\""+entity.getRegistration_id()+"\"");
|
}
|
index++;
|
};
|
//---解绑多出来的设备
|
url=JpushAction.URL+"/v3/aliases/"+aliase;
|
String data="{\n" +
|
" \"registration_ids\":{\"remove\": ["+joiner.toString()+"]}\n" +
|
"}";
|
final HttpPost httpPost = HttpClientUtil.CreateHttpPostByAuthorization(url, data, false, JpushAction.appKey, JpushAction.masterSecret);
|
response = HttpClientUtil.getClient().execute(httpPost);
|
if (response.getStatusLine().getStatusCode() !=200) {
|
throw new ApplicationException("删除极光别名关联设备出错:"+response.getStatusLine().getStatusCode()+"["+response.getStatusLine().getReasonPhrase()+"]");
|
}
|
}
|
} else {
|
throw new ApplicationException("获取极光别名出错:" + response.getStatusLine().getStatusCode() + "[" + response.getStatusLine().getReasonPhrase() + "]");
|
}
|
|
}catch (Exception e){
|
System.out.println(e.getCause()==null?e.getMessage():e.getCause().getMessage());
|
}
|
}
|
private void print2(HttpServletResponse response, String sb, String redirect, Boolean isApp) {
|
CallBackMessage callBackMessage = new CallBackMessage();
|
// redirect Added by Johns Wang, 2016-03-06
|
if (redirect != null && !"".equals(redirect)) {
|
redirect = URIUtil.encodeURIComponent(redirect);
|
callBackMessage.setData("{\"redirect\":\"" + redirect + "\"}");
|
}
|
callBackMessage.sendErrorMessage(sb);
|
if (isApp != null && isApp) {
|
if ("密码错误".equalsIgnoreCase(sb)) {
|
//密码不正确 以状态码为-1004返回给app,弹出登录界面
|
callBackMessage.sendErrorMessage(sb, -1004);
|
}
|
this.print(response, callBackMessage.toString());
|
} else {
|
this.print(response, callBackMessage.toString());
|
}
|
// // this.print(response, "<script>
|
// // alert('"+sb+"');window.history.back();</script>");
|
// if (redirect == null || redirect.equals(""))
|
// this.print(response, "<script> alert('" + sb + "');window.history.back();</script>");
|
// else
|
// this.print(response, "<script> alert('" + sb + "');window.location='/login.jsp?redirect=" + redirect
|
// + "';</script>");
|
// }
|
}
|
|
private Map<String, Object> getSessionInfo(HttpSession session) {
|
Map<String, Object> map = new HashMap<String, Object>();
|
map.put(SessionKey.HRCODE.replace("@", ""), session.getAttribute(SessionKey.HRCODE));
|
map.put(SessionKey.HRNAME.replace("@", ""), session.getAttribute(SessionKey.HRNAME));
|
map.put(SessionKey.USERNAME.replace("@", ""), session.getAttribute(SessionKey.USERNAME));
|
map.put(SessionKey.USER_NAME.replace("@", ""), session.getAttribute(SessionKey.USER_NAME));
|
map.put(SessionKey.ORIGINAL_USERNAME.replace("@", ""), session.getAttribute(SessionKey.ORIGINAL_USERNAME));
|
map.put(SessionKey.USER.replace("@", ""), session.getAttribute(SessionKey.USER));
|
map.put(SessionKey.ORIGINAL_USERCODE.replace("@", ""), session.getAttribute(SessionKey.ORIGINAL_USERCODE));
|
map.put(SessionKey.USERCODE.replace("@", ""), session.getAttribute(SessionKey.USERCODE));
|
map.put(SessionKey.COMPANY_ID.replace("@", ""), session.getAttribute(SessionKey.COMPANY_ID));
|
map.put(SessionKey.COMPANY_NAME.replace("@", ""), session.getAttribute(SessionKey.COMPANY_NAME));
|
map.put(SessionKey.COMPANYMEMO.replace("@", ""), session.getAttribute(SessionKey.COMPANYMEMO));
|
map.put(SessionKey.VERSION_ID.replace("@", ""), session.getAttribute(SessionKey.VERSION_ID));
|
map.put(SessionKey.DEPARTMENT.replace("@", ""), session.getAttribute(SessionKey.DEPARTMENT));
|
map.put(SessionKey.CCCODE.replace("@", ""), session.getAttribute(SessionKey.CCCODE));
|
map.put(SessionKey.CCNAME.replace("@", ""), session.getAttribute(SessionKey.CCNAME));
|
map.put(SessionKey.SUPPER_USER.replace("@", ""), session.getAttribute(SessionKey.SUPPER_USER));
|
map.put(SessionKey.ROLE_NAME.replace("@", ""), session.getAttribute(SessionKey.ROLE_NAME));
|
map.put(SessionKey.DEFAULT_SET.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_SET));
|
map.put(SessionKey.LOGIN_TYPE.replace("@", ""), session.getAttribute(SessionKey.LOGIN_TYPE));
|
map.put(SessionKey.isStopSystem.replace("@", ""), session.getAttribute(SessionKey.isStopSystem));
|
map.put(SessionKey.OPEN_ID.replace("@", ""), session.getAttribute(SessionKey.OPEN_ID));
|
map.put(SessionKey.CURRENCY.replace("@", ""), session.getAttribute(SessionKey.CURRENCY));
|
map.put(SessionKey.SHOP_CCCDOE.replace("@", ""), session.getAttribute(SessionKey.SHOP_CCCDOE));
|
;
|
map.put(SessionKey.SYSTEM_LANGUAGE.replace("@", ""), session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
|
map.put(SessionKey.DEFAULT_STCODE.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_STCODE));
|
map.put(SessionKey.DEFAULT_ACCTCODE.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_ACCTCODE));
|
map.put(SessionKey.UserCodePermission.replace("@", ""), session.getAttribute(SessionKey.UserCodePermission));
|
map.put(SessionKey.COMPANY_PERMISSION.replace("@", ""), session.getAttribute(SessionKey.COMPANY_PERMISSION));
|
map.put(SessionKey.AT_TODAY.replace("@", ""), session.getAttribute(SessionKey.AT_TODAY));
|
map.put(SessionKey.AT_NOW.replace("@", ""), session.getAttribute(SessionKey.AT_NOW));
|
map.put(SessionKey.DEFAULT_BRAND.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_BRAND));
|
map.put(SessionKey.CCCODEPERMISSION.replace("@", ""), session.getAttribute(SessionKey.CCCODEPERMISSION));
|
map.put(SessionKey.USERTYPE.replace("@", ""), session.getAttribute(SessionKey.USERTYPE));
|
map.put(SessionKey.ISMODIFYPRICEWHENSCANQRCODE, session.getAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE));
|
map.put(SessionKey.ISMODIFYPRICEWHENSALESORDER, session.getAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER));
|
map.put(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER, session.getAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER));
|
map.put(SessionKey.SWITCHTOPAGEWHENLOGONAPP, session.getAttribute(SessionKey.SWITCHTOPAGEWHENLOGONAPP));
|
map.put(SessionKey.SELECTNEXTDOCUMENTWHENAPPROVED, session.getAttribute(SessionKey.SELECTNEXTDOCUMENTWHENAPPROVED));
|
map.put("day", DateUtil.getDay(0));
|
map.put("month", DateUtil.getMonth(0));
|
map.put("year", DateUtil.getYear(0));
|
return map;
|
|
}
|
|
private void proccError(String account, String pwd, HttpServletRequest request, HttpServletResponse response) {
|
Boolean isApp = Boolean.valueOf((request.getParameter("isApp") == null&&request.getAttribute("isApp") == null) ? false : true);// 手机app传过来
|
try {
|
SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
record.loginRecord(account, pwd, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
|
} catch (Exception e2) {
|
e2.printStackTrace();
|
this.print2(response, e2.getMessage().replace("\"", ""), request.getParameter("redirect"), isApp);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
this.print2(response, "用户账号或密码错误!", request.getParameter("redirect"), isApp);
|
}
|
|
@RequestMapping("/logout.do")
|
public void logout(HttpServletRequest request, HttpServletResponse response) {
|
try {
|
HttpSession session = request.getSession();
|
session.invalidate();
|
this.printJson(response, "{\"success\":\"ok\"}");
|
} catch (Exception e) {
|
e.printStackTrace();
|
this.printJson(response, "{\"error\":\"" + e.getMessage() + "\"}");
|
}
|
}
|
|
|
@RequestMapping("/GetLoginUser.do")
|
public void getLoginUser(HttpServletRequest request, HttpServletResponse response) {
|
int pageSize = 0;
|
int curPage = 0;
|
int total = 0;
|
List<Map<String, Object>> list = null;
|
try {
|
pageSize = Integer.parseInt(request.getParameter("rows"));// 每页大小
|
curPage = Integer.parseInt(request.getParameter("page")); // 当前页
|
} catch (Exception e) {
|
return;
|
}
|
|
// 搜索条件
|
String companyname = request.getParameter("companyname");
|
String usercode = request.getParameter("usercode");
|
String username = request.getParameter("username");
|
try {
|
SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
if (StringUtils.isBlank(companyname) && StringUtils.isBlank(usercode) && StringUtils.isBlank(username)) {
|
total = userAccountService.getUserTotal();
|
list = userAccountService.getLoginUser(curPage, pageSize);
|
} else {
|
total = userAccountService.getUserTotal(companyname, usercode, username);
|
list = userAccountService.getLoginUser(curPage, pageSize, companyname, usercode, username);
|
}
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
Gson gson = new Gson();
|
String data = gson.toJson(list);
|
|
StringBuilder sb = new StringBuilder();
|
sb.append("{\"total\":").append(total).append(",\"rows\":").append(data).append("}");
|
|
try {
|
printText(response, sb.toString());
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
data = null;
|
sb = null;
|
list = null;
|
gson = null;
|
}
|
|
/**
|
* 输出信息到客户端
|
*
|
* @param response
|
* @param str
|
* @throws IOException
|
*/
|
public void printText(HttpServletResponse response, String str) throws IOException {
|
response.setCharacterEncoding("utf-8");
|
PrintWriter out = response.getWriter();
|
out.write(str);
|
out.flush();
|
out.close();
|
}
|
|
/**
|
* 设置session 相关值(添加新的session标识符时应在切换用户功能添加相应的session标识符com.yc.action.login.SwitchUserCodeAction)
|
*
|
* @param dbId
|
* @param userAccount
|
* @param session
|
* @return
|
* @throws Exception
|
*/
|
public static String setSessionValues(String dbId, UserAccountEntity userAccount, HttpSession session,
|
PerssionEntity perssionEntity) throws Exception {
|
// ------------用SessionKey类来存储session标识符 避免大小写或者忘记session标识符的情况-------
|
Map<String, Object> role = perssionEntity.getRole(); // rIfc.getRole(userAccount.getUserCode());
|
String userCode = (String) userAccount.getUserCode();
|
session.setAttribute(SessionKey.HRCODE, ((String) userAccount.getHrCode()).replaceAll("\\s", ""));// 用户ID
|
session.setAttribute(SessionKey.HRNAME, ((String) userAccount.getHrName()).replaceAll("\\s", ""));// 用户ID
|
String userName = (String) userAccount.getUserName();// 用户名
|
session.setAttribute(SessionKey.USERNAME, userName.replaceAll("\\s", ""));
|
session.setAttribute(SessionKey.USER_NAME, userName.replaceAll("\\s", ""));
|
session.setAttribute(SessionKey.PASSWORD, userAccount.getPassword());
|
session.setAttribute(SessionKey.ORIGINAL_USERNAME, userName.replaceAll("\\s", ""));
|
session.setAttribute(SessionKey.USER, userCode.replaceAll("\\s", ""));// 用户ID
|
session.setAttribute(SessionKey.ORIGINAL_USERCODE, userCode.replaceAll("\\s", ""));
|
session.setAttribute(SessionKey.USERCODE, userCode.replaceAll("\\s", ""));// 用户ID
|
session.setAttribute(SessionKey.COMPANY_ID, userAccount.getCompanyId());// 公司代码
|
session.setAttribute(SessionKey.COMPANY_NAME, userAccount.getCompanyName());// 公司代码
|
session.setAttribute(SessionKey.COMPANYMEMO, userAccount.getCompanyMemo());// 适合于多公司
|
session.setAttribute(SessionKey.VERSION_ID, 0);// 版本号
|
session.setAttribute(SessionKey.DEPARTMENT, userAccount.getCcName());
|
session.setAttribute(SessionKey.CCCODE, userAccount.getCcCode());
|
session.setAttribute(SessionKey.CCNAME, userAccount.getCcName());
|
session.setAttribute(SessionKey.SUPPER_USER,
|
("SuperUser".equalsIgnoreCase(userAccount.getUserType()) || "DeveloperUser".equalsIgnoreCase(userAccount.getUserType())) ? "1" : "0");// 系统管理员
|
session.setAttribute(SessionKey.isStopSystem, userAccount.isStopSystem() ? "1" : "0");
|
session.setAttribute(SessionKey.OPEN_ID, userAccount.getOpenId());// openid号
|
session.setAttribute(SessionKey.CURRENCY, userAccount.getCurrency());
|
session.setAttribute(SessionKey.SHOP_CCCDOE, userAccount.getShopCcCode());// shopcccode
|
session.setAttribute(SessionKey.COMPANY_PERMISSION, userAccount.getCompanyPermission());// CompanyPermission
|
|
session.setAttribute(SessionKey.ROLE_NAME,
|
role == null ? "未设置" : role.get("RoleName") == null ? "" : role.get("RoleName"));// 如超级用户
|
|
// 根据账号获取相关权限集合
|
Map<String, Map<String, Object>> perssion = perssionEntity.getPerssion(); // userAccountService.getUserProfiles(userCode);
|
|
// 获得缺省集合
|
if (userAccount.getDefaultSet() != null && !"".equals(userAccount.getDefaultSet())) {
|
// DefaultSet.defaultSet2Session(userAccountService.getDefaultSet(userAccount.getDefaultSet()),
|
// session);
|
DefaultSet.defaultSet2Session(perssionEntity.getDefaultSet(), session);
|
}
|
|
// 构建账号对应的系统菜单
|
session.setAttribute(SessionKey.PERSSION, perssion);// 权限集合
|
session.setAttribute(SessionKey.LOGIN_TYPE, userAccount.getLogonType() + "");
|
session.setAttribute(SessionKey.SYSTEM_LANGUAGE, "cnzh");// 设置语言
|
session.setAttribute(SessionKey.DIBANG, userAccount.isEnableLoadCollection() ? "1" : "0");// 设置地磅权限
|
// 添加地磅需要信息 默认先给空白
|
session.setAttribute(SessionKey.LOADER_NAME, "");
|
session.setAttribute(SessionKey.IP_ADDRESS, "");
|
session.setAttribute(SessionKey.HOSTNAME, "");
|
session.setAttribute(SessionKey.MAC_ADDRESS, "");
|
session.setAttribute(SessionKey.AT_TODAY, DateUtil.toDayDate());
|
session.setAttribute(SessionKey.AT_NOW, DateUtil.toDay());
|
session.setAttribute(SessionKey.DEFAULT_STCODE, userAccount.getDefaultStcode());
|
session.setAttribute(SessionKey.DEFAULT_ACCTCODE, userAccount.getDefaultAcctCode());
|
session.setAttribute(SessionKey.UserCodePermission, userAccount.getUserCodePermission());
|
session.setAttribute(SessionKey.DEFAULT_BRAND, userAccount.getDefaultBrand());
|
session.setAttribute(SessionKey.CCCODEPERMISSION, userAccount.getCcCodePermission());
|
session.setAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE, userAccount.getIsModifyPriceWhenScanQrCode());
|
session.setAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER, userAccount.getIsModifyPriceWhenSalesOrder());
|
session.setAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER, userAccount.getIsModifyPriceWhenPurchaseOrder());
|
session.setAttribute(SessionKey.SWITCHTOPAGEWHENLOGONAPP, userAccount.getSwitchToPageWhenLogonApp());
|
session.setAttribute(SessionKey.SELECTNEXTDOCUMENTWHENAPPROVED, userAccount.getSelectNextDocumentWhenApproved());
|
session.setAttribute(SessionKey.USERTYPE, userAccount.getUserType());
|
|
session.setAttribute(SessionKey.PAGE_PATH,
|
File.separator + "app" + File.separator + session.getAttribute(SessionKey.DATA_BASE_ID) + File.separator
|
+ session.getAttribute(SessionKey.VERSION_ID) + File.separator
|
+ session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
|
String realpath = session.getServletContext().getRealPath("/") + session.getAttribute(SessionKey.PAGE_PATH);
|
session.setAttribute(SessionKey.REAL_PATH, realpath.replaceAll("\\\\", "/"));
|
session.setAttribute(SessionKey.DATA_PATH,
|
File.separator + "app" + File.separator + session.getAttribute(SessionKey.DATA_BASE_ID) + File.separator
|
+ session.getAttribute(SessionKey.VERSION_ID) + File.separator
|
+ session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
|
InitSystem.getInstance().setMailSavePath(session.getServletContext()
|
.getRealPath(File.separator + "WEB-INF" + File.separator + "MAIL" + File.separator));
|
// 结束地磅所需信息
|
// 增加读取授权门店数
|
DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(dbId);
|
if (dataSourceEntity != null) {
|
session.setAttribute(SessionKey.LimitDepartmentNumber, dataSourceEntity.getLimitDepartmentNumber());
|
session.setAttribute(SessionKey.DATACHECK_PAGENUM, dataSourceEntity.getDataCheckPageNum());
|
}
|
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
|
session.setAttribute(SessionKey.LOGIN_TIME, df.format(new Date()));//登录时间 xin 2020-8-31 11:35:22
|
|
return userName;
|
|
}
|
|
public void setRecord(LoginRecordIfc record) {
|
this.record = record;
|
}
|
|
// 检查session是否失效
|
@RequestMapping("/checkSession.do")
|
public void sessionCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
HttpSession session = request.getSession();
|
String result = "";
|
if (session.getAttribute(SessionKey.HRCODE) == null) {
|
// userAccountService.doQuitLog(request.getParameter("usercode")); by 2014-8-5
|
// danaus 会话失效写插进数据无意义且会出错
|
result = "fail";
|
} else {
|
result = "success";
|
}
|
printText(response, "{\"status\":\"" + result + "\"}");
|
}
|
|
/**
|
* session失效后弹出登录框登录
|
*
|
* @param request
|
* @param response 2012-09-20
|
*/
|
@RequestMapping("/againLogin.do")
|
public String againLogin(String usercode, String password, String dbid, String dbstr, String domain,
|
HttpServletRequest request, HttpServletResponse response) {
|
// System.out.println("againLogin..."+request.getSession().getId()+",时间:"+request.getSession().getCreationTime());
|
StringBuilder sb = new StringBuilder();
|
HttpSession session = request.getSession();
|
CallBackMessage callBackMessage = new CallBackMessage();
|
if (dbid == null || "".equals(dbid)) {
|
List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByDomain(domain);
|
if (dataSourceList != null && dataSourceList.size() > 0) {
|
dbid = dataSourceList.get(0).getDbId() + "";
|
}
|
}
|
try {
|
if (dbid == null || "".equals(dbid)) {
|
sb.append("数据库ID不能为空\\n");
|
}
|
|
if (StringUtils.isBlank(usercode)) {
|
sb.append("账号不能为空\\n");
|
}
|
if (StringUtils.isBlank(password)) {
|
sb.append("密码不能为空\\n");
|
}
|
if (sb.length() > 0) {
|
callBackMessage.sendErrorMessage(sb.toString());
|
this.printJson(response, callBackMessage.toString());
|
return null;// 验证出错返回'
|
}
|
|
session.setAttribute(SessionKey.DATA_BASE_ID, dbid);
|
session.setAttribute(SessionKey.DATABASE_DIS, dbstr);
|
session.setAttribute(SessionKey.DOMAIN, request.getParameter("domain"));
|
|
// --------------------
|
// 判断是否超出人数限制
|
|
if (SessionListener.checkUserLimit(request, dbid)) {
|
String s = "当前登录人数已超过系统最大登录人数,如有需要增加登录人数,请联系软件公司";
|
this.print2(response, s, null, null);
|
session.invalidate();
|
return null;// 验证出错返回'
|
}
|
Boolean isApp = Boolean.valueOf(request.getParameter("isApp") == null ? false : true);// 手机app传过来
|
if (usercode != null && usercode.length() > 30) {//解密为明文
|
try {
|
usercode = ChangePassword.getDecryptPassword(usercode);
|
} catch (Exception e) {
|
e.printStackTrace();
|
print2(response, this.getErrorMsg(e), null, isApp);
|
return null;// 验证出错返回'
|
|
}
|
}
|
// ----------------
|
// String dbid=session.getAttribute(SessionKey.DATA_BASE_ID)+"";
|
int recordeCount = 0;
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
recordeCount = record.getRecordCountIn10min(usercode);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (recordeCount >= 5) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 登录次数过多再行登陆作为登录失败处理
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
this.print2(response, usercode + "在短时间内登录错误次数过多!请耐心的等10分钟后再登录!", null, null);
|
return null;// 验证出错返回
|
}
|
|
// session.setAttribute(SessionKey.ONLINE_USERS, new
|
// OnLineUser(usercode,userName,dbid,request.getParameter("domain")));//在线人数统计
|
// 设置session
|
String ip = IPUtil.getIpAddr(request);
|
// 检查限制用户登录时间和登录IP
|
int s = 0;
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
s = userAccountService.checkUserLoginTimeAndIp(usercode, ip);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (s == 0) {
|
print2(response, "该用户只能在工作时间或固定场所使用本系统[" + ip + "]", null, isApp);
|
return null;
|
}
|
//
|
// --------------
|
// String ucode = usercode + Math.random();// 是为了区分用户重复问题,同一用户可以多人使用。
|
// session.setAttribute(SessionKey.SAIL_USERCODE, ucode);
|
// OnLineUser.setOnlineUser(dataString, ucode, session);
|
// session.setAttribute(SessionKey.ONLINE_USERS, new OnLineUser());// 在线人数统计
|
// ------------------
|
|
|
UserAccountEntity userAccount = null;
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
userAccount = userAccountService.getUserInfoByUserCode(usercode);
|
if (userAccount == null) {
|
userAccount = userAccountService.getUserInfoByTelephone(usercode); //允许电话登录
|
}
|
|
if (userAccount == null) {
|
userAccount = userAccountService.getUserInfoByEmail(usercode); //允许邮箱号登录
|
}
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
if (userAccount == null) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
this.print2(response, usercode+"未开通ERP系统服务,登录失败", request.getParameter("redirect"), isApp);
|
return null;
|
}else {
|
if(userAccount.isInActive()){
|
this.print2(response, usercode+"已被停用,禁止登录本系统!", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
}
|
try {
|
if (!userAccount.checkPassword(password)) {
|
try {
|
SpObserver.setDBtoInstance("_" + dbid);
|
record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
this.print2(response, "用户密码不正确!", request.getParameter("redirect"), isApp);
|
return null;
|
}
|
} catch (Exception ex) {
|
this.print2(response, ex.getMessage(), request.getParameter("redirect"), isApp);
|
}
|
// 设置权限
|
processLoginUserToSessionV2(ip, dbid, request, userAccount);
|
callBackMessage.sendSuccessMessage("登录成功");
|
this.printJson(response, callBackMessage.toString());
|
return null;
|
} catch (NullPointerException e) {// 不存在此账号
|
e.printStackTrace();
|
proccError(usercode, password, request, response);
|
return null;
|
} catch (RuntimeException e) {
|
e.printStackTrace();
|
if (e.getMessage().equals(SessionKey.DEMO_REF)) {
|
session.setAttribute(SessionKey.DEMO_REF, SessionKey.DEMO_REF);
|
this.print(response, "<script>alert('请生成正确配置信息');window.location.href='/demo/demoList.jsp';</script>");
|
}
|
return null;
|
} catch (Exception e) {// 不存在此账号
|
e.printStackTrace();
|
proccError(usercode, password, request, response);
|
return null;
|
}
|
}
|
|
private class AppJsonObject {
|
private boolean myResult;
|
private HttpServletResponse mResponse;
|
private String mUserCode;
|
private String mPassword;
|
private Boolean mIsApp;
|
private String mRedirect;
|
private List<Map<String, Object>> mList;
|
private boolean mCh_userid;
|
private String mDbId;
|
private String mDataBaseDis;
|
private String mDomain;
|
private UserAccountEntity mUserAccount;
|
|
public AppJsonObject(HttpServletResponse response, String userCode, String password, Boolean isApp, String redirect, List<Map<String, Object>> list) {
|
mResponse = response;
|
mUserCode = userCode;
|
mPassword = password;
|
mIsApp = isApp;
|
mRedirect = redirect;
|
mList = list;
|
}
|
|
boolean is() {
|
return myResult;
|
}
|
|
public String getUserCode() {
|
return mUserCode;
|
}
|
|
public String getPassword() {
|
return mPassword;
|
}
|
|
public boolean isCh_userid() {
|
return mCh_userid;
|
}
|
|
public String getDbId() {
|
return mDbId;
|
}
|
|
public String getDataBaseDis() {
|
return mDataBaseDis;
|
}
|
|
public String getDomain() {
|
return mDomain;
|
}
|
|
public UserAccountEntity getUserAccount() {
|
return mUserAccount;
|
}
|
|
public AppJsonObject invoke() {
|
Map<String, Object> map = mList.get(0);
|
mDbId = map.get("id") + "";
|
mDataBaseDis = (String) map.get("systemid");
|
mDomain = (String) map.get("domain");
|
// 通过数据源id和手机号取得用户usercode进行登录,这时候不需要密码验证
|
try {
|
SpObserver.setDBtoInstance("_" + mDbId);
|
mUserAccount = userAccountService.getUserInfoByTelephone(mUserCode);
|
if (mUserAccount != null) {
|
if(mUserAccount.isInActive()){
|
print2(mResponse, mUserCode+"已被停用,禁止登录本系统", mRedirect, mIsApp);
|
myResult = true;
|
return this;
|
}
|
mUserAccount.setApp_userCode(mUserCode);
|
mUserAccount.setApp_Password(mPassword);
|
mUserCode = mUserAccount.getUserCode();//转成ERP的usercode进行登陆
|
mPassword = mUserAccount.getPassword();//转成ERP的密码进行登陆
|
mCh_userid = true;
|
} else {
|
print2(mResponse, mUserCode+"未开通ERP系统服务,登录失败", mRedirect, mIsApp);
|
myResult = true;
|
return this;
|
}
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
myResult = false;
|
return this;
|
}
|
}
|
}
|