qa-prevention-gwj/src/main/java/com/zcloud/controller/system/LoginController.java

513 lines
24 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.zcloud.controller.system;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.zcloud.service.system.*;
import com.zcloud.util.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Role;
import com.zcloud.entity.system.User;
import com.zcloud.service.bus.CorpInfoService;
import com.zcloud.service.bus.OffDutyService;
import net.sf.json.JSONObject;
/**
* 说明:登录处理类
* 作者luoxiaobao
* 官网www.qdkjchina.com
*/
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {
@Autowired
private UsersService usersService;
@Autowired
private RoleService roleService;
@Autowired
private FHlogService FHLOG;
@Autowired
private DepartmentService departmentService;
@Autowired
private CorpInfoService corpinfoService;
@Autowired
private OffDutyService offdutyService;
@Autowired
private PhotoService photoService;
// @Value("${czks-useridentity}")
// private String czksIdentity;
// @Value("${czks-baseimgpath}")
// private String czksBaseimgpath;
// @Value("${czks-backendaddr}")
// private String czksBackendaddr;
//
// @Value("${gwj-useridentity}")
// private String gwjIdentity;
// @Value("${gwj-baseimgpath}")
// private String gwjBaseimgpath;
// @Value("${gwj-backendaddr}")
// private String gwjBackendaddr;
@Autowired
private CorpPathService corpPathService;
/**
* 请求登录验证用户接口
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/check", produces = "application/json;charset=UTF-8")
@ResponseBody
public Object check() throws Exception {
// 获取IP
HttpServletRequest request = this.getRequest();
String ip = "";
if (request.getHeader("x-forwarded-for") == null) {
ip = request.getRemoteAddr();
} else {
ip = request.getHeader("x-forwarded-for");
}
Map<String, String> map = new HashMap<String, String>();
String errInfo = "success";
// if(!BasicInfoUtil.checkValid()) {
// String errInfo = "invalid";
// map.put("result", errInfo);
// return map;
// }
Session session = Jurisdiction.getSession();
// System.out.println("登录次数:"+session.getAttribute("loginCount"));
//session 手机端需要打包安装到实机有效模拟器一直返回null
// int loginCount = null != session.getAttribute("loginCount")?Integer.parseInt(session.getAttribute("loginCount").toString()):0;
// if (loginCount >= 5) {
// errInfo = "systemlock";
// map.put("result", "fail");
// map.put("errorCode", errInfo);
// map.put("msg", "发现异常登录,系统拒绝访问");
// map.put("failMsg", "发现异常登录,系统拒绝访问");
// return map;
// }
PageData pd = new PageData();
pd = this.getPageData();
String loginData = pd.getString("KEYDATA");
if (!loginData.startsWith("qdkjchina")) {
loginData = RSAUtils.decryptDataOnJava(loginData, RSAUtils.getPrivateKey());
}
int loginCount = 0;
String KEYDATA[] = loginData.replaceAll("qdkjchina", "").split(",qd,");
if (null != KEYDATA && KEYDATA.length >= 2) {
String USERNAME = KEYDATA[0]; //登录过来的用户名
String PASSWORD = KEYDATA[1]; //登录过来的密码
UsernamePasswordToken token;
if (null != pd.get("isLogin")) {
token = new UsernamePasswordToken(USERNAME, PASSWORD);
} else {
token = new UsernamePasswordToken(USERNAME, new SimpleHash("SHA-1", USERNAME, PASSWORD).toString());
}
pd.put("USERNAME", USERNAME);
pd = usersService.findByUsername(pd);
if (!Tools.isEmpty(pd)) {
if (!Tools.isEmpty(pd.getString("ERROR_COUNT"))) {
loginCount = Integer.parseInt(pd.getString("ERROR_COUNT"));
}
} else {
map.put("result", "exception");
map.put("msg", "未找到此用户");
map.put("exception", "未找到此用户");
return map;
}
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token); //这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中
} catch (UnknownAccountException uae) {
errInfo = "usererror";
} catch (IncorrectCredentialsException ice) {
errInfo = "usererror";
} catch (LockedAccountException lae) {
errInfo = "usererror";
} catch (ExcessiveAttemptsException eae) {
errInfo = "usererror";
} catch (DisabledAccountException sae) {
errInfo = "usererror";
} catch (AuthenticationException ae) {
errInfo = "usererror";
}
if (subject.isAuthenticated()) { //验证是否登录成功
removeSession(USERNAME);
if (pd != null) {
if ("99".equals(pd.getString("STATUS"))) {
errInfo = "userlock";
map.put("result", "fail");
map.put("errorCode", errInfo);
map.put("msg", "帐号已锁定,请联系管理员");
map.put("failMsg", "帐号已锁定,请联系管理员");
return map;
}
// 判断是不是沧州矿石的用户
// if (czksIdentity.equals(pd.getString("USER_IDENTITY"))) {
// // 沧州矿石的用户
// // 用户标识
// map.put("USER_IDENTITY", czksIdentity);
// // 图片路径
// map.put("baseImgPath", czksBaseimgpath);
// // 后台地址
// map.put("BACKENDADDR", czksBackendaddr);
// }
// if ("".equals(pd.getString("USER_IDENTITY"))) {
// // 港股的用户
// // 用户标识
// map.put("USER_IDENTITY", gwjIdentity);
// // 图片路径
// map.put("baseImgPath", gwjBaseimgpath);
// // 后台地址
// map.put("BACKENDADDR", gwjBackendaddr);
// }
PageData cpd = corpinfoService.findById(pd);
//System.out.println(cpd.getString("ISUSE"));
if (cpd != null) {
if (cpd.getString("ISUSE").equals("0")) {
if (pd != null) {
if (pd.getString("ROLE_ID").equals("1") || pd.getString("ROLE_ID").equals("0efe7308b3ef4e6594c9c0ddf900ad26")) {
errInfo = "usererror";
} else {
map.put("USERNAME", USERNAME);
map.put("USER_ID", pd.getString("USER_ID"));
map.put("NAME", pd.getString("NAME"));
map.put("ISMAIN", pd.getString("ISMAIN"));
map.put("DEPARTMENT_ID", pd.getString("DEPARTMENT_ID"));
map.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
map.put("LONGITUDE", cpd.getString("LONGITUDE"));
map.put("LATITUDE", cpd.getString("LATITUDE"));
// PageData dpd = new PageData();
// dpd.put("DEPARTMENT_ID", pd.getString("DEPARTMENT_ID"));
// dpd=departmentService.findById(dpd);
// map.put("DEPARTMENT_NAME", dpd.getString("NAME"));
// map.put("PARENT_NAME", dpd.getString("PARENT_NAME"));
// 现在多roleID 使用权限最高的
List<String> roleIds = new ArrayList<>();
String role = pd.getString("ROLE_ID");
roleIds.add(role);
if (Tools.notEmpty(pd.getString("ROLE_IDS"))) {
roleIds.add(Arrays.toString(pd.getString("ROLE_IDS").split(",")));
}
PageData rpd = roleService.findMaxRoleByRId(roleIds);
map.put("ROLEID", rpd.getString("ROLE_ID"));
map.put("ROLE_NAME", rpd.getString("ROLE_NAME"));
map.put("USERBZ", pd.getString("BZ"));
PageData dpd = new PageData();
dpd.put("DEPARTMENT_ID", pd.getString("DEPARTMENT_ID"));
dpd = departmentService.findById(dpd);
map.put("DEPARTMENT_NAME", dpd.getString("NAME"));
User user = new User();
user.setUSER_ID(pd.getString("USER_ID"));
user.setUSERNAME(pd.getString("USERNAME"));
user.setPASSWORD(pd.getString("PASSWORD"));
user.setNAME(pd.getString("NAME"));
user.setROLE_ID(pd.getString("ROLE_ID"));
user.setLAST_LOGIN(pd.getString("LAST_LOGIN"));
user.setIP(pd.getString("IP"));
user.setSTATUS(pd.getString("STATUS"));
user.setRoleLevel(rpd.getString("LEVEL")); //用户等级
user.setSuperviseDepartId(this.superviseDepart(pd, rpd, dpd)); //查看部门
PageData ypd = photoService.findByUserId(user.getUSER_ID());
if (null != ypd) { //没有数据就新增,否则就修改
map.put("USERPHONE", ypd.getString("PHOTO1")); //主键
} else {
map.put("USERPHONE", "");
}
map.put("supDeparIds", user.getSuperviseDepartId());
map.put("roleLevel", rpd.getString("LEVEL"));
PageData isRest = this.getPageData();
isRest.put("ISREST", "1");
isRest.put("USER_ID", pd.getString("USER_ID"));
isRest.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
List<PageData> restList = offdutyService.listAll(isRest);
if (restList != null && restList.size() > 0) {
// 休假中
map.put("ISREST", "1");
} else {
// 正常工作
map.put("ISREST", "0");
}
session.setAttribute(Const.SESSION_USER, user); //把当前用户放入session
session.setAttribute(Const.DEPARTMENT_ID, pd.getString("DEPARTMENT_ID")); //把当前用户放入session
session.setAttribute(Const.CORPINFO_ID, pd.getString("CORPINFO_ID")); //把当前用户企业放入session
session.setAttribute(Const.POST_ID, pd.getString("POST_ID") == null ? "" : pd.getString("POST_ID")); //把当前用户岗位放入session
session.setAttribute(Const.USER_ID, pd.getString("USER_ID")); //把当前用户企业放入session
session.setAttribute(Const.SESSION_USERNAME, USERNAME); //放入用户名到session
session.setAttribute(Const.SESSION_U_NAME, user.getNAME()); //放入用户姓名到session
session.setAttribute(Const.IS_MAIN, pd.get("ISMAIN")); //是否主账号
session.setAttribute(Const.ISSUPERVISE, dpd.getString("ISSUPERVISE")); //把当前用户放入session
FHLOG.save(USERNAME, "成功登录系统", ip); //记录日志
//查询该用户或企业的图片和后端地址
if (!Tools.isEmpty(pd.getString("CORPINFO_ID")) && !pd.getString("CORPINFO_ID").equals("1")) {
PageData pathData = corpPathService.getCorpPathByCorpId(pd);
map.put("baseImgPath",pathData.getString("PIC_PATH"));
map.put("USER_IDENTITY",pathData.getString("USER_IDENTITY"));
map.put("BACKENDADDR", pathData.getString("BACK_END_PATH"));
} else {
PageData pathData = corpPathService.getCorpPathByPersonInfo(pd);
map.put("baseImgPath",pathData.getString("PIC_PATH"));
map.put("USER_IDENTITY",pathData.getString("USER_IDENTITY"));
map.put("BACKENDADDR", pathData.getString("BACK_END_PATH"));
}
}
} else {
token.clear();
errInfo = "usererror";
}
} else {
errInfo = "userUSEerror";
map.put("msg", "您的企业已到使用期限,请联系管理员");
}
} else {
errInfo = "usererror";
// map.put("msg", "用户不存在"); //用户账号枚举漏洞
}
} else {
errInfo = "usererror";
// map.put("msg", "用户不存在"); //用户账号枚举漏洞
}
} else {
token.clear();
errInfo = "usererror";
}
if (!"success".equals(errInfo)) FHLOG.save(USERNAME, "尝试登录系统失败,用户名密码错误,无权限", ip);
} else {
errInfo = "error"; //缺少参数
}
if ("success".equals(errInfo)) {
map.put("result", "success");
session.removeAttribute("loginCount");
} else {
map.put("errorCode", errInfo);
map.put("result", "fail");
if (loginCount == 4) {
map.put("msg", "帐号已锁定,请联系管理员");
map.put("failMsg", "帐号已锁定,请联系管理员");
} else {
if ("userUSEerror".equals(errInfo)) {
map.put("msg", "您的企业已被暂停使用,请联系管理员");
map.put("failMsg", "您的企业已被暂停使用,请联系管理员");
} else {
map.put("msg", "用户名或密码有误,您还有" + (4 - loginCount) + "次机会,请重试");
map.put("failMsg", "用户名或密码有误,您还有" + (4 - loginCount) + "次机会,请重试");
}
}
session.setAttribute("loginCount", loginCount + 1);
if ("error".equals(errInfo)) {
map.put("msg", "缺少参数");
map.put("failMsg", "");
} else {
pd.put("USERNAME", KEYDATA[0]);
pd = usersService.findByUsername(pd);
if (pd != null) {
int loginErrorCount = Tools.isEmpty(pd.getString("ERROR_COUNT")) ? 0 : Integer.parseInt(pd.getString("ERROR_COUNT"));
if (!"99".equals(pd.getString("LOCK_STATUS"))) { //非锁定帐号
if (loginErrorCount < 4) {
pd.put("LOCK_STATUS", "0");
pd.put("LAST_LOGIN", DateUtil.date2Str(new Date()));
pd.put("ERROR_COUNT", loginErrorCount + 1);
usersService.lockUser(pd);
} else {
pd.put("LOCK_STATUS", "99");
pd.put("ERROR_COUNT", loginErrorCount + 1);
pd.put("LAST_LOGIN", DateUtil.date2Str(new Date()));
usersService.lockUser(pd);
map.put("msg", "帐号已锁定,请联系管理员");
map.put("failMsg", "帐号已锁定,请联系管理员");
}
} else {
map.put("msg", "帐号已锁定,请联系管理员");
map.put("failMsg", "帐号已锁定,请联系管理员");
}
}
}
}
return map;
}
/**
* 系统用户注册接口
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/register", produces = "application/json;charset=UTF-8")
@ResponseBody
public Object register(@RequestParam("callback") String callback) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
PageData pd = new PageData();
pd = this.getPageData();
String result = "00";
if (Tools.checkKey("USERNAME", pd.getString("FKEY"))) { //检验请求key值是否合法
pd.put("USER_ID", this.get32UUID()); //ID 主键
pd.put("ROLE_ID", "fhadminzhuche"); //角色ID fhadminzhuche 为注册用户
pd.put("NUMBER", ""); //编号
pd.put("PHONE", ""); //手机号
pd.put("BZ", "注册用户"); //备注
pd.put("LAST_LOGIN", ""); //最后登录时间
pd.put("IP", ""); //IP
pd.put("STATUS", "0"); //状态
pd.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,"); //用户默认皮肤
pd.put("EMAIL", "");
pd.put("ROLE_IDS", "");
pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString()); //密码加密
if (null == usersService.findByUsername(pd)) { //判断用户名是否存在
usersService.saveUser(pd); //执行保存
FHLOG.save(pd.getString("USERNAME"), "新注册");
} else {
result = "01"; //用户名已存在
}
} else {
result = "05"; //不合法的注册
}
map.put("result", result);
JSONObject sresult = JSONObject.fromObject(map);
;
return callback + "(" + sresult.toString() + ")";
}
/**
* 判断是否登录状态
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/islogin")
@ResponseBody
public Object islogin() throws Exception {
Map<String, String> map = new HashMap<String, String>();
String errInfo = "success";
Session session = Jurisdiction.getSession();
if (null == session.getAttribute(Const.SESSION_USERNAME)) {
errInfo = "errer";
}
map.put("result", errInfo);
return map;
}
/**
* 清理session
*/
public void removeSession(String USERNAME) {
Session session = Jurisdiction.getSession(); //以下清除session缓存
session.removeAttribute(Const.SESSION_USER);
session.removeAttribute(USERNAME + Const.SESSION_ROLE_RIGHTS);
session.removeAttribute(USERNAME + Const.SESSION_ALLMENU);
session.removeAttribute(USERNAME + Const.SHIROSET);
session.removeAttribute(Const.SESSION_USERNAME);
session.removeAttribute(Const.SESSION_U_NAME);
session.removeAttribute(Const.SESSION_USERROL);
session.removeAttribute(Const.SESSION_RNUMBERS);
session.removeAttribute(Const.SKIN);
}
/**
* 获取用户监管部门id
* 等级(0--公司领导1部门领导3普通员工)
*
* @param userPd
* @param userRole 企业主账号
* 监管部门
*/
public String superviseDepart(PageData userPd, PageData userRole, PageData dpd) throws Exception {
String userSuperviseDepart = "NOT";
if (!Tools.isEmpty(userRole.getString("LEVEL"))) {
if ("0".equals(userRole.getString("LEVEL")) || "1".equals(userPd.getString("ISMAIN"))) { // 如果是 领导 或者是主账号 就显示 全部信息
userSuperviseDepart = "ALL";
} else if ("1".equals(userRole.getString("LEVEL"))) { //还要监管自己部门,如果没有监管自己,要增加上
String[] checkedIds = dpd.getString("checkedIds").split(",");
Map<String, Integer> chuchongMap = new HashMap<>(checkedIds.length + 1); //去重Map
chuchongMap.put(userPd.getString("DEPARTMENT_ID"), 0);
StringBuffer supDeptId = new StringBuffer();
for (int i = 0; i < checkedIds.length; i++) {
if (!Tools.isEmpty(checkedIds[i])) {
if (!chuchongMap.containsKey(checkedIds[i])) { //去除重复 判断空
supDeptId.append("'" + checkedIds[i] + "',");
}
}
}
supDeptId.append("'" + userPd.getString("DEPARTMENT_ID") + "'");
userSuperviseDepart = supDeptId.toString();
} else {
userSuperviseDepart = "NOT";
}
}
return userSuperviseDepart;
}
// PageData pd1 = new PageData();
// pd1.put("DEPARTMENT_ID",Jurisdiction.getDEPARTMENT_ID());
// pd1.put("ISSUPERVISE",1); //是监管部门
// PageData idss = departmentService.findById(pd1);
// if(idss!=null){
// String ids = idss.getString("checkedIds");
// if(ids!=null && Tools.notEmpty(ids) && ids.lastIndexOf(",")>-1 ) {
// String idList[] = ids.split(",");
// String a = "";
// for(String list:idList){
// a+="'"+list+"',";
//
// }
// a = a.substring(0,a.length()-1);
// pd.put("ArrayDATA_IDS", a);
// }
// }
}