src/main/java/com/whyc/config/I18nLocaleResolver.java
@@ -1,6 +1,7 @@ package com.whyc.config; import com.whyc.constant.YamlProperties; import com.whyc.util.ActionUtil; import com.whyc.util.CommonUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -51,7 +52,7 @@ //获取请求中的语言参数 String language = httpServletRequest.getParameter("lang"); //从session中获取lang String language2 = (String) CommonUtil.getSession().getAttribute("lang"); String language2 = (String) ActionUtil.getSession().getAttribute("lang"); //如果请求的链接中携带了 国际化的参数 if (!StringUtils.isEmpty(language)) { //zh_CN src/main/java/com/whyc/constant/UserConstant.java
New file @@ -0,0 +1,40 @@ package com.whyc.constant; /** * 用户常量 */ public enum UserConstant { ACCOUNT_TYPE_NORMAL("账号类型-长期",1), ACCOUNT_TYPE_TEMP("账号类型-临时",2), ACCOUNT_STATUS_ACTIVE("账号状态-激活",1), ACCOUNT_STATUS_HIBERNATE("账号状态-休眠",2), ACCOUNT_STATUS_LOCK("账号状态-锁定",3), ACCOUNT_STATUS_LOCK_FAIL("账号状态-锁定-连续失败",4), ACCOUNT_STATUS_CANCEL("账号状态-注销",0), ; private String label; private Integer value; UserConstant(String label, Integer value) { this.label = label; this.value = value; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } } src/main/java/com/whyc/constant/YamlProperties.java
@@ -26,6 +26,13 @@ /**系统运行模式*/ public static Integer runModel; /** * 系统类型 * 1:普通,没有多重校验 * 2:严格,有多重校验(登录,防重放,参数过滤) */ public static Integer systemType; /**自定义常量*/ public static String fontDynamicCodeSwitch; public static String allowedCORSDomainList; @@ -126,4 +133,9 @@ public void setI18nLanguage(String i18nLanguage) { YamlProperties.i18nLanguage = i18nLanguage; } @Value("${system.type}") public void setSystemType(Integer systemType) { YamlProperties.systemType = systemType; } } src/main/java/com/whyc/controller/LoginController.java
@@ -4,18 +4,13 @@ import com.whyc.pojo.db_user.User; import com.whyc.service.LoginService; import com.whyc.service.UserService; import com.whyc.util.CommonUtil; import com.whyc.util.UserUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @RequestMapping("login") @RestController src/main/java/com/whyc/controller/UserController.java
@@ -3,7 +3,6 @@ import com.whyc.dto.Response; import com.whyc.pojo.db_user.User; import com.whyc.service.UserService; import com.whyc.util.CommonUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; src/main/java/com/whyc/mapper/BaojigroupUsrMapper.java
@@ -12,4 +12,6 @@ List<BaojigroupUsr> getALlUsrByBjId(@Param("id") Integer id); List<User> getUserList(@Param("id") Integer id); Integer getGroupFlag(int uid); } src/main/java/com/whyc/mapper/PageParamMapper.java
New file @@ -0,0 +1,19 @@ package com.whyc.mapper; import com.whyc.pojo.db_app_sys.PageParam; import org.apache.ibatis.annotations.Param; import java.util.List; public interface PageParamMapper extends CustomMapper<PageParam>{ void updateList(List<PageParam> pageParamList, int operationFlag); //创建表 boolean createTable(); //根据 List<PageParam> findByCategoryId(@Param("categoryId") int categoryId); int update(@Param("id") int id,@Param("status") int status); void updateStatusList(@Param("pageParamList") List<PageParam> pageParamList); } src/main/java/com/whyc/pojo/db_app_sys/PageParam.java
New file @@ -0,0 +1,63 @@ package com.whyc.pojo.db_app_sys; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.ibatis.type.Alias; /** * 页面通用参数 */ @TableName(schema = "db_app_sys",value = "tb_page_param") @Alias("PageParam") @Data @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class PageParam { @TableId private Integer id; private String param; private Integer status; @TableField("categoryId") private Integer categoryId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } } src/main/java/com/whyc/pojo/db_user/User.java
@@ -3,6 +3,8 @@ import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.ToString; @@ -26,7 +28,26 @@ private String phoneNumber; @ApiModelProperty(value = "账号类型 1:长期,2:临时 ") private Integer type; @ApiModelProperty(value = "账号状态 1:激活,2:休眠,3:锁定,0:注销") private Integer status; @ApiModelProperty("临时账号的到期时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai") private Date expirationTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai") private Date lastLoginTime; @ApiModelProperty("密码更新时间,至少3个月一次") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai") private Date passwordUpdateTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai") private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai") private Date lockTime; @ApiModelProperty("允许访问ip") private String visitIp; @ApiModelProperty("允许访问时间区间") private String visitTime; public User() { } src/main/java/com/whyc/service/BaojigroupService.java
@@ -189,4 +189,9 @@ List<User> list=UserMapper.getBaojiUserByUid(baojiIdList); return new Response().setII(1,list!=null,list,"当前用户所在包机组下所有的用户(下拉)"); } public boolean getGroupFlag(int userId){ Integer flag = bjUsrmapper.getGroupFlag(userId); return flag != null && flag == 1; } } src/main/java/com/whyc/service/LoginService.java
@@ -2,19 +2,21 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.whyc.constant.UserConstant; import com.whyc.constant.YamlProperties; import com.whyc.dto.Response; import com.whyc.dto.UserClient; import com.whyc.mapper.PageParamMapper; import com.whyc.mapper.UserMapper; import com.whyc.pojo.db_app_sys.PageParam; import com.whyc.pojo.db_user.PermitgroupUsr; import com.whyc.pojo.db_user.User; import com.whyc.util.CommonUtil; import com.whyc.util.DateUtil; import com.whyc.util.MessageUtils; import com.whyc.util.RSAUtil; import com.whyc.util.*; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -31,62 +33,16 @@ private UserMapper userMapper; @Resource private PageParamMapper pageParamMapper; @Resource private UserService userService; @Resource private PermitGroupUserService permitGroupUserService; public Response login(String name, String pwd, HttpServletRequest request) { UsernamePasswordToken userToken = new UsernamePasswordToken(name, pwd); Subject subject = SecurityUtils.getSubject(); try { subject.login(userToken); } catch (Exception e) { String message = e.getMessage(); if (message.contains("did not match the expected credentials")) { return new Response<>().set(1, false, "密码错误"); } return new Response<>().set(1, false, message); } if (subject.isAuthenticated()){ //每个登录的用户都有一个全局变量,里面存着对应的SessionId; //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1 request.getServletContext().setAttribute(name,request.getSession().getId()); //Session存储当前用户 request.getSession().setAttribute("user",subject.getPrincipal()); //request.getSession().setMaxInactiveInterval(600); return new Response<>().setII(1,true,subject.getPrincipal(),"登录成功"); } return new Response<>().set(1,false,"密码错误"); } public Response login2(String userName, String pwd, HttpServletRequest request) throws UnsupportedEncodingException { //String password = URLDecoder.decode(pwd, "utf-8"); String password = pwd; String[] dataArr = RSAUtil.decryptFront(password, RSAUtil.fontSeparator); //验签md5 if(!dataArr[1].equals(CommonUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())){ return new Response<>().set(0,"密码验签失败"); } UsernamePasswordToken userToken = new UsernamePasswordToken(userName, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(userToken); }catch (Exception e){ String message = e.getMessage(); if(message.contains("did not match the expected credentials")){ return new Response<>().set(1,false,"密码错误"); } return new Response<>().set(1,false,message); } if (subject.isAuthenticated()){ //每个登录的用户都有一个全局变量,里面存着对应的SessionId; //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1 request.getServletContext().setAttribute(userName,request.getSession().getId()); //Session存储当前用户 request.getSession().setAttribute("user",subject.getPrincipal()); return new Response<>().setII(1,true,subject.getPrincipal(),"登录成功"); } return new Response<>().set(1,false,"密码错误"); } @Autowired private BaojigroupService bjService; public Response loginByRSA(String userName, String pwd, String deliveredCode, HttpServletRequest request, Integer validCode) { Response<Object> response = new Response<>(); @@ -96,7 +52,7 @@ deliveredCode = deliveredCode.toUpperCase(Locale.ENGLISH); if(validCode ==null ) { //属性不存在,则进行验证码校验;属性存在,则不进行验证码校验 if (YamlProperties.fontDynamicCodeSwitch.toLowerCase(Locale.ENGLISH).equals("true")) { String fontDynamicCode = (String) CommonUtil.getSession().getAttribute("fontDynamicCode"); String fontDynamicCode = (String) ActionUtil.getSession().getAttribute("fontDynamicCode"); if (fontDynamicCode == null || "".equals(fontDynamicCode)) { return response.set(1, false, MessageUtils.getMessage("RefreshVerification")); } @@ -106,7 +62,7 @@ } } //验证正确,清除验证码 CommonUtil.getSession().removeAttribute("fontDynamicCode"); ActionUtil.getSession().removeAttribute("fontDynamicCode"); /*String password = ""; try { password = URLDecoder.decode(pwd, "utf-8"); @@ -115,7 +71,7 @@ }*/ String[] dataArr = RSAUtil.decryptFront(pwd, RSAUtil.fontSeparator); //验签md5 if (!dataArr[1].equals(CommonUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())) { if (!dataArr[1].equals(ActionUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())) { return response.set(1, false, MessageUtils.getMessage("PasswordVerificationFailed")); } UsernamePasswordToken userToken = new UsernamePasswordToken(userName, dataArr[0]); @@ -125,14 +81,96 @@ Enumeration<String> attributeNames = servletContext.getAttributeNames(); QueryWrapper<User> queryWrapper = Wrappers.query(); queryWrapper.select("uId", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("uName", userName); User user = userMapper.selectOne(queryWrapper); queryWrapper.select("id", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("name", userName); User userInf = userMapper.selectOne(queryWrapper); //每个登录的用户都有一个全局变量,里面存着对应的SessionId; //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1 //查询账号状态 if(user == null){ if(userInf == null){ return response.set(1,false,MessageUtils.getMessage("AccountOrPasswordError")); } if (userInf.getStatus() != 1) { switch (userInf.getStatus()) { case 0: response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_CANCEL.getLabel()); break; case 2: response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_HIBERNATE.getLabel()); break; case 3: response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_LOCK.getLabel()); break; case 4: response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_LOCK_FAIL.getLabel()); break; default: response.setMsg(MessageUtils.getMessage("AccountException") + ": " + MessageUtils.getMessage("Nothing")); } return response.set(1, false); } //严格标准下的规则校验 if (YamlProperties.systemType == 2) { //登录之前,首先校验允许时间和登录ip boolean ipPass = true; String firstTime = userInf.getVisitTime().split("~")[0]; String lastTime = userInf.getVisitTime().split("~")[1]; List<String> ipRules = new LinkedList<>(); String ipRuleStr = userInf.getVisitIp(); ipRules = Arrays.asList(ipRuleStr.split(",")); Calendar instance = Calendar.getInstance(); String hourOfDay = String.format("%1$02d", instance.get(Calendar.HOUR_OF_DAY)); int minute = instance.get(Calendar.MINUTE); int second = instance.get(Calendar.SECOND); String nowTime = hourOfDay + ":" + minute + ":" + second; //登录时间校验 if (nowTime.compareTo(firstTime) >= 0 && nowTime.compareTo(lastTime) <= 0) { //登录ip校验 String clientIp = ActionUtil.getRequest().getRemoteAddr(); if (!ipRules.contains("*")) { for (String ipRule : ipRules) { ipPass = true; //ip规则格式为 * 或者 xxx.xxx.x.x String[] ipArr = clientIp.split("\\."); String[] ipRuleArr = ipRule.split("\\."); for (int i = 0; i < ipRuleArr.length; i++) { if (!ipRuleArr[i].equals("*") && !ipRuleArr[i].equals(ipArr[i])) { ipPass = false; break; } } if (ipPass) { break; } } } if (!ipPass) { return response.set(1, false, MessageUtils.getMessage("IPProhibition")); } } else { return response.set(1, false, MessageUtils.getMessage("LoginOutOfAllowed")); } //首次登录,密码修改;超过3个月未修改密码,强制修改密码 Date passwordUpdateTime = userInf.getPasswordUpdateTime(); Calendar now = Calendar.getInstance(); now.add(Calendar.MONTH, -3); if (passwordUpdateTime == null) { //密码修改时间为空,尚未修改初始口令 /*response.setCode(3); response.setData(false); response.setMsg(MessageUtils.getMessage("FirstLoginModify")); return response;*/ response.setData3(2); } else if (passwordUpdateTime.compareTo(now.getTime()) < 0) { /*response.setCode(2); response.setData(false); response.setMsg(MessageUtils.getMessage("ThreeMonthModify")); return response;*/ response.setData3(3); } } try { @@ -152,6 +190,16 @@ } } //查询账号密码错误限制次数 PageParam loginFailTimesLimit = pageParamMapper.findByCategoryId(9).get(0); if ((++loginFailTimes) == loginFailTimesLimit.getStatus()) { //达到限制次数,锁定账号 userService.lock(userInf.getId()); //清除登录错误次数统计 loginFailAttributeList.forEach(servletContext::removeAttribute); } else { servletContext.setAttribute(userName + "_login_fail_times_" + System.currentTimeMillis(), 0); } // CommonUtil.record(0, UserOperation.TYPE_LOGIN_FAIL.getType(), UserOperation.TYPE_LOGIN_FAIL.getTypeName(), UserOperation.TYPE_LOGIN_FAIL.getTypeNameEn()); return response.set(1, false, MessageUtils.getMessage("AccountOrPasswordError")); }else if(e instanceof AuthenticationException){ return response.set(1, false, "密码解析失败"); @@ -160,6 +208,11 @@ } if (subject.isAuthenticated()) { //验证密码时效性 int flag=userService.checkPasswordValidity(userInf); if(flag==-1){ return response.set(1, false, "密码长期未修改已失效,请修改密码"); } //登录成功 servletContext.setAttribute(userName, request.getSession().getId()); //日登录用户统计 @@ -170,9 +223,12 @@ } String dateStr = DateUtil.YYYY_MM_DD.format(new Date()); loginMap.put(userName, dateStr); /*//累计访问人次 pageParam2Service.updateVisitCount();*/ //Session存储当前用户及权限组列表 request.getSession().setAttribute("user", subject.getPrincipal()); //request.getSession().setMaxInactiveInterval(60*60*24); request.getSession().setMaxInactiveInterval(60*60*24); request.getSession().setAttribute("permits", ActionUtil.getGson().toJson(permitGroupUserService.getItemList(userInf.getId()))); //清除账号登录失败记录 while (attributeNames.hasMoreElements()) { String attributeName = attributeNames.nextElement(); @@ -181,91 +237,43 @@ } } //回写登录时间到数据库 userService.updateLoginTime(userInf.getId()); //查询用户对应的权限组id并返回给前端 LinkedList<Object> dataList = new LinkedList<>(); dataList.add(subject.getPrincipal()); PermitgroupUsr permitGroup = permitGroupUserService.getPermitGroup(userInf.getId()); if(permitGroup == null){ return response.set(1, false, MessageUtils.getMessage("userNoPermitGroup")); }else { int permitGroupId = permitGroup.getPermitGroupId(); dataList.add(permitGroupId); } //查询用户对应的班组标识 dataList.add(bjService.getGroupFlag(userInf.getId().intValue())); // CommonUtil.record(((User) subject.getPrincipal()).getId(), UserOperation.TYPE_LOGIN.getType(), UserOperation.TYPE_LOGIN.getTypeName(), UserOperation.TYPE_LOGIN.getTypeNameEn()); return response.setII(1, true, dataList, MessageUtils.getMessage("LoginSucceeded")); } return response.set(1, false, MessageUtils.getMessage("AuthenticationFailed")); } // 将所有登陆的用户的信息存到application中 public void setApplication(User user) { ServletContext application = CommonUtil.getApplication(); //查看全局中存储的users的Map的key-value集合 Map<String, UserClient> map = (Map) application.getAttribute("users"); if (map == null) { map = new HashMap<String, UserClient>(); } else { //如果集合中有值,则获取当前用户对应的用户信息,key为用户名username,Value为用户名,存储的时间 UserClient client = map.get(user.getName()); if (client != null) { //已存在 map.remove(user.getName()); } } Long login_time = new Date().getTime(); CommonUtil.getSession().setAttribute("login_time", login_time); map.put(user.getName(), new UserClient(CommonUtil.getRequest().getRemoteAddr(),user,login_time)); application.setAttribute("users", map); } /** * 开始查看application中是否有另一用使用该账号登陆 * * @return */ public Response checkUser(){ Response model = new Response(); Map<String, UserClient> map = (Map) CommonUtil.getApplication().getAttribute("users"); // System.out.println(map); if (map != null && map.size() > 0) { HttpSession session = CommonUtil.getSession(); // System.out.println(session); User user = (User) session.getAttribute("user"); Long login_time = (Long) session.getAttribute("login_time"); if (user != null && login_time != null) { UserClient client = map.get(user.getName()); if (client != null) { if (!login_time.equals(client.getLogin_times())) { model.setCode(1); //model.setMsg(getText("The landing on the account in another host, please log in again")); model.setMsg("The landing on the account in another host, please log in again"); } } } else { model.setCode(1); //model.setMsg(getText("You are not logged in, please log in")); model.setMsg("You are not logged in, please log in"); } } else { model.setCode(1); //model.setMsg(getText("You are not logged in, please log in")); model.setMsg("You are not logged in, please log in"); } return model; } //登录检测 public Response checkUserWebSocket(HttpSession httpSession){ Response model = new Response(); try { User user = (User) httpSession.getAttribute("user"); //System.out.println("webSocket:"+user); if(user!=null){ ServletContext servletContext = httpSession.getServletContext(); String sessionId = (String) servletContext.getAttribute(user.getName()); String sessionId = (String) httpSession.getServletContext().getAttribute(user.getName()); if(httpSession.getId().equals(sessionId)){ //用户在线状态校验成功,更新当前用户的在线时间 HashMap<String, Long> onlineMap = (HashMap<String, Long>) servletContext.getAttribute("online"); if(onlineMap == null){ onlineMap = new HashMap<>(); servletContext.setAttribute("online", onlineMap); } onlineMap.put(user.getName(), System.currentTimeMillis()); model.set(1,user,null); }else{ model.set(1,false,"不同主机登录"); if(sessionId.equals("123456")){ model.set(1,false,"身份权限变更,请重新登录"); }else{ model.set(1,false,"不同主机登录"); } //用户在其他主机登录,强迫用户在本机的session失效 httpSession.invalidate(); } @@ -273,7 +281,6 @@ else { model.set(1,false,"用户信息失效,请重新登录"); } }catch (Exception e){ model.set(1,false,"登录信息失效,重新登录"); } @@ -285,32 +292,4 @@ subject.logout(); } public Response loginNoPass(int uId, HttpServletRequest request) { Response<Object> response = new Response<>(); //根据uId获取用户的用户名和密码,进行类登录操作 User user = userService.getUinfByUId(uId); UsernamePasswordToken userToken = new UsernamePasswordToken(user.getName(),RSAUtil.decrypt(user.getPwd(),RSAUtil.getPrivateKey())); Subject subject = SecurityUtils.getSubject(); subject.login(userToken); if (subject.isAuthenticated()) { //每个登录的用户都有一个全局变量,里面存着对应的SessionId; //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1 //登录成功 ServletContext servletContext = request.getServletContext(); servletContext.setAttribute(user.getName(), request.getSession().getId()); //Session存储当前用户及权限组列表 request.getSession().setAttribute("user", subject.getPrincipal()); request.getSession().setMaxInactiveInterval(60 * 60 * 24); //回写登录时间到数据库 //查询用户对应的权限组id并返回给前端 LinkedList<Object> dataList = new LinkedList<>(); dataList.add(subject.getPrincipal()); return new Response<>().setII(1, true, dataList, "登录成功"); } return new Response().set(1,false,"认证未通过"); } } src/main/java/com/whyc/service/PermitGroupUserService.java
@@ -49,9 +49,9 @@ } } public PermitgroupUsr getPermitGroup(Long uId) { public PermitgroupUsr getPermitGroup(Integer uid) { QueryWrapper<PermitgroupUsr> wrapper = Wrappers.query(); wrapper.select("permit_group_id").eq("uid",uId).last(" limit 1"); wrapper.select("permit_group_id").eq("uid",uid).last(" limit 1"); return mapper.selectOne(wrapper); } src/main/java/com/whyc/service/UserLogService.java
@@ -2,6 +2,7 @@ import com.whyc.mapper.UserLogMapper; import com.whyc.pojo.db_user.UserLog; import com.whyc.util.ActionUtil; import com.whyc.util.CommonUtil; import org.springframework.stereotype.Service; @@ -17,18 +18,20 @@ public void add(Integer categoryId, Integer type, String message, String messageDetail) { HttpServletRequest request = CommonUtil.getRequest(); HttpServletRequest request = ActionUtil.getRequest(); UserLog userLog = new UserLog(); userLog.setCategory(categoryId); userLog.setType(type); userLog.setMessage(message); userLog.setMessageDetail(messageDetail); userLog.setUserId(CommonUtil.getUser().getId()); userLog.setUserName(CommonUtil.getUser().getName()); userLog.setUserId(ActionUtil.getUser().getId()); userLog.setUserName(ActionUtil.getUser().getName()); userLog.setTerminalIp(request.getRemoteAddr()); userLog.setCreateTime(new Date()); mapper.insert(userLog); } } src/main/java/com/whyc/service/UserService.java
@@ -1,19 +1,20 @@ package com.whyc.service; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.whyc.constant.UserConstant; import com.whyc.dto.Response; import com.whyc.dto.UserClient; import com.whyc.mapper.BaojigroupUsrMapper; import com.whyc.mapper.PageParamMapper; import com.whyc.mapper.PermitGroupUserMapper; import com.whyc.mapper.UserMapper; import com.whyc.pojo.db_app_sys.PageParam; import com.whyc.pojo.db_user.User; import com.whyc.util.ActionUtil; import com.whyc.util.CommonUtil; import com.whyc.util.MD5Util; import com.whyc.util.RSAUtil; import lombok.extern.slf4j.Slf4j; @@ -22,9 +23,6 @@ import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -32,7 +30,6 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.security.InvalidParameterException; import java.util.*; import java.util.stream.Collectors; @@ -48,6 +45,10 @@ @Autowired(required = false) private PermitGroupUserMapper pergroupUserMapper; @Resource private PageParamMapper pageParamMapper; //查询所有用户信息 public Response getAllUser(String uname, int pageCurr, int pageSize) { @@ -310,7 +311,19 @@ User User = mapper.selectOne(queryWrapper); return User; } /**锁定账号*/ public void lock(Integer uId) { UpdateWrapper<User> wrapper = Wrappers.update(); wrapper.set("status", UserConstant.ACCOUNT_STATUS_LOCK_FAIL.getValue()).set("lock_time",new Date()).eq("uId",uId); mapper.update((User) ActionUtil.objeNull,wrapper); } /**更新登录时间*/ public void updateLoginTime(Integer uId) { UpdateWrapper<User> wrapper = Wrappers.update(); wrapper.set("last_login_time", new Date()).eq("uId",uId); mapper.update((User) ActionUtil.objeNull,wrapper); } // 将所有登陆的用户的信息存到application中 public void setApplication(User user) { ServletContext application = ActionUtil.getApplication(); @@ -331,6 +344,23 @@ application.setAttribute("users", map); } //验证密码的时效性 public int checkPasswordValidity(User uinf) { int flag=1; //获取系统设置的密码时效(57,15) QueryWrapper wrapper=new QueryWrapper(); wrapper.eq("categoryId",15); wrapper.eq("id",57); wrapper.last("limit 1"); PageParam pageParam=pageParamMapper.selectOne(wrapper); if(pageParam!=null){ int dayDifference=ActionUtil.daysBetween(uinf.getPasswordUpdateTime(),new Date()); if((pageParam.getStatus()>0)&&(dayDifference>pageParam.getStatus())){ flag= -1; } } return flag; } public List<User> searchCS_All2() { return mapper.searchCS_All2(); src/main/java/com/whyc/util/CommonUtil.java
@@ -1,594 +1,77 @@ package com.whyc.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.whyc.constant.YamlProperties; import com.whyc.pojo.db_user.User; import org.apache.commons.codec.digest.DigestUtils; import org.apache.shiro.SecurityUtils; import com.whyc.service.UserLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.system.ApplicationHome; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import org.springframework.stereotype.Component; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.io.File; /** * 通用工具列 */ @Component public class CommonUtil { public static Object objectNull = null; private static UserLogService userLogService; public static String time_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss"; public static String time_yyyyMMdd = "yyyy-MM-dd"; public static String time_yyyyMMdd_HH_mm_ss = "yyyy-MM-dd_HH_mm_ss"; public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static SimpleDateFormat sdfwithOutday = new SimpleDateFormat("yyyy_MM"); public static SimpleDateFormat sdfwithday = new SimpleDateFormat("yyyy-MM-dd"); public static SimpleDateFormat sdfwithtime = new SimpleDateFormat("HH:mm:ss"); public static SimpleDateFormat sdfwithtime_yyyyMMdd_HH_mm_ss = new SimpleDateFormat(time_yyyyMMdd_HH_mm_ss); public static SimpleDateFormat sdfwithALL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String classesPath(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); return jarFile.toString(); } /** * 获取存放文件的根路径 * @return 返回存放文件的根路径 */ public static String getRootFile(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); String baseDirPath; if(YamlProperties.runModel == 1) { //开发路径 baseDirPath = jarFile.getParentFile().toString()+File.separator+"battery_gwm_file"+File.separator; }else { //打包路径 baseDirPath = jarFile.toString()+File.separator+"battery_gwm_file"+File.separator; } return baseDirPath; } /** * 获取项目所在文件夹路径 * @return 获取项目所在文件夹路径 */ public static String getProjectDir(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); String baseDirPath; if(YamlProperties.runModel == 1) { //开发路径 baseDirPath = jarFile.getParentFile().toString(); }else { //打包路径 baseDirPath = jarFile.toString(); } return baseDirPath; } /* * 获取HttpServletRequest */ public static HttpServletRequest getRequest(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); return request; } /* * 获取HttpServletResponse */ public static HttpServletResponse getResponse(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = requestAttributes.getResponse(); return response; } /* * 获取HttpSession */ public static HttpSession getSession(){ return getRequest().getSession(); } /** * * @return 返回application */ public static ServletContext getApplication(){ return getSession().getServletContext(); } public static User getUser(){ User principal = (User) SecurityUtils.getSubject().getPrincipal(); if(principal == null){ User user = new User(); user.setName("unLogged-in user"); user.setId(0); return user; }else { return principal; } } //获取application中互斥上传的标志位flag public static int getFlag(){ ServletContext app=getApplication(); int flag=(Integer) app.getAttribute("flag"); return flag; } ////给application中互斥上传的标志位flag设置值 public static void setFlag(int flag){ ServletContext app=getApplication(); app.setAttribute("flag", flag); } /* * 获取将对象转换成json格式 */ public static String tojson(Object obj){ Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); return gson.toJson(obj); } public static String chageDateToString(Date time,String type){ String msg = ""; SimpleDateFormat sdf = new SimpleDateFormat(type); msg = sdf.format(time); return msg; } /** * * @param datetype 需要解析的日期的格式如:"yyyy-MM-dd HH:mm:ss" * @return 得到对应的gson对象 */ public static Gson getGson(String datetype){ return new GsonBuilder().setDateFormat(datetype).create(); } /** * 获取默认的gson对象 * @return */ public static Gson getGson(){ return new Gson(); } public static <T> T getObject(String jsonstring,Type listtype){ Gson gson=new Gson(); T t=null; try { t=gson.fromJson(jsonstring, listtype); } catch (JsonSyntaxException e) { e.printStackTrace(); } return t; } /** * * @return 获取输出流 */ public static PrintWriter getOut(){ PrintWriter out =null; try { out=getResponse().getWriter(); } catch (IOException e) { e.printStackTrace(); } return out; } /** * * @param time java.util包中的时间 * @return java.sql时间 */ public static Date getSimpDate(Date time){ //System.out.println(time); return new java.sql.Date(time.getTime()); } //使用Base64加密 public static Object EncryptionBase64(Object obj){ String base64=null; if(obj!=null && obj.toString().length()>0){ base64=new BASE64Encoder().encode(obj.toString().getBytes()); base64 = base64.replaceAll("[\\s*\t\n\r]", ""); //替换加密后不换行 } return base64; } //使用Base64解密 public static Object DecryptionBase64(Object obj){ String base64=null; if(obj!=null && obj.toString().length()>0){ try { base64 = new String(new BASE64Decoder().decodeBuffer(obj.toString())); } catch (IOException e) { e.printStackTrace(); } } return base64; } //获取指定年月的天数 public static int getDaysByYearMonth(int year, int month) { Calendar a = Calendar.getInstance(); a.set(Calendar.YEAR, year); a.set(Calendar.MONTH, month - 1); a.set(Calendar.DATE, 1); a.roll(Calendar.DATE, -1); int maxDate = a.get(Calendar.DATE); return maxDate; @Autowired public void setUserLogService(UserLogService userLogService) { CommonUtil.userLogService = userLogService; } //获取某年某月的起始和结束时间 //需要注意的是:月份是从0开始的,比如说如果输入5的话,实际上显示的是4月份的最后一天,千万不要搞错了哦 public static String getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE)); return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59"; } public static String getFirstDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,cal.getMinimum(Calendar.DATE)); return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00"; } //获取当前时间的年份 public static int getNowYear(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int year = ca.get(Calendar.YEAR); //System.out.println(month); return year; } //获取当前时间的月份 public static int getNowMonth(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int month = ca.get(Calendar.MONTH) + 1; //System.out.println(month); return month; } //获取当前时间的日期 public static int getNowday(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int day = ca.get(Calendar.DAY_OF_MONTH); //System.out.println(month); return day; } //当前时间加上x小时 public static String getDateAdd(int minute){ Date date = new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MINUTE, minute); return new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(c.getTime()); /**获取当前Session中的属性user*/ public static User getUser(HttpServletRequest request) { return (User) request.getSession().getAttribute("user"); } //使用MD5加密 public static Object EncryptionMD5(Object obj){ String md5=null; if(obj!=null && obj.toString().length()>0){ md5= DigestUtils.md5Hex(obj.toString()); } return md5; } //获取时间的年份 public static int getDateYear(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int year = ca.get(Calendar.YEAR); //System.out.println(month); return year; public static String classesPath(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); return jarFile.toString(); } //获取时间的月份 public static int getDateMonth(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int month = ca.get(Calendar.MONTH) + 1; //System.out.println(month); return month; } //获取时间的日期 public static int getDateday(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int day = ca.get(Calendar.DAY_OF_MONTH); //System.out.println(month); return day; } //当前时间加上x小时 public static Date getDateAdd(Date date,int minute){ Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MINUTE, minute); return c.getTime(); } //给定时间判断与当前时间相比是否为老电池(numYear为时间期限几年) public static int judgeBatt(Date inUseDate,Date date,int numYear){ int judge=0; inUseDate.setYear(CommonUtil.getDateYear(inUseDate)+numYear-1900); //System.out.println("inUseDate: "+inUseDate); if(inUseDate.after(date)){ judge=1; }else{ judge=0; } return judge; } //获取某年某月某日内的时间<date为执行时间的时分秒设置为提醒时间段的时分秒> public static Date getWorkDay(Date date,Date noticeTime) { Calendar cal = Calendar.getInstance(); cal.setTime(date); //设置时间为执行日期 int year = cal.get(Calendar.YEAR);//年 int month = cal.get(Calendar.MONTH);//月 int day = cal.get(Calendar.DAY_OF_MONTH);//日 cal.setTime(noticeTime);//设置时间为提醒时间段 /*int hour=cal.get(Calendar.HOUR_OF_DAY);//时 int minute=cal.get(Calendar.MINUTE);//分 int second=cal.get(Calendar.SECOND);//秒*/ cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,day); return cal.getTime(); } //获取某年某月某日起始时间/结束时间 public static String getDayTime(int year, int month,int day,int type) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,day); if(type==1){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00"; } else if(type==2){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"09:00:00"; }else if(type==3){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"17:00:00"; }else if(type==4){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59"; public static String getRootFile(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); String baseDirPath; if(YamlProperties.runModel == 1) { //开发路径 baseDirPath = jarFile.getParentFile().toString()+File.separator+"fg_file"+File.separator; }else { //打包路径 baseDirPath = jarFile.toString()+File.separator+"fg_file"+File.separator; } return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime()); } return baseDirPath; } //计算电池使用了多少个月 public static int battInuseMonth(Date inUseDate){ int useDay=0; Date nowd=new Date();//当前时间 int inuseY= CommonUtil.getDateYear(inUseDate); int inuseM= CommonUtil.getDateMonth(inUseDate); int nowY= CommonUtil.getDateYear(nowd); int nowM= CommonUtil.getDateMonth(nowd); if(inuseY==nowY){ useDay=nowM-inuseM; }else{ useDay=(nowY-inuseY)*12+nowM-inuseM; } return useDay; } //计算日期之间相差的天数 public static int daysBetween(Date smdate,Date bdate) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); try { smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_days=(time2-time1)/(1000*3600*24); return Math.abs(Integer.parseInt(String.valueOf(between_days))); } //计算日期之间相差的小时 public static int HoursBetween(Date smdate,Date bdate) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_hours=(time2-time1)/(1000*3600); //System.out.println("between_hours:"+between_hours); return (int) Math.abs(between_hours); } //比较两个时间的大小 public static int compareDate(Date d1,Date d2){ if (d1.getTime() > d2.getTime()) { return 1; } else if (d1.getTime() < d2.getTime()) { return -1; } else {//相等 return 0; } } /** * @Description: 根据图片地址转换为base64编码字符串 * @Author: * @CreateTime: * @return * 获取项目所在文件夹路径 * @return 获取项目所在文件夹路径 */ public static String getImageStr(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); public static String getProjectDir(){ ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class); File jarFile = applicationHome.getDir(); String baseDirPath; if (YamlProperties.runModel == 1) { //开发路径 baseDirPath = jarFile.getParentFile().toString(); } else { //打包路径 baseDirPath = jarFile.toString(); } // 加密 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); return baseDirPath; } /** * @Description: 将base64编码字符串转换为图片 * @Author: * @CreateTime: * @param imgStr base64编码字符串 * @param path 图片路径-具体到文件 * @return */ public static boolean generateImage(String imgStr, String path) { if (imgStr == null) { return false; } BASE64Decoder decoder = new BASE64Decoder(); try { // 解密 byte[] b = decoder.decodeBuffer(imgStr); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } OutputStream out = new FileOutputStream(path); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 将输入流中的数据读到字节数组中 * @param is * @return * 手动记录特定日志 */ public static byte[] IStoByteArr(InputStream is){ byte[] b = null; try { b = new byte[is.available()]; is.read(b); } catch (IOException e) { e.printStackTrace(); } finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return b; public static void record(int category, int type, String message,String messageDetail) { userLogService.add(category, type, message, messageDetail); } /** * 创建指定的文件文件,若不存在则先创建指定的文件夹再创建指定的文件 * @param filePath */ public static void createFilefolderIFNotExist(String filePath){ File f = new File(filePath); if(!f.exists()){ if(!f.getParentFile().exists()){ f.getParentFile().mkdirs(); } } } /** * 秒转换小时-分-秒analytics/util/DateUtil.java * * @param seconds 秒为单位 比如..600秒 * @return 比如...2小时3分钟52秒 */ public static String secToTime(int seconds) { int hour = seconds / 3600; int minute = (seconds - hour * 3600) / 60; int second = (seconds - hour * 3600 - minute * 60); StringBuffer sb = new StringBuffer(); if (hour > 0) { if(hour<10){ sb.append("0"+hour + ":"); }else{ sb.append(hour + ":"); } }else{ sb.append("00"+ ":"); } if (minute > 0) { if(minute<10){ sb.append("0"+minute + ":"); }else{ sb.append(minute + ":"); } }else{ sb.append("00" + ":"); } if (second > 0) { if(second<10){ sb.append("0"+second); }else{ sb.append(second); } }else{ sb.append("00"); } return sb.toString(); } //获取当前系统的语言环境 public static String getLang() { Locale locale = Locale.getDefault();//对Locale类实例化定义 String lang = locale.getLanguage(); String str = (String) CommonUtil.getSession().getAttribute("lang"); if (str != null) { lang = str; } return lang; } } src/main/resources/config/application-dev.yml
@@ -1,3 +1,6 @@ system: #系统类型:1(普通,无限制),2(严格-gw标准),3(严格-签名) type: 1 #服务端口号 server: port: 8108 src/main/resources/config/application-prod.yml
@@ -1,3 +1,6 @@ system: #系统类型:1(普通,无限制),2(严格-gw标准),3(严格-签名) type: 1 #服务端口号 server: port: 8108 src/main/resources/mapper/BaojigroupUsrMapper.xml
@@ -19,4 +19,10 @@ and bu.baoji_id = #{id} and u.uid>100 </select> <select id="getGroupFlag" resultType="java.lang.Integer"> select b.team_flag from db_user.tb_baojigroup_usr bu,db_user.tb_baojigroup b where bu.baoji_group_id = b.baoji_group_id and b.team_flag = 1 and bu.uid = #{uid} limit 1 </select> </mapper>