Commit 774fd11e3f3ec07a73c8c5f7b52c1ce144360e6b

Authored by 王通
1 parent ca0c3273

1.CSP header

2.密码验证、强制更新弱密码,管理员重置密码,解锁账号
3.白名单套装
4.密码错误多次锁定账号
Showing 28 changed files with 2681 additions and 1273 deletions

Too many changes to show.

To preserve performance only 28 of 42 files are displayed.

src/main/java/com/bsth/Application.java
1   -package com.bsth;
2   -
3   -import com.fasterxml.jackson.databind.ObjectMapper;
4   -import com.fasterxml.jackson.databind.SerializationFeature;
5   -import org.springframework.boot.SpringApplication;
6   -import org.springframework.boot.autoconfigure.SpringBootApplication;
7   -import org.springframework.boot.builder.SpringApplicationBuilder;
8   -import org.springframework.boot.context.web.SpringBootServletInitializer;
9   -import org.springframework.context.annotation.Bean;
10   -import org.springframework.context.annotation.Primary;
11   -import org.springframework.transaction.annotation.EnableTransactionManagement;
12   -
13   -import java.util.concurrent.Executors;
14   -import java.util.concurrent.ScheduledExecutorService;
15   -
16   -@EnableTransactionManagement
17   -@SpringBootApplication
18   -public class Application extends SpringBootServletInitializer {
19   -
20   - public static ScheduledExecutorService mainServices = Executors.newScheduledThreadPool(18);
21   -
22   - @Override
23   - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
24   - return application.sources(Application.class);
25   - }
26   -
27   - @Bean
28   - @Primary
29   - public ObjectMapper objectMapper() {
30   - ObjectMapper objectMapper = new ObjectMapper();
31   - objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
32   -
33   - return objectMapper;
34   - }
35   -
36   - public static void main(String[] args) throws Exception {
37   - SpringApplication.run(Application.class, args);
38   - }
  1 +package com.bsth;
  2 +
  3 +import com.bsth.data.SystemParamCache;
  4 +import com.fasterxml.jackson.databind.ObjectMapper;
  5 +import com.fasterxml.jackson.databind.SerializationFeature;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.boot.SpringApplication;
  8 +import org.springframework.boot.autoconfigure.SpringBootApplication;
  9 +import org.springframework.boot.builder.SpringApplicationBuilder;
  10 +import org.springframework.boot.context.web.SpringBootServletInitializer;
  11 +import org.springframework.context.annotation.Bean;
  12 +import org.springframework.context.annotation.Primary;
  13 +import org.springframework.transaction.annotation.EnableTransactionManagement;
  14 +
  15 +import java.util.concurrent.Executors;
  16 +import java.util.concurrent.ScheduledExecutorService;
  17 +
  18 +@EnableTransactionManagement
  19 +@SpringBootApplication
  20 +public class Application extends SpringBootServletInitializer {
  21 +
  22 + public static ScheduledExecutorService mainServices = Executors.newScheduledThreadPool(21);
  23 +
  24 + @Autowired
  25 + private SystemParamCache systemParamCache;
  26 +
  27 + @Override
  28 + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  29 + return application.sources(Application.class);
  30 + }
  31 +
  32 + @Bean
  33 + @Primary
  34 + public ObjectMapper objectMapper() {
  35 + ObjectMapper objectMapper = new ObjectMapper();
  36 + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  37 +
  38 + return objectMapper;
  39 + }
  40 +
  41 + public static void main(String[] args) throws Exception {
  42 + SpringApplication.run(Application.class, args);
  43 + }
39 44 }
40 45 \ No newline at end of file
... ...
src/main/java/com/bsth/common/Constants.java
1   -package com.bsth.common;
2   -
3   -/**
4   - *
5   - * @ClassName: Constants
6   - * @Description: TODO(常量类)
7   - * @author PanZhao
8   - * @date 2016年3月18日 下午11:06:53
9   - *
10   - */
11   -public class Constants {
12   -
13   - /**
14   - * 不需要拦截的资源
15   - */
16   - public static final String LOGIN = "/user/login/**";
17   - public static final String LOGIN_PAGE = "/login.html";
18   - public static final String ASSETS_URL = "/assets/**";
19   - public static final String FAVICON_URL = "/favicon.ico";
20   - public static final String METRONIC_URL = "/metronic_v4.5.4/**";
21   - public static final String LOGIN_FAILURE = "/user/loginFailure";
22   - public static final String CAPTCHA = "/captcha.jpg";
23   - public static final String XIANDIAO_LOGIN = "/xdlogin.html";
24   - public static final String IPAD_IMG_URL = "/apple-touch-icon-72x72.png";
25   -
26   - //对外的营运数据接口
27   - public static final String SERVICE_INTERFACE = "/companyService/**";
28   -
29   - /**
30   - * 线调部分子页面不做拦截,便于浏览器缓存
31   - */
32   - public static final String XD_CHILD_PAGES = "/real_control_v2/**";
33   - public static final String XD_REAL_GPS = "/gps/real/line";
34   - //public static final String XD_TEMPS = "/pages/control/line/temps/**";
35   -
36   - //车载网关上行接口
37   - public static final String UPSTREAM_URL = "/control/upstream";
38   - //rfid 上传入口
39   - public static final String UP_RFID_URL = "/rfid/**";
40   -
41   - public static final String SESSION_USERNAME = "sessionUserName";
42   - public static final String COMPANY_AUTHORITYS = "cmyAuths";
43   - public static final String STATION_AND_SECTION_COUNT = "/station/updateStationAndSectionCode";
44   -
45   - /**
46   - * 解除调度指令和班次的外键约束
47   - */
48   - public static final String REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch=?";
49   -
50   - /**
51   - * 批量解除调度指令和班次的外键约束
52   - */
53   - public static final String MULTI_REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch in ";
54   -}
  1 +package com.bsth.common;
  2 +
  3 +/**
  4 + *
  5 + * @ClassName: Constants
  6 + * @Description: TODO(常量类)
  7 + * @author PanZhao
  8 + * @date 2016年3月18日 下午11:06:53
  9 + *
  10 + */
  11 +public class Constants {
  12 +
  13 + /**
  14 + * 不需要拦截的资源
  15 + */
  16 + public static final String LOGIN = "/user/login/**";
  17 + public static final String ORIGINAL_LOGIN_PAGE = "/login.html";
  18 + public static String LOGIN_PAGE = "/login.html";
  19 + public static final String ASSETS_URL = "/assets/**";
  20 + public static final String FAVICON_URL = "/favicon.ico";
  21 + public static final String METRONIC_URL = "/metronic_v4.5.4/**";
  22 + public static final String LOGIN_FAILURE = "/user/loginFailure";
  23 + public static final String CAPTCHA = "/captcha.jpg";
  24 + public static final String XIANDIAO_LOGIN = "/xdlogin.html";
  25 + public static final String IPAD_IMG_URL = "/apple-touch-icon-72x72.png";
  26 +
  27 + //对外的营运数据接口
  28 + public static final String SERVICE_INTERFACE = "/companyService/**";
  29 +
  30 + /**
  31 + * 线调部分子页面不做拦截,便于浏览器缓存
  32 + */
  33 + public static final String XD_CHILD_PAGES = "/real_control_v2/**";
  34 + public static final String XD_REAL_GPS = "/gps/real/line";
  35 + //public static final String XD_TEMPS = "/pages/control/line/temps/**";
  36 +
  37 + //车载网关上行接口
  38 + public static final String UPSTREAM_URL = "/control/upstream";
  39 + //rfid 上传入口
  40 + public static final String UP_RFID_URL = "/rfid/**";
  41 +
  42 + public static final String SESSION_USERNAME = "sessionUserName";
  43 + public static final String COMPANY_AUTHORITYS = "cmyAuths";
  44 + public static final String STATION_AND_SECTION_COUNT = "/station/updateStationAndSectionCode";
  45 +
  46 + /**
  47 + * 解除调度指令和班次的外键约束
  48 + */
  49 + public static final String REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch=?";
  50 +
  51 + /**
  52 + * 批量解除调度指令和班次的外键约束
  53 + */
  54 + public static final String MULTI_REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch in ";
  55 +
  56 + /**
  57 + * 批量解除子任务和班次的外键约束
  58 + */
  59 + public static final String MULTI_REMOVE_CHILDTASK_SCH_FK = "update bsth_c_s_child_task set schedule=NULL where schedule in ";
  60 +
  61 + public static final String WEAK_CIPHER = "weakCipher";
  62 +
  63 + public static final String FILE_AUTH = "/.well-known/pki-validation/fileauth.txt";
  64 +
  65 + public static final String SSO_TOKEN = "ssoToken";
  66 +
  67 + public static final String RESOURCE_AUTHORITYS = "resourceAuthoritys";
  68 +}
... ...
src/main/java/com/bsth/common/SystemParamKeys.java 0 → 100644
  1 +package com.bsth.common;
  2 +
  3 +/**
  4 + * @author Hill
  5 + */
  6 +public class SystemParamKeys {
  7 +
  8 + public static final String SPECIAL_ROLES = "special.roles";
  9 +
  10 + public static final String SPECIAL_DAYS = "special.days";
  11 +
  12 + public static final String URL_HTTP_GPS_REAL_CACHE = "url.http.gps.real.cache";
  13 +
  14 + public static final String URL_HTTP_GPS_REAL = "url.http.gps.real";
  15 +
  16 + public static final String URL_HTTP_DIRECTIVE = "url.http.directive";
  17 +
  18 + public static final String URL_HTTP_RFID = "url.http.rfid";
  19 +
  20 + public static final String URL_HTTP_REPORT = "url.http.report.%s";
  21 +
  22 + public static final String URL_HTTP_TICKETING = "url.http.ticketing";
  23 +
  24 + public static final String URL_HTTP_DSM_ACK = "url.http.dsm.ack";
  25 +
  26 + public static final String URL_HTTP_CP_ACK = "url.http.cp.ack";
  27 +
  28 + public static final String MAIL_ADMIN = "mail.admin";
  29 +
  30 + public static final String MAIL_WAYBILL = "mail.waybill";
  31 +
  32 + public static final String ENABLED_FIRST_LAST_GENERATION = "enabled.first.last.generation";
  33 +
  34 + public static final String ENABLED_FILTER_SQL_INJECTION = "enabled.filter.sql.injection";
  35 +
  36 + public static final String ENABLED_SSO = "enabled.sso";
  37 +
  38 + public static final String SSO_SYSTEM_CODE = "sso.system.code";
  39 +
  40 + public static final String URL_HTTP_SSO_LOGIN = "url.http.sso.login";
  41 +
  42 + public static final String URL_HTTP_SSO_LOGOUT = "url.http.sso.logout";
  43 +
  44 + public static final String URL_HTTP_SSO_AUTH = "url.http.sso.auth";
  45 +
  46 + public static final String URL_HTTP_MAINTENANCE = "url.http.maintenance";
  47 +
  48 + public static final String ENABLED_WHITE_IP = "enabled.white.ip";
  49 +
  50 + public static final String ENABLED_FILTER_AUTHORITY = "enabled.filter.authority";
  51 +
  52 + public static final String URL_HTTP_DVR = "url.http.dvr";
  53 +
  54 + public static final String URL_HTTP_DVR_PWD = "url.http.dvr.pwd";
  55 +}
0 56 \ No newline at end of file
... ...
src/main/java/com/bsth/controller/realcontrol/AdminUtilsController.java
1 1 package com.bsth.controller.realcontrol;
2 2  
3   -import ch.qos.logback.classic.Level;
4   -import ch.qos.logback.classic.LoggerContext;
  3 +import java.util.*;
  4 +
5 5 import com.bsth.data.BasicData;
  6 +import com.bsth.service.SectionService;
  7 +import com.bsth.service.StationService;
6 8 import com.bsth.data.directive.DayOfDirectives;
7 9 import com.bsth.data.directive.DirectivesPstThread;
  10 +import com.bsth.data.directive.GatewayHttpUtils;
8 11 import com.bsth.data.gpsdata_v2.cache.GeoCacheData;
9 12 import com.bsth.data.gpsdata_v2.handlers.overspeed.OverspeedProcess;
  13 +import com.bsth.data.gpsdata_v2.load.GatewayHttpLoader;
  14 +import com.bsth.data.gpsdata_v2.load.SocketClientLoader;
10 15 import com.bsth.data.gpsdata_v2.thread.GpsDataLoaderThread;
11 16 import com.bsth.data.msg_queue.DirectivePushQueue;
12 17 import com.bsth.data.msg_queue.WebSocketPushQueue;
13 18 import com.bsth.data.pilot80.PilotReport;
14 19 import com.bsth.data.schedule.DayOfSchedule;
15 20 import com.bsth.entity.realcontrol.ScheduleRealInfo;
16   -import com.bsth.websocket.handler.SendUtils;
  21 +import com.bsth.service.SystemParamService;
  22 +import com.bsth.util.MailUtils;
17 23 import com.fasterxml.jackson.databind.ObjectMapper;
18 24 import org.slf4j.Logger;
19 25 import org.slf4j.LoggerFactory;
... ... @@ -22,10 +28,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
22 28 import org.springframework.web.bind.annotation.RequestParam;
23 29 import org.springframework.web.bind.annotation.RestController;
24 30  
25   -import java.util.HashMap;
26   -import java.util.List;
27   -import java.util.Map;
28   -import java.util.Set;
  31 +import com.bsth.websocket.handler.SendUtils;
  32 +
  33 +import ch.qos.logback.classic.Level;
  34 +import ch.qos.logback.classic.LoggerContext;
29 35  
30 36 /**
31 37 * Created by panzhao on 2017/4/14.
... ... @@ -56,8 +62,29 @@ public class AdminUtilsController {
56 62 PilotReport pilotReport;
57 63  
58 64 @Autowired
  65 + private MailUtils mailUtils;
  66 +
  67 + @Autowired
59 68 private BasicData.BasicDataLoader basicDataLoader;
60 69  
  70 + @Autowired
  71 + private SectionService sectionService;
  72 +
  73 + @Autowired
  74 + private StationService stationService;
  75 +
  76 + @Autowired
  77 + private SystemParamService systemParamService;
  78 +
  79 + @Autowired
  80 + private SocketClientLoader socketClientLoader;
  81 +
  82 + @Autowired
  83 + private GatewayHttpLoader gatewayHttpLoader;
  84 +
  85 + @Autowired
  86 + private GatewayHttpUtils gatewayHttpUtils;
  87 +
61 88 /**
62 89 * 出现重复班次的车辆
63 90 *
... ... @@ -218,9 +245,71 @@ public class AdminUtilsController {
218 245  
219 246 @RequestMapping("/reloadSystemParam")
220 247 public String reloadSystemParam() {
  248 + try {
  249 + systemParamService.refresh();
  250 +
  251 + return "success";
  252 + } catch (Exception e) {
  253 + e.printStackTrace();
  254 + }
  255 +
  256 + return "error";
  257 + }
  258 +
  259 + @RequestMapping("/applySystemParam")
  260 + public String applySystemParam() {
  261 + try {
  262 + socketClientLoader.afterPropertiesSet();
  263 + gatewayHttpLoader.afterPropertiesSet();
  264 + gatewayHttpUtils.afterPropertiesSet();
  265 + //rfidHttpLoader.afterPropertiesSet();
  266 + //ssoConfig.afterPropertiesSet();
  267 +
  268 + return "success";
  269 + } catch (Exception e) {
  270 + e.printStackTrace();
  271 + }
  272 +
  273 + return "error";
  274 + }
  275 +
  276 + @RequestMapping("/reloadAndApplySystemParam")
  277 + public String reloadAndApplySystemParam() {
  278 + try {
  279 + systemParamService.refresh();
  280 +
  281 + socketClientLoader.afterPropertiesSet();
  282 + gatewayHttpLoader.afterPropertiesSet();
  283 + gatewayHttpUtils.afterPropertiesSet();
  284 + //rfidHttpLoader.afterPropertiesSet();
  285 + //ssoConfig.afterPropertiesSet();
  286 +
  287 + return "success";
  288 + } catch (Exception e) {
  289 + e.printStackTrace();
  290 + }
  291 +
  292 + return "error";
  293 + }
  294 +
  295 + @RequestMapping("/section/translateWgs2Bd")
  296 + public String translateWgs2Bd1() {
  297 + Map<String, Object> result = new HashMap<>();
  298 + try {
  299 + //sectionService.translateWgs2Bd();
  300 + return "success";
  301 + } catch (Exception e) {
  302 + e.printStackTrace();
  303 + }
  304 +
  305 + return "error";
  306 + }
  307 +
  308 + @RequestMapping("/station/translateWgs2Bd")
  309 + public String translateWgs2Bd2() {
221 310 Map<String, Object> result = new HashMap<>();
222 311 try {
223   - basicDataLoader.loadSystemParam();
  312 + //stationService.translateWgs2Bd();
224 313 return "success";
225 314 } catch (Exception e) {
226 315 e.printStackTrace();
... ...
src/main/java/com/bsth/controller/sys/RoleController.java
1   -package com.bsth.controller.sys;
2   -
3   -import java.util.Map;
4   -
5   -import org.springframework.beans.factory.annotation.Autowired;
6   -import org.springframework.web.bind.annotation.RequestMapping;
7   -import org.springframework.web.bind.annotation.RequestMethod;
8   -import org.springframework.web.bind.annotation.RequestParam;
9   -import org.springframework.web.bind.annotation.RestController;
10   -
11   -import com.bsth.controller.BaseController;
12   -import com.bsth.entity.sys.Role;
13   -import com.bsth.service.sys.RoleService;
14   -
15   -@RestController
16   -@RequestMapping("role")
17   -public class RoleController extends BaseController<Role, Integer>{
18   -
19   -
20   - @Autowired
21   - RoleService roleService;
22   -
23   - /**
24   - *
25   - * @Title: settRoleModules
26   - * @Description: TODO(为角色设置模块,全量覆盖)
27   - * @param @param roleId 角色ID
28   - * @param @param mIds 模块ID字符串(1,2,3,4)
29   - * @throws
30   - */
31   - @RequestMapping(value = "/settModules", method = RequestMethod.POST)
32   - public Map<String, Object> settRoleModules(@RequestParam Integer roleId,@RequestParam String mIds){
33   - return roleService.settRoleModules(roleId, mIds);
34   - }
35   -
36   - /**
37   - *
38   - * @Title: roleInfo
39   - * @Description: TODO(角色信息)
40   - * @param @param id 角色ID
41   - * @throws
42   - */
43   - @RequestMapping(value = "/roleInfo")
44   - public Map<String, Object> roleInfo(@RequestParam Integer id){
45   - return roleService.roleInfo(id);
46   - }
47   -}
  1 +package com.bsth.controller.sys;
  2 +
  3 +import java.util.Map;
  4 +
  5 +import org.springframework.beans.factory.annotation.Autowired;
  6 +import org.springframework.web.bind.annotation.RequestMapping;
  7 +import org.springframework.web.bind.annotation.RequestMethod;
  8 +import org.springframework.web.bind.annotation.RequestParam;
  9 +import org.springframework.web.bind.annotation.RestController;
  10 +
  11 +import com.bsth.controller.BaseController;
  12 +import com.bsth.entity.sys.Role;
  13 +import com.bsth.service.sys.RoleService;
  14 +
  15 +@RestController
  16 +@RequestMapping("role")
  17 +public class RoleController extends BaseController<Role, Integer>{
  18 +
  19 +
  20 + @Autowired
  21 + RoleService roleService;
  22 +
  23 + /**
  24 + * @param @param map
  25 + * @throws
  26 + * @Title: list
  27 + * @Description: TODO(查询下级)
  28 + */
  29 + @RequestMapping(value = "/findSubordinate", method = RequestMethod.GET)
  30 + public Map<String, Object> findSubordinate() {
  31 + return roleService.findSubordinate();
  32 + }
  33 +
  34 + /**
  35 + * @param @param map
  36 + * @Description: TODO(添加角色)
  37 + * @return
  38 + */
  39 + @RequestMapping(value = "/add", method = RequestMethod.POST)
  40 + public Map<String, Object> add(Role role){
  41 + return roleService.add(role);
  42 + }
  43 +
  44 + /**
  45 + *
  46 + * @Title: settRoleModules
  47 + * @Description: TODO(为角色设置模块,全量覆盖)
  48 + * @param @param roleId 角色ID
  49 + * @param @param mIds 模块ID字符串(1,2,3,4)
  50 + * @throws
  51 + */
  52 + @RequestMapping(value = "/settModules", method = RequestMethod.POST)
  53 + public Map<String, Object> settRoleModules(@RequestParam Integer roleId,@RequestParam String mIds){
  54 + return roleService.settRoleModules(roleId, mIds);
  55 + }
  56 +
  57 + /**
  58 + *
  59 + * @Title: roleInfo
  60 + * @Description: TODO(角色信息)
  61 + * @param @param id 角色ID
  62 + * @throws
  63 + */
  64 + @RequestMapping(value = "/roleInfo")
  65 + public Map<String, Object> roleInfo(@RequestParam Integer id){
  66 + return roleService.roleInfo(id);
  67 + }
  68 +
  69 + /**
  70 + * 检查操作合法性 操作的是否是下级角色
  71 + * @param operationRoleId 下级角色Id
  72 + * @return
  73 + */
  74 + @RequestMapping(value = "/checkOperationLegality")
  75 + public boolean checkOperationLegality(@RequestParam Integer operationRoleId){
  76 + return roleService.checkOperationLegality(operationRoleId);
  77 + }
  78 +}
... ...
src/main/java/com/bsth/controller/sys/UserController.java
1   -package com.bsth.controller.sys;
2   -
3   -import com.bsth.common.Constants;
4   -import com.bsth.common.ResponseCode;
5   -import com.bsth.controller.BaseController;
6   -import com.bsth.controller.sys.dto.CompanyData;
7   -import com.bsth.controller.sys.util.RSAUtils;
8   -import com.bsth.entity.sys.CompanyAuthority;
9   -import com.bsth.entity.sys.SysUser;
10   -import com.bsth.security.util.SecurityUtils;
11   -import com.bsth.service.logger.UserSignService;
12   -import com.bsth.service.sys.CompanyAuthorityService;
13   -import com.bsth.service.sys.SysUserService;
14   -import com.google.common.collect.ArrayListMultimap;
15   -import org.apache.commons.lang3.StringUtils;
16   -import org.slf4j.Logger;
17   -import org.slf4j.LoggerFactory;
18   -import org.springframework.beans.factory.annotation.Autowired;
19   -import org.springframework.security.authentication.BadCredentialsException;
20   -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
21   -import org.springframework.security.web.authentication.session.SessionAuthenticationException;
22   -import org.springframework.web.bind.annotation.RequestMapping;
23   -import org.springframework.web.bind.annotation.RequestMethod;
24   -import org.springframework.web.bind.annotation.RequestParam;
25   -import org.springframework.web.bind.annotation.RestController;
26   -
27   -import javax.servlet.http.HttpServletRequest;
28   -import javax.servlet.http.HttpSession;
29   -import java.util.*;
30   -
31   -@RestController
32   -@RequestMapping("user")
33   -public class UserController extends BaseController<SysUser, Integer> {
34   -
35   - Logger logger = LoggerFactory.getLogger(this.getClass());
36   -
37   - @Autowired
38   - SysUserService sysUserService;
39   -
40   - @Autowired
41   - CompanyAuthorityService companyAuthorityService;
42   -
43   - @Autowired
44   - UserSignService userLogInoutService;
45   -
46   - @RequestMapping(value = "/login/jCryptionKey")
47   - public Map<String, Object> jCryptionKey(HttpServletRequest request) {
48   - //公匙返回页面
49   - Map<String, Object> rs = new HashMap<>();
50   - rs.put("publickey", RSAUtils.generateBase64PublicKey());
51   - return rs;
52   - }
53   -
54   - //需要验证码的账号
55   - public static Map<String, Integer> captchaMap = new HashMap<>();
56   -
57   - @RequestMapping(value = "/login", method = RequestMethod.POST)
58   - public Map<String, Object> login(HttpServletRequest request, @RequestParam String userName,
59   - @RequestParam String password, String captcha) {
60   -
61   - Map<String, Object> rs = new HashMap<>();
62   - rs.put("status", ResponseCode.ERROR);
63   - try {
64   - HttpSession session = request.getSession();
65   - rs.put("captcha", session.getAttribute("captcha"));
66   -
67   - if (captchaMap.get(userName) != null && captchaMap.get(userName) >= 3) {
68   - //校验验证码
69   - String verCode = (String) session
70   - .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
71   -
72   - if (StringUtils.isBlank(captcha))
73   - return put(rs, "msg", "请输入验证码");
74   -
75   - if (!verCode.equals(captcha))
76   - return put(rs, "msg", "验证码有误,请刷新后重新输入");
77   - }
78   -
79   - //解密RSA
80   - try {
81   - userName = RSAUtils.decryptBase64(userName);
82   - password = RSAUtils.decryptBase64(password);
83   - } catch (RuntimeException e) {
84   - return put(rs, "msg", "decrypt RSA fail!可能页面已过期,尝试刷新页面。");
85   - }
86   -
87   - SysUser user = sysUserService.findByUserName(userName);
88   - if (null == user)
89   - return put(rs, "msg", "不存在的用户");
90   -
91   - if (!user.isEnabled())
92   - return put(rs, "msg", "该用户已被锁定,请联系管理员");
93   -
94   - // 校验密码
95   - boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
96   - if (!matchStatus) {
97   - rs.put("msg", "密码有误");
98   -
99   - Integer captchSize = captchaMap.get(userName);
100   - if (null == captchSize)
101   - captchSize = 0;
102   -
103   - captchSize++;
104   - captchaMap.put(userName, captchSize);
105   - return rs;
106   - }
107   -
108   - // 登录
109   - SecurityUtils.login(user, request);
110   - //session里写入用户名,webSocket连接时标识身份用
111   - session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
112   -
113   - //获取公司权限数据
114   - List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
115   - session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
116   -
117   - captchaMap.remove(userName);
118   - rs.put("status", ResponseCode.SUCCESS);
119   -
120   - // 记录登录日志
121   - userLogInoutService.userLogIn(user.getUserName(), session.getId(), new Date());
122   - } catch (Exception e) {
123   - logger.error("", e);
124   - rs.put("msg", "服务器出现异常,请联系管理员");
125   - }
126   - return rs;
127   - }
128   -
129   - @RequestMapping(value = "/change_user", method = RequestMethod.POST)
130   - public Map<String, Object> changeUser(HttpServletRequest request, @RequestParam String userName,
131   - @RequestParam String password) {
132   -
133   - Map<String, Object> rs = new HashMap<>();
134   - rs.put("status", ResponseCode.ERROR);
135   - try {
136   - HttpSession session = request.getSession();
137   -
138   - SysUser user = sysUserService.findByUserName(userName);
139   - if (null == user)
140   - return put(rs, "msg", "不存在的用户");
141   -
142   - if (!user.isEnabled())
143   - return put(rs, "msg", "该用户已被锁定,请联系管理员");
144   -
145   - // 校验密码
146   - boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
147   - if (!matchStatus)
148   - return put(rs, "msg", "密码有误");
149   -
150   - // 登录
151   - SecurityUtils.login(user, request);
152   - //session里写入用户名,webSocket连接时标识身份用
153   - session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
154   -
155   - //获取公司权限数据
156   - List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
157   - session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
158   - rs.put("status", ResponseCode.SUCCESS);
159   - } catch (Exception e) {
160   - logger.error("", e);
161   - rs.put("msg", "服务器出现异常,请联系管理员");
162   - }
163   - return rs;
164   - }
165   -
166   - /**
167   - * 返回当前用户的公司权限数据,用于构建页面级联下拉框
168   - *
169   - * @return
170   - */
171   - @RequestMapping("companyData")
172   - public List<CompanyData> companyData(HttpServletRequest request) {
173   - List<CompanyData> rs = new ArrayList<>();
174   - CompanyData companyData;
175   -
176   - ArrayListMultimap<String, CompanyAuthority> map = ArrayListMultimap.create();
177   - List<CompanyAuthority> cmyAuths = (List<CompanyAuthority>) request.getSession().getAttribute(Constants.COMPANY_AUTHORITYS);
178   -
179   - for (CompanyAuthority cAuth : cmyAuths) {
180   - map.put(cAuth.getCompanyCode() + "_" + cAuth.getCompanyName(), cAuth);
181   - }
182   -
183   - Set<String> keys = map.keySet();
184   - String[] temps;
185   - for (String k : keys) {
186   - temps = k.split("_");
187   -
188   - companyData = new CompanyData();
189   - companyData.setCompanyCode(temps[0]);
190   - companyData.setCompanyName(temps[1]);
191   - companyData.setChildren(new ArrayList<CompanyData.ChildrenCompany>());
192   -
193   - cmyAuths = map.get(k);
194   - for (CompanyAuthority c : cmyAuths) {
195   - companyData.getChildren().add(new CompanyData.ChildrenCompany(c.getSubCompanyCode(), c.getSubCompanyName()));
196   - }
197   -
198   - rs.add(companyData);
199   - }
200   -
201   - return rs;
202   - }
203   -
204   - @RequestMapping(value = "/login/captchaStatus")
205   - public int captchaStatus(String userName) {
206   - Integer size = captchaMap.get(userName);
207   - return size == null ? 0 : size;
208   - }
209   -
210   - public Map<String, Object> put(Map<String, Object> rs, String key, Object val) {
211   - rs.put(key, val);
212   - return rs;
213   - }
214   -
215   - /**
216   - * @Title: loginFailure @Description: TODO(查询登录失败的详细信息) @param @param
217   - * request @return String 返回类型 @throws
218   - */
219   - @RequestMapping("/loginFailure")
220   - public String loginFailure(HttpServletRequest request) {
221   - String msg = "";
222   - HttpSession session = request.getSession();
223   -
224   - Object obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
225   -
226   - if (obj instanceof BadCredentialsException)
227   - msg = "登录失败,用户名或密码错误.";
228   - else if (obj instanceof SessionAuthenticationException)
229   - msg = "登录失败,当前策略不允许重复登录.";
230   - session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
231   - return msg;
232   - }
233   -
234   - @RequestMapping("/currentUser")
235   - public SysUser currentUser() {
236   - return SecurityUtils.getCurrentUser();
237   - }
238   -
239   - /**
240   - * @param id 用户ID
241   - * @param enabled 状态
242   - * @return
243   - * @Title changeEnabled
244   - * @Description: TODO(改变用户状态)
245   - */
246   - @RequestMapping("/changeEnabled")
247   - public int changeEnabled(@RequestParam int id, @RequestParam int enabled) {
248   - return sysUserService.changeEnabled(id, enabled);
249   - }
250   -
251   - /**
252   - * @param oldPWD 原始密码
253   - * @param newPWD 新密码
254   - * @param cnewPWD 确认新密码
255   - * @return
256   - * @Title changePWD
257   - * @Description: TODO(修改密码)
258   - */
259   - @RequestMapping(value = "/changePWD", method = RequestMethod.POST)
260   - public String changePWD(@RequestParam String oldPWD, @RequestParam String newPWD, @RequestParam String cnewPWD) {
261   - SysUser sysUser = SecurityUtils.getCurrentUser();
262   - String msg = "";
263   - if (new BCryptPasswordEncoder(4).matches(oldPWD, sysUser.getPassword())) {
264   - if (oldPWD.equals(newPWD)) {
265   - msg = "新密码不能跟原始密码一样!";
266   - } else {
267   - if (newPWD.equals(cnewPWD)) {
268   - sysUserService.changePWD(sysUser.getId(), newPWD);
269   - msg = "修改成功!";
270   - } else {
271   - msg = "新密码两次输入不一致!";
272   - }
273   - }
274   - } else {
275   - msg = "原始密码错误!";
276   - }
277   - return msg;
278   - }
279   -
280   - @RequestMapping(value = "/register", method = RequestMethod.POST)
281   - public Map<String, Object> register(SysUser u) {
282   - return sysUserService.register(u);
283   - }
284   -
285   - @RequestMapping(value = "/all_distinct")
286   - public List<SysUser> findAll_distinct() {
287   - return sysUserService.findAll_distinct();
288   - }
289   -}
  1 +package com.bsth.controller.sys;
  2 +
  3 +import com.bsth.common.Constants;
  4 +import com.bsth.common.ResponseCode;
  5 +import com.bsth.controller.BaseController;
  6 +import com.bsth.controller.sys.dto.CompanyData;
  7 +import com.bsth.controller.sys.util.RSAUtils;
  8 +import com.bsth.entity.sys.CompanyAuthority;
  9 +import com.bsth.entity.sys.Role;
  10 +import com.bsth.entity.sys.SysUser;
  11 +import com.bsth.security.util.SecurityUtils;
  12 +import com.bsth.service.logger.UserSignService;
  13 +import com.bsth.service.sys.CompanyAuthorityService;
  14 +import com.bsth.service.sys.SysUserService;
  15 +import com.google.common.collect.ArrayListMultimap;
  16 +import org.apache.commons.lang3.StringUtils;
  17 +import org.joda.time.DateTime;
  18 +import org.joda.time.Period;
  19 +import org.joda.time.PeriodType;
  20 +import org.slf4j.Logger;
  21 +import org.slf4j.LoggerFactory;
  22 +import org.springframework.beans.factory.annotation.Autowired;
  23 +import org.springframework.security.authentication.BadCredentialsException;
  24 +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  25 +import org.springframework.security.web.authentication.session.SessionAuthenticationException;
  26 +import org.springframework.web.bind.annotation.RequestMapping;
  27 +import org.springframework.web.bind.annotation.RequestMethod;
  28 +import org.springframework.web.bind.annotation.RequestParam;
  29 +import org.springframework.web.bind.annotation.RestController;
  30 +
  31 +import javax.servlet.http.HttpServletRequest;
  32 +import javax.servlet.http.HttpSession;
  33 +import java.util.*;
  34 +import java.util.regex.Matcher;
  35 +import java.util.regex.Pattern;
  36 +
  37 +@RestController
  38 +@RequestMapping("user")
  39 +public class UserController extends BaseController<SysUser, Integer> {
  40 +
  41 + Logger logger = LoggerFactory.getLogger(this.getClass());
  42 +
  43 + @Autowired
  44 + SysUserService sysUserService;
  45 +
  46 + @Autowired
  47 + CompanyAuthorityService companyAuthorityService;
  48 +
  49 + @Autowired
  50 + UserSignService userLogInoutService;
  51 +
  52 + private Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*?[#?!@$%^&*-.]).{8,16}$");
  53 +
  54 + @RequestMapping(value = "/login/jCryptionKey")
  55 + public Map<String, Object> jCryptionKey(HttpServletRequest request) {
  56 + //公匙返回页面
  57 + Map<String, Object> rs = new HashMap<>();
  58 + rs.put("publickey", RSAUtils.generateBase64PublicKey());
  59 + return rs;
  60 + }
  61 +
  62 + @RequestMapping(value = "/getCurrentUser")
  63 + public SysUser getCurrentUser() {
  64 + SysUser user = SecurityUtils.getCurrentUser();
  65 + return user;
  66 + }
  67 +
  68 + //需要验证码的账号
  69 + public static Map<String, Integer> USER_ERRTIMES = new HashMap<>();
  70 + public static Map<String, Long> USER_LOCKTIME = new HashMap<>();
  71 +
  72 + @RequestMapping(value = "/login", method = RequestMethod.POST)
  73 + public Map<String, Object> login(HttpServletRequest request, @RequestParam String userName,
  74 + @RequestParam String password, String captcha) {
  75 +
  76 + Map<String, Object> rs = new HashMap<>();
  77 + rs.put("status", ResponseCode.ERROR);
  78 + try {
  79 + HttpSession session = request.getSession();
  80 + rs.put("captcha", session.getAttribute("captcha"));
  81 +
  82 + //解密RSA
  83 + try {
  84 + userName = RSAUtils.decryptBase64(userName);
  85 + password = RSAUtils.decryptBase64(password);
  86 + } catch (RuntimeException e) {
  87 + return put(rs, "msg", "decrypt RSA fail!可能页面已过期,尝试刷新页面。");
  88 + }
  89 +
  90 + SysUser user = sysUserService.findByUserName(userName);
  91 +
  92 + if (null == user) {
  93 + userOrPasswordInvalid(rs, userName);
  94 +
  95 + return rs;
  96 + }
  97 +
  98 + // 校验用户状态
  99 + if (!user.isEnabled()) {
  100 + return put(rs, "msg", "该用户已被锁定,请联系管理员");
  101 + }
  102 +
  103 + // 校验临时状态
  104 + if (USER_LOCKTIME.get(userName) != null && USER_LOCKTIME.get(userName) >= System.currentTimeMillis()) {
  105 + return put(rs, "msg", "您的账户因密码错误次数过多,处于锁定状态中");
  106 + }
  107 +
  108 + // 校验验证码
  109 + if (USER_ERRTIMES.get(userName) != null && USER_ERRTIMES.get(userName) > 1) {
  110 + String verCode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
  111 + if (StringUtils.isBlank(captcha)) {
  112 + return put(rs, "msg", "请输入验证码");
  113 + }
  114 + if (!verCode.equals(captcha)) {
  115 + return put(rs, "msg", "验证码有误,请刷新后重新输入");
  116 + }
  117 + }
  118 +
  119 + // 校验密码
  120 + boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
  121 + if (!matchStatus) {
  122 + userOrPasswordInvalid(rs, userName);
  123 +
  124 + return rs;
  125 + }
  126 +
  127 + // 检验密码有效期
  128 + Date lastPwdDate = user.getLastPwdDate();
  129 + if (lastPwdDate != null) {
  130 + if (user.getPwdExpiredDate().before(new Date())) {
  131 + return put(rs, "msg", "密码已过期,不能登录,请联系管理员");
  132 + }
  133 +
  134 + Integer validPeriod = user.getPwdValidPeriod();
  135 + if (validPeriod == null) {
  136 + validPeriod = 30;
  137 + }
  138 + Period p = new Period(new DateTime(lastPwdDate), new DateTime(new Date()), PeriodType.days());
  139 + if (p.getDays() > validPeriod) {
  140 + return put(rs, "msg", "天没有修改密码,不能登录,请联系管理员");
  141 + }
  142 + } else {
  143 + return put(rs, "msg", "从未更新过密码,不能登录,请联系管理员");
  144 + }
  145 +
  146 + // 弱密码检查
  147 + Matcher matcher = pattern.matcher(password);
  148 + if (!matcher.matches()) {
  149 + session.setAttribute(Constants.WEAK_CIPHER, 1);
  150 + }
  151 +
  152 + // 登录
  153 + SecurityUtils.login(user, request);
  154 + sysUserService.recordLoginDate(userName);
  155 + //session里写入用户名,webSocket连接时标识身份用
  156 + session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
  157 + session.setAttribute(Constants.RESOURCE_AUTHORITYS, user.getLinks());
  158 +
  159 + //获取公司权限数据
  160 + List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
  161 + session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
  162 +
  163 + USER_ERRTIMES.remove(userName);
  164 + rs.put("status", ResponseCode.SUCCESS);
  165 + logger.error("用户:" + user.getUserName() + "登录");
  166 +
  167 + // 记录登录日志
  168 + userLogInoutService.userLogIn(user.getUserName(), session.getId(), new Date());
  169 + } catch (Exception e) {
  170 + logger.error("", e);
  171 + rs.put("msg", "服务器出现异常,请联系管理员");
  172 + }
  173 + return rs;
  174 + }
  175 +
  176 + private void userOrPasswordInvalid(Map<String, Object> rs, String userName) {
  177 + rs.put("msg", "密码有误");
  178 +
  179 + Integer errTimes = USER_ERRTIMES.get(userName);
  180 + if (null == errTimes) {
  181 + errTimes = 0;
  182 + }
  183 + USER_ERRTIMES.put(userName, ++errTimes);
  184 + if (errTimes > 3) {
  185 + USER_LOCKTIME.put(userName, System.currentTimeMillis() + 600000);
  186 + USER_ERRTIMES.put(userName, 0);
  187 + put(rs, "msg", "密码错误4次,账户将被锁定10分钟");
  188 + }
  189 + }
  190 +
  191 + @RequestMapping(value = "/change_user", method = RequestMethod.POST)
  192 + public Map<String, Object> changeUser(HttpServletRequest request, @RequestParam String userName,
  193 + @RequestParam String password) {
  194 +
  195 + Map<String, Object> rs = new HashMap<>();
  196 + rs.put("status", ResponseCode.ERROR);
  197 + try {
  198 + HttpSession session = request.getSession();
  199 +
  200 + SysUser user = sysUserService.findByUserName(userName);
  201 + if (null == user)
  202 + return put(rs, "msg", "不存在的用户");
  203 +
  204 + if (!user.isEnabled())
  205 + return put(rs, "msg", "该用户已被锁定,请联系管理员");
  206 +
  207 + // 校验密码
  208 + boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
  209 + if (!matchStatus)
  210 + return put(rs, "msg", "密码有误");
  211 +
  212 + // 登录
  213 + SecurityUtils.login(user, request);
  214 + //session里写入用户名,webSocket连接时标识身份用
  215 + session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
  216 + session.setAttribute(Constants.RESOURCE_AUTHORITYS, user.getLinks());
  217 +
  218 + //获取公司权限数据
  219 + List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
  220 + session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
  221 + rs.put("status", ResponseCode.SUCCESS);
  222 + } catch (Exception e) {
  223 + logger.error("", e);
  224 + rs.put("msg", "服务器出现异常,请联系管理员");
  225 + }
  226 + return rs;
  227 + }
  228 +
  229 + /**
  230 + * 返回当前用户的公司权限数据,用于构建页面级联下拉框
  231 + *
  232 + * @return
  233 + */
  234 + @RequestMapping("companyData")
  235 + public List<CompanyData> companyData(HttpServletRequest request) {
  236 + List<CompanyData> rs = new ArrayList<>();
  237 + CompanyData companyData;
  238 +
  239 + ArrayListMultimap<String, CompanyAuthority> map = ArrayListMultimap.create();
  240 + List<CompanyAuthority> cmyAuths = (List<CompanyAuthority>) request.getSession().getAttribute(Constants.COMPANY_AUTHORITYS);
  241 +
  242 + for (CompanyAuthority cAuth : cmyAuths) {
  243 + map.put(cAuth.getCompanyCode() + "_" + cAuth.getCompanyName(), cAuth);
  244 + }
  245 +
  246 + Set<String> keys = map.keySet();
  247 + String[] temps;
  248 + for (String k : keys) {
  249 + temps = k.split("_");
  250 +
  251 + companyData = new CompanyData();
  252 + companyData.setCompanyCode(temps[0]);
  253 + companyData.setCompanyName(temps[1]);
  254 + companyData.setChildren(new ArrayList<CompanyData.ChildrenCompany>());
  255 +
  256 + cmyAuths = map.get(k);
  257 + for (CompanyAuthority c : cmyAuths) {
  258 + companyData.getChildren().add(new CompanyData.ChildrenCompany(c.getSubCompanyCode(), c.getSubCompanyName()));
  259 + }
  260 +
  261 + rs.add(companyData);
  262 + }
  263 +
  264 + return rs;
  265 + }
  266 +
  267 + @RequestMapping(value = "/login/captchaStatus")
  268 + public int captchaStatus(String userName) {
  269 + Integer size = USER_ERRTIMES.get(userName);
  270 + return size == null ? 0 : size;
  271 + }
  272 +
  273 + public Map<String, Object> put(Map<String, Object> rs, String key, Object val) {
  274 + rs.put(key, val);
  275 + return rs;
  276 + }
  277 +
  278 + /**
  279 + * @Title: loginFailure @Description: TODO(查询登录失败的详细信息) @param @param
  280 + * request @return String 返回类型 @throws
  281 + */
  282 + @RequestMapping("/loginFailure")
  283 + public String loginFailure(HttpServletRequest request) {
  284 + String msg = "";
  285 + HttpSession session = request.getSession();
  286 +
  287 + Object obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
  288 +
  289 + if (obj instanceof BadCredentialsException)
  290 + msg = "登录失败,用户名或密码错误.";
  291 + else if (obj instanceof SessionAuthenticationException)
  292 + msg = "登录失败,当前策略不允许重复登录.";
  293 + session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
  294 + return msg;
  295 + }
  296 +
  297 + @RequestMapping("/currentUser")
  298 + public SysUser currentUser() {
  299 + return SecurityUtils.getCurrentUser();
  300 + }
  301 +
  302 + /**
  303 + * @param id 用户ID
  304 + * @param enabled 状态
  305 + * @return
  306 + * @Title changeEnabled
  307 + * @Description: TODO(改变用户状态)
  308 + */
  309 + @RequestMapping("/changeEnabled")
  310 + public int changeEnabled(@RequestParam int id, @RequestParam int enabled) {
  311 + return sysUserService.changeEnabled(id, enabled);
  312 + }
  313 +
  314 + /**
  315 + * @param oldPWD 原始密码
  316 + * @param newPWD 新密码
  317 + * @param cnewPWD 确认新密码
  318 + * @return
  319 + * @Title changePWD
  320 + * @Description: TODO(修改密码)
  321 + */
  322 + @RequestMapping(value = "/changePWD", method = RequestMethod.POST)
  323 + public String changePWD(@RequestParam String oldPWD, @RequestParam String newPWD, @RequestParam String cnewPWD, HttpServletRequest request) {
  324 + SysUser sysUser = SecurityUtils.getCurrentUser();
  325 + String msg = "";
  326 +
  327 + //解密RSA
  328 + try{
  329 + oldPWD = (RSAUtils.decryptBase64(oldPWD));
  330 + newPWD = (RSAUtils.decryptBase64(newPWD));
  331 + cnewPWD = (RSAUtils.decryptBase64(cnewPWD));
  332 + }catch (RuntimeException e) {
  333 + return "网络延迟,解密失败,请重新添加!";
  334 + }
  335 + if (new BCryptPasswordEncoder(4).matches(oldPWD, sysUser.getPassword())) {
  336 + if (oldPWD.equals(newPWD)) {
  337 + msg = "新密码不能跟原始密码一样!";
  338 + } else {
  339 + if (newPWD.equals(cnewPWD)) {
  340 + sysUserService.changePWD(sysUser.getId(), newPWD);
  341 + request.getSession().setAttribute(Constants.WEAK_CIPHER, 0);
  342 + msg = "修改成功!";
  343 + } else {
  344 + msg = "新密码两次输入不一致!";
  345 + }
  346 + }
  347 + } else {
  348 + msg = "原始密码错误!";
  349 + }
  350 + return msg;
  351 + }
  352 +
  353 + @RequestMapping(value = "/validPWDExpired", method = RequestMethod.GET)
  354 + public String validPWDExpired() {
  355 + try {
  356 + SysUser sysUser = SecurityUtils.getCurrentUser();
  357 + this.sysUserService.validPWDExpired(sysUser.getUserName());
  358 + return "ok";
  359 + } catch (Exception exp) {
  360 + exp.printStackTrace();
  361 + return exp.getMessage();
  362 + }
  363 + }
  364 +
  365 + @RequestMapping(value = "/register", method = RequestMethod.POST)
  366 + public Map<String, Object> register(SysUser u) {
  367 + return sysUserService.register(u);
  368 + }
  369 +
  370 + // 查询用户下所有下级角色
  371 + @RequestMapping(value = "/all_distinct")
  372 + public List<SysUser> findAll_distinct() {
  373 + return sysUserService.findAll_distinct();
  374 + }
  375 +
  376 + // 重置密码
  377 + @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
  378 + public Map<String, Object> resetPassword(@RequestParam Integer id, @RequestParam Integer pwdValidPeriod) {
  379 + return sysUserService.resetPassword(id, pwdValidPeriod);
  380 + }
  381 +
  382 + /**
  383 + * 解除临时锁定
  384 + * @param userName
  385 + * @return
  386 + */
  387 + @RequestMapping(value = "/unlock", method = RequestMethod.POST)
  388 + public Map<String, Object> unlock(@RequestParam String userName) {
  389 + Map<String, Object> result = new HashMap<>();
  390 + // 获取当前用户
  391 + SysUser user = SecurityUtils.getCurrentUser();
  392 + Iterator<Role> itRole = user.getRoles().iterator();
  393 + Role ro = new Role();
  394 + boolean isSuper = false;
  395 + while (itRole.hasNext()) {//判断是否有下一个
  396 + ro = itRole.next();
  397 + if (ro.getLevel() == 1) {
  398 + isSuper = true;
  399 + }
  400 + }
  401 + if (isSuper) {
  402 + USER_LOCKTIME.remove(userName);
  403 + USER_ERRTIMES.remove(userName);
  404 + result.put("status", ResponseCode.SUCCESS);
  405 + result.put("msg", "用户解锁成功!");
  406 + } else {
  407 + result.put("status", ResponseCode.ERROR);
  408 + result.put("msg", "您不是管理员无用户解锁权限");
  409 + }
  410 +
  411 + return result;
  412 + }
  413 +
  414 + /**
  415 + * 弱密码
  416 + * @param request
  417 + * @return
  418 + */
  419 + @RequestMapping(value = "/isWeakCipher", method = RequestMethod.POST)
  420 + public Map<String, Object> isWeakCipher(HttpServletRequest request) {
  421 + Map<String, Object> result = new HashMap<>();
  422 + result.put("status", ResponseCode.SUCCESS);
  423 + result.put("data", request.getSession().getAttribute(Constants.WEAK_CIPHER));
  424 +
  425 + return result;
  426 + }
  427 +
  428 +// /**
  429 +// * 弱密码
  430 +// * @return
  431 +// */
  432 +// @RequestMapping(value = "/isRealName", method = RequestMethod.POST)
  433 +// public Map<String, Object> hasJobCode() {
  434 +// Map<String, Object> result = new HashMap<>();
  435 +// SysUser user = SecurityUtils.getCurrentUser();
  436 +// result.put("status", ResponseCode.SUCCESS);
  437 +// result.put("data", (StringUtils.isBlank(user.getJobCode()) || StringUtils.isBlank(user.getRealName())) ? 0 : 1);
  438 +//
  439 +// return result;
  440 +// }
  441 +//
  442 +// // 重置密码
  443 +// @RequestMapping(value = "/realName", method = RequestMethod.POST)
  444 +// public Map<String, Object> setJobCode(@RequestParam String jobCode, @RequestParam String realName) throws Exception {
  445 +// Map<String, Object> data = new HashMap<>(), result = new HashMap<>();
  446 +// result.put("status", ResponseCode.ERROR);
  447 +// result.put("data", "设置成功");
  448 +//
  449 +// if (jobCode == null || realName == null) {
  450 +// result.put("data", "你跳过验证了是吧");
  451 +// return result;
  452 +// }
  453 +// data.put("account", jobCode);
  454 +// data.put("pageSize", 2);
  455 +// data.put("pageNum", 1);
  456 +// StringBuilder stringBuilder = HttpClientUtils.post("https://112.64.45.51/businessCenter/userInfo/queryUserList", mapper.writeValueAsString(data));
  457 +// if (stringBuilder == null) {
  458 +// result.put("data", "统一平台验证失败1");
  459 +// return result;
  460 +// } else {
  461 +// List<Map<String, Object>> maps = mapper.readValue(mapper.writeValueAsString(((Map) mapper.readValue(stringBuilder.toString(), Map.class).get("data")).get("list")), mapper.getTypeFactory().constructParametricType(List.class, Map.class));
  462 +// if (maps.size() == 0) {
  463 +// result.put("data", "统一平台验证失败2");
  464 +// return result;
  465 +// } else {
  466 +// boolean isAuth = false;
  467 +// for (Map<String, Object> map : maps) {
  468 +// if (realName.equals(map.get("name"))) {
  469 +// isAuth = true;
  470 +// break;
  471 +// }
  472 +// }
  473 +// if (!isAuth) {
  474 +// result.put("data", "统一平台验证失败3");
  475 +// return result;
  476 +// }
  477 +// }
  478 +// }
  479 +//
  480 +// SysUser user = SecurityUtils.getCurrentUser();
  481 +// sysUserService.realName(jobCode, realName, user.getId());
  482 +// user.setJobCode(jobCode);
  483 +// user.setRealName(realName);
  484 +//
  485 +// result.put("status", ResponseCode.SUCCESS);
  486 +// return result;
  487 +// }
  488 +
  489 +}
... ...
src/main/java/com/bsth/data/SystemParamCache.java 0 → 100644
  1 +package com.bsth.data;
  2 +
  3 +import com.bsth.common.SystemParamKeys;
  4 +import com.bsth.service.SystemParamService;
  5 +import org.springframework.beans.factory.InitializingBean;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.stereotype.Component;
  8 +
  9 +/**
  10 + * @author Hill
  11 + */
  12 +@Component
  13 +public class SystemParamCache implements InitializingBean {
  14 +
  15 + @Autowired
  16 + private SystemParamService systemParamService;
  17 +
  18 + private static SystemParamService systemParamService1;
  19 +
  20 + public static String getSpecialRoles() {
  21 + return systemParamService1.getValue(SystemParamKeys.SPECIAL_ROLES);
  22 + }
  23 +
  24 + public static String getSpecialDays() {
  25 + return systemParamService1.getValue(SystemParamKeys.SPECIAL_DAYS);
  26 + }
  27 +
  28 + public static String getUrlHttpGpsRealCache() {
  29 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_GPS_REAL_CACHE);
  30 + }
  31 +
  32 + public static String getUrlHttpGpsReal() {
  33 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_GPS_REAL);
  34 + }
  35 +
  36 + public static String getUrlHttpDirective() {
  37 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_DIRECTIVE);
  38 + }
  39 +
  40 + public static String getUrlHttpRfid() {
  41 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_RFID);
  42 + }
  43 +
  44 + public static String getUrlHttpReport(String param) {
  45 + return systemParamService1.getValue(String.format(SystemParamKeys.URL_HTTP_REPORT, param));
  46 + }
  47 +
  48 + public static String getUrlHttpTicketing() {
  49 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_TICKETING);
  50 + }
  51 +
  52 + public static String getUrlHttpDsmAck() {
  53 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_DSM_ACK);
  54 + }
  55 +
  56 + public static String getUrlHttpCpAck() {
  57 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_CP_ACK);
  58 + }
  59 +
  60 + public static String getMailAdmin() {
  61 + return systemParamService1.getValue(SystemParamKeys.MAIL_ADMIN);
  62 + }
  63 +
  64 + public static String getMailWaybill() {
  65 + return systemParamService1.getValue(SystemParamKeys.MAIL_WAYBILL);
  66 + }
  67 +
  68 + public static boolean getEnabledFirstLastGeneration() {
  69 + return Boolean.parseBoolean(systemParamService1.getValue(SystemParamKeys.ENABLED_FIRST_LAST_GENERATION));
  70 + }
  71 +
  72 + public static boolean getEnabledFilterSqlInjection() {
  73 + return Boolean.parseBoolean(systemParamService1.getValue(SystemParamKeys.ENABLED_FILTER_SQL_INJECTION));
  74 + }
  75 +
  76 + public static boolean getEnabledSso() {
  77 + return Boolean.parseBoolean(systemParamService1.getValue(SystemParamKeys.ENABLED_SSO));
  78 + }
  79 +
  80 + public static String getSsoSystemCode() {
  81 + return systemParamService1.getValue(SystemParamKeys.SSO_SYSTEM_CODE);
  82 + }
  83 +
  84 + public static String getUrlHttpSsoLogin() {
  85 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_SSO_LOGIN);
  86 + }
  87 +
  88 + public static String getUrlHttpSsoLogout() {
  89 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_SSO_LOGOUT);
  90 + }
  91 +
  92 + public static String getUrlHttpSsoAuth() {
  93 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_SSO_AUTH);
  94 + }
  95 +
  96 + public static String getUrlHttpMaintenance() {
  97 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_MAINTENANCE);
  98 + }
  99 +
  100 + public static boolean getEnabledWhiteIp() {
  101 + return Boolean.parseBoolean(systemParamService1.getValue(SystemParamKeys.ENABLED_WHITE_IP));
  102 + }
  103 +
  104 + public static boolean getEnableFilterAuthority() {
  105 + return Boolean.parseBoolean(systemParamService1.getValue(SystemParamKeys.ENABLED_FILTER_AUTHORITY));
  106 + }
  107 +
  108 + public static String getUrlHttpDvr() {
  109 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_DVR);
  110 + }
  111 +
  112 + public static String getUrlHttpDvrPwd() {
  113 + return systemParamService1.getValue(SystemParamKeys.URL_HTTP_DVR_PWD);
  114 + }
  115 +
  116 + @Override
  117 + public void afterPropertiesSet() throws Exception {
  118 + systemParamService1 = systemParamService;
  119 + systemParamService1.refresh();
  120 + }
  121 +}
0 122 \ No newline at end of file
... ...
src/main/java/com/bsth/data/WhiteIpCache.java 0 → 100644
  1 +package com.bsth.data;
  2 +
  3 +import com.bsth.Application;
  4 +import com.bsth.XDApplication;
  5 +import com.bsth.entity.WhiteIp;
  6 +import org.slf4j.Logger;
  7 +import org.slf4j.LoggerFactory;
  8 +import org.springframework.beans.factory.InitializingBean;
  9 +import org.springframework.beans.factory.annotation.Autowired;
  10 +import org.springframework.jdbc.core.BeanPropertyRowMapper;
  11 +import org.springframework.jdbc.core.JdbcTemplate;
  12 +import org.springframework.stereotype.Component;
  13 +
  14 +import java.util.List;
  15 +import java.util.concurrent.TimeUnit;
  16 +
  17 +@Component
  18 +public class WhiteIpCache implements InitializingBean {
  19 +
  20 + private final static Logger log = LoggerFactory.getLogger(WhiteIpCache.class);
  21 +
  22 + @Autowired
  23 + private JdbcTemplate jdbcTemplate;
  24 +
  25 + private static List<WhiteIp> whiteIps;
  26 +
  27 + public static List<WhiteIp> getWhiteIps() {
  28 + return whiteIps;
  29 + }
  30 +
  31 + @Override
  32 + public void afterPropertiesSet() throws Exception {
  33 + Application.mainServices.scheduleWithFixedDelay(new WhiteIpDataLoader(), 0, 1, TimeUnit.MINUTES);
  34 + }
  35 +
  36 + class WhiteIpDataLoader extends Thread {
  37 +
  38 + @Override
  39 + public void run() {
  40 + if (SystemParamCache.getEnabledWhiteIp()) {
  41 + loadData();
  42 + }
  43 + }
  44 +
  45 + /**
  46 + * @Title: loadAllData
  47 + * @Description: TODO(加载所有数据)
  48 + */
  49 + public int loadData() {
  50 + try {
  51 + log.info("开始加载IP白名单数据..,");
  52 + loadWhiteIp();
  53 + log.info("加载IP白名单数据成功!,");
  54 + } catch (Exception e) {
  55 + log.error("加载IP白名单数据时出现异常,", e);
  56 + }
  57 + return 0;
  58 + }
  59 +
  60 + /**
  61 + * 加载IP白名单
  62 + */
  63 + public void loadWhiteIp() {
  64 + List<WhiteIp> result = jdbcTemplate.query("select * from control_interface.bsth_c_white_ip where valid_date > now()", BeanPropertyRowMapper.newInstance(WhiteIp.class));
  65 + whiteIps = result;
  66 + }
  67 + }
  68 +}
... ...
src/main/java/com/bsth/data/directive/GatewayHttpUtils.java
1   -package com.bsth.data.directive;
2   -
3   -import com.alibaba.fastjson.JSONObject;
4   -import com.bsth.util.ConfigUtil;
5   -import org.apache.http.client.config.RequestConfig;
6   -import org.apache.http.client.methods.CloseableHttpResponse;
7   -import org.apache.http.client.methods.HttpPost;
8   -import org.apache.http.entity.StringEntity;
9   -import org.apache.http.impl.client.CloseableHttpClient;
10   -import org.apache.http.impl.client.HttpClients;
11   -import org.apache.http.util.EntityUtils;
12   -import org.slf4j.Logger;
13   -import org.slf4j.LoggerFactory;
14   -
15   -/**
16   - * @author PanZhao
17   - * @ClassName: GatewayHttpUtils
18   - * @Description: TODO(和网关HTTP通讯工具类)
19   - * @date 2016年8月14日 下午9:50:46
20   - */
21   -public class GatewayHttpUtils {
22   - static Logger logger = LoggerFactory.getLogger(GatewayHttpUtils.class);
23   -
24   - static String url;
25   - static CloseableHttpClient httpClient = null;
26   - static HttpPost post;
27   - static RequestConfig requestConfig;
28   - static CloseableHttpResponse response;
29   -
30   - static {
31   - url = ConfigUtil.get("http.send.directive");
32   - httpClient = HttpClients.createDefault();
33   - post = new HttpPost(url);
34   - requestConfig = RequestConfig.custom()
35   - .setConnectTimeout(3000).setConnectionRequestTimeout(2000)
36   - .setSocketTimeout(3000).build();
37   - post.setConfig(requestConfig);
38   - }
39   -
40   - public static int postJson(String jsonStr) {
41   - logger.info("send : " + jsonStr);
42   -
43   - int code = -1;
44   - try {
45   - post.setEntity(new StringEntity(jsonStr, "utf-8"));
46   -
47   - response = httpClient.execute(post);
48   -
49   - int statusCode = response.getStatusLine().getStatusCode();
50   - if(statusCode != 200){
51   - logger.error("http client status code: " + statusCode);
52   - }
53   -
54   - JSONObject json = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
55   - if (null != json && json.getInteger("errCode") == 0)
56   - code = 0;
57   - else
58   - logger.error("和网关http通讯失败,rs: " + json);
59   -
60   - if (null != response)
61   - response.close();
62   - } catch (Exception e) {
63   - logger.error("", e);
64   - }
65   - return code;
66   - }
67   -}
  1 +package com.bsth.data.directive;
  2 +
  3 +import com.alibaba.fastjson.JSONObject;
  4 +import com.bsth.data.SystemParamCache;
  5 +import org.apache.http.client.config.RequestConfig;
  6 +import org.apache.http.client.methods.CloseableHttpResponse;
  7 +import org.apache.http.client.methods.HttpPost;
  8 +import org.apache.http.entity.StringEntity;
  9 +import org.apache.http.impl.client.CloseableHttpClient;
  10 +import org.apache.http.impl.client.HttpClients;
  11 +import org.apache.http.util.EntityUtils;
  12 +import org.slf4j.Logger;
  13 +import org.slf4j.LoggerFactory;
  14 +import org.springframework.beans.factory.InitializingBean;
  15 +import org.springframework.stereotype.Component;
  16 +
  17 +/**
  18 + * @author PanZhao
  19 + * @ClassName: GatewayHttpUtils
  20 + * @Description: TODO(和网关HTTP通讯工具类)
  21 + * @date 2016年8月14日 下午9:50:46
  22 + */
  23 +@Component
  24 +public class GatewayHttpUtils implements InitializingBean {
  25 + static Logger logger = LoggerFactory.getLogger(GatewayHttpUtils.class);
  26 +
  27 + static String url;
  28 + static CloseableHttpClient httpClient = null;
  29 + static HttpPost post;
  30 + static RequestConfig requestConfig;
  31 + static CloseableHttpResponse response;
  32 +
  33 + public static int postJson(String jsonStr) {
  34 + logger.info("send : " + jsonStr);
  35 +
  36 + int code = -1;
  37 + try {
  38 + post.setEntity(new StringEntity(jsonStr, "utf-8"));
  39 +
  40 + response = httpClient.execute(post);
  41 +
  42 + int statusCode = response.getStatusLine().getStatusCode();
  43 + if(statusCode != 200){
  44 + logger.error("http client status code: " + statusCode);
  45 + }
  46 +
  47 + JSONObject json = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
  48 + if (null != json && json.getInteger("errCode") == 0)
  49 + code = 0;
  50 + else
  51 + logger.error("和网关http通讯失败,rs: " + json);
  52 +
  53 + if (null != response)
  54 + response.close();
  55 + } catch (Exception e) {
  56 + logger.error("", e);
  57 + }
  58 + return code;
  59 + }
  60 +
  61 + @Override
  62 + public void afterPropertiesSet() throws Exception {
  63 + url = SystemParamCache.getUrlHttpDirective();
  64 + httpClient = HttpClients.createDefault();
  65 + post = new HttpPost(url);
  66 + requestConfig = RequestConfig.custom()
  67 + .setConnectTimeout(3000).setConnectionRequestTimeout(2000)
  68 + .setSocketTimeout(3000).build();
  69 + post.setConfig(requestConfig);
  70 + }
  71 +}
... ...
src/main/java/com/bsth/data/gpsdata_v2/load/GatewayHttpLoader.java
... ... @@ -2,10 +2,10 @@ package com.bsth.data.gpsdata_v2.load;
2 2  
3 3 import com.alibaba.fastjson.JSON;
4 4 import com.bsth.data.BasicData;
  5 +import com.bsth.data.SystemParamCache;
5 6 import com.bsth.data.gpsdata_v2.GpsRealData;
6 7 import com.bsth.data.gpsdata_v2.entity.GpsEntity;
7 8 import com.bsth.data.gpsdata_v2.utils.GpsDataUtils;
8   -import com.bsth.util.ConfigUtil;
9 9 import org.apache.commons.lang3.StringUtils;
10 10 import org.apache.http.HttpEntity;
11 11 import org.apache.http.client.config.RequestConfig;
... ... @@ -16,6 +16,7 @@ import org.apache.http.impl.client.HttpClients;
16 16 import org.slf4j.Logger;
17 17 import org.slf4j.LoggerFactory;
18 18 import org.springframework.beans.BeansException;
  19 +import org.springframework.beans.factory.InitializingBean;
19 20 import org.springframework.context.ApplicationContext;
20 21 import org.springframework.context.ApplicationContextAware;
21 22 import org.springframework.stereotype.Component;
... ... @@ -30,7 +31,7 @@ import java.util.List;
30 31 * Created by panzhao on 2017/11/15.
31 32 */
32 33 @Component
33   -public class GatewayHttpLoader implements ApplicationContextAware{
  34 +public class GatewayHttpLoader implements ApplicationContextAware, InitializingBean {
34 35  
35 36 static Logger logger = LoggerFactory.getLogger(GatewayHttpLoader.class);
36 37  
... ... @@ -45,17 +46,6 @@ public class GatewayHttpLoader implements ApplicationContextAware{
45 46  
46 47 static GpsRealData gpsRealData;
47 48  
48   - static{
49   - url = ConfigUtil.get("http.gps.real.url");
50   - list = new ArrayList<>();
51   - httpClient = HttpClients.createDefault();
52   - get = new HttpGet(url);
53   - requestConfig = RequestConfig.custom()
54   - .setConnectTimeout(2500).setConnectionRequestTimeout(2000)
55   - .setSocketTimeout(2500).build();
56   - get.setConfig(requestConfig);
57   - }
58   -
59 49 public static List<GpsEntity> load(){
60 50 try{
61 51 if(list.size() > 0)
... ... @@ -117,4 +107,16 @@ public class GatewayHttpLoader implements ApplicationContextAware{
117 107 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
118 108 gpsRealData = applicationContext.getBean(GpsRealData.class);
119 109 }
  110 +
  111 + @Override
  112 + public void afterPropertiesSet() throws Exception {
  113 + url = SystemParamCache.getUrlHttpGpsReal();
  114 + list = new ArrayList<>();
  115 + httpClient = HttpClients.createDefault();
  116 + get = new HttpGet(url);
  117 + requestConfig = RequestConfig.custom()
  118 + .setConnectTimeout(2500).setConnectionRequestTimeout(2000)
  119 + .setSocketTimeout(2500).build();
  120 + get.setConfig(requestConfig);
  121 + }
120 122 }
... ...
src/main/java/com/bsth/data/gpsdata_v2/load/SocketClientLoader.java
1   -package com.bsth.data.gpsdata_v2.load;
2   -
3   -import com.alibaba.fastjson.JSON;
4   -import com.bsth.data.BasicData;
5   -import com.bsth.data.gpsdata_v2.entity.GpsEntity;
6   -import com.bsth.data.gpsdata_v2.utils.GpsDataUtils;
7   -import com.bsth.util.ConfigUtil;
8   -import org.apache.http.HttpEntity;
9   -import org.apache.http.client.config.RequestConfig;
10   -import org.apache.http.client.methods.CloseableHttpResponse;
11   -import org.apache.http.client.methods.HttpGet;
12   -import org.apache.http.impl.client.CloseableHttpClient;
13   -import org.apache.http.impl.client.HttpClients;
14   -import org.slf4j.Logger;
15   -import org.slf4j.LoggerFactory;
16   -
17   -import java.io.BufferedReader;
18   -import java.io.InputStreamReader;
19   -import java.util.ArrayList;
20   -import java.util.List;
21   -
22   -/**
23   - * 从专用的socket client 加载数据
24   - * Created by panzhao on 2017/11/15.
25   - */
26   -public class SocketClientLoader {
27   -
28   - static Logger logger = LoggerFactory.getLogger(SocketClientLoader.class);
29   -
30   - static String url;
31   - static List<GpsEntity> list;
32   - static CloseableHttpClient httpClient = null;
33   - static HttpGet get;
34   - static RequestConfig requestConfig;
35   - static CloseableHttpResponse response;
36   - static HttpEntity entity;
37   - static BufferedReader br;
38   -
39   - static {
40   - url = ConfigUtil.get("http.gps.real.cache.url");
41   - list = new ArrayList<>();
42   - httpClient = HttpClients.createDefault();
43   - get = new HttpGet(url);
44   - requestConfig = RequestConfig.custom()
45   - .setConnectTimeout(2500).setConnectionRequestTimeout(2000)
46   - .setSocketTimeout(2500).build();
47   - get.setConfig(requestConfig);
48   - }
49   -
50   - public static List<GpsEntity> load(){
51   - try {
52   - if(list.size() > 0)
53   - list.clear();
54   - logger.info("load start...");
55   - response = httpClient.execute(get);
56   - entity = response.getEntity();
57   - if(null == entity)
58   - return list;
59   -
60   - br = new BufferedReader(new InputStreamReader(entity.getContent()));
61   - StringBuilder sb = new StringBuilder();
62   - String str;
63   - while ((str = br.readLine()) != null)
64   - sb.append(str);
65   -
66   - list = JSON.parseArray(sb.toString(), GpsEntity.class);
67   -
68   - logger.info("load end ! size: " + list.size());
69   - //过滤掉无效的点位
70   - list = GpsDataUtils.clearInvalid(list);
71   -
72   - for (GpsEntity gps : list) {
73   - gps.setNbbm(BasicData.deviceId2NbbmMap.get(gps.getDeviceId()));
74   - }
75   -
76   - if (null != response)
77   - response.close();
78   - } catch (Exception e) {
79   - logger.error("", e);
80   - }
81   -
82   - return list;
83   - }
84   -}
  1 +package com.bsth.data.gpsdata_v2.load;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.bsth.data.BasicData;
  5 +import com.bsth.data.SystemParamCache;
  6 +import com.bsth.data.gpsdata_v2.entity.GpsEntity;
  7 +import com.bsth.data.gpsdata_v2.utils.GpsDataUtils;
  8 +import org.apache.http.HttpEntity;
  9 +import org.apache.http.client.config.RequestConfig;
  10 +import org.apache.http.client.methods.CloseableHttpResponse;
  11 +import org.apache.http.client.methods.HttpGet;
  12 +import org.apache.http.impl.client.CloseableHttpClient;
  13 +import org.apache.http.impl.client.HttpClients;
  14 +import org.slf4j.Logger;
  15 +import org.slf4j.LoggerFactory;
  16 +import org.springframework.beans.factory.InitializingBean;
  17 +import org.springframework.stereotype.Component;
  18 +
  19 +import java.io.BufferedReader;
  20 +import java.io.InputStreamReader;
  21 +import java.util.ArrayList;
  22 +import java.util.List;
  23 +
  24 +/**
  25 + * 从专用的socket client 加载数据
  26 + * Created by panzhao on 2017/11/15.
  27 + */
  28 +@Component
  29 +public class SocketClientLoader implements InitializingBean {
  30 +
  31 + static Logger logger = LoggerFactory.getLogger(SocketClientLoader.class);
  32 +
  33 + static String url;
  34 + static List<GpsEntity> list;
  35 + static CloseableHttpClient httpClient = null;
  36 + static HttpGet get;
  37 + static RequestConfig requestConfig;
  38 + static CloseableHttpResponse response;
  39 + static HttpEntity entity;
  40 + static BufferedReader br;
  41 +
  42 + public static List<GpsEntity> load(){
  43 + try {
  44 + if(list.size() > 0)
  45 + list.clear();
  46 + logger.info("load start...");
  47 + response = httpClient.execute(get);
  48 + entity = response.getEntity();
  49 + if(null == entity)
  50 + return list;
  51 +
  52 + br = new BufferedReader(new InputStreamReader(entity.getContent()));
  53 + StringBuilder sb = new StringBuilder();
  54 + String str;
  55 + while ((str = br.readLine()) != null)
  56 + sb.append(str);
  57 +
  58 + list = JSON.parseArray(sb.toString(), GpsEntity.class);
  59 +
  60 + logger.info("load end ! size: " + list.size());
  61 + //过滤掉无效的点位
  62 + list = GpsDataUtils.clearInvalid(list);
  63 +
  64 + for (GpsEntity gps : list) {
  65 + gps.setNbbm(BasicData.deviceId2NbbmMap.get(gps.getDeviceId()));
  66 + }
  67 +
  68 + if (null != response)
  69 + response.close();
  70 + } catch (Exception e) {
  71 + logger.error("", e);
  72 + }
  73 +
  74 + return list;
  75 + }
  76 +
  77 + @Override
  78 + public void afterPropertiesSet() throws Exception {
  79 + url = SystemParamCache.getUrlHttpGpsRealCache();
  80 + list = new ArrayList<>();
  81 + httpClient = HttpClients.createDefault();
  82 + get = new HttpGet(url);
  83 + requestConfig = RequestConfig.custom()
  84 + .setConnectTimeout(2500).setConnectionRequestTimeout(2000)
  85 + .setSocketTimeout(2500).build();
  86 + get.setConfig(requestConfig);
  87 + }
  88 +}
... ...
src/main/java/com/bsth/entity/sys/Role.java
1   -package com.bsth.entity.sys;
2   -
3   -import java.util.Date;
4   -import java.util.LinkedHashSet;
5   -import java.util.Set;
6   -
7   -import javax.persistence.Column;
8   -import javax.persistence.Entity;
9   -import javax.persistence.FetchType;
10   -import javax.persistence.GeneratedValue;
11   -import javax.persistence.GenerationType;
12   -import javax.persistence.Id;
13   -import javax.persistence.ManyToMany;
14   -import javax.persistence.Table;
15   -
16   -import com.fasterxml.jackson.annotation.JsonIgnore;
17   -
18   -@Entity
19   -@Table(name = "bsth_c_sys_role")
20   -public class Role {
21   -
22   - @Id
23   - @GeneratedValue(strategy = GenerationType.IDENTITY)
24   - private Integer id;
25   -
26   - private String codeName;
27   -
28   - private String roleName;
29   -
30   - private String descriptions;
31   -
32   - private boolean isSuperAdmin;
33   -
34   - private boolean enable;
35   -
36   - @JsonIgnore
37   - @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
38   - private Set<SysUser> users = new LinkedHashSet<>();
39   -
40   - @JsonIgnore
41   - @ManyToMany
42   - private Set<Module> modules = new LinkedHashSet<>();
43   -
44   - @JsonIgnore
45   - @ManyToMany(mappedBy = "roles")
46   - private Set<Resource> resources = new LinkedHashSet<>();
47   -
48   - @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
49   - private Date createDate;
50   -
51   - @Column(name = "update_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
52   - private Date updateDate;
53   -
54   - private int pic;
55   -
56   - public Integer getId() {
57   - return id;
58   - }
59   -
60   - public void setId(Integer id) {
61   - this.id = id;
62   - }
63   -
64   - public String getRoleName() {
65   - return roleName;
66   - }
67   -
68   - public String getDescriptions() {
69   - return descriptions;
70   - }
71   -
72   - public void setDescriptions(String descriptions) {
73   - this.descriptions = descriptions;
74   - }
75   -
76   - public void setRoleName(String roleName) {
77   - this.roleName = roleName;
78   - }
79   -
80   - public boolean isEnable() {
81   - return enable;
82   - }
83   -
84   - public void setEnable(boolean enable) {
85   - this.enable = enable;
86   - }
87   -
88   - public Set<SysUser> getUsers() {
89   - return users;
90   - }
91   -
92   - public void setUsers(Set<SysUser> users) {
93   - this.users = users;
94   - }
95   -
96   - public boolean isSuperAdmin() {
97   - return isSuperAdmin;
98   - }
99   -
100   - public void setSuperAdmin(boolean isSuperAdmin) {
101   - this.isSuperAdmin = isSuperAdmin;
102   - }
103   -
104   - public Set<Module> getModules() {
105   - return modules;
106   - }
107   -
108   - public void setModules(Set<Module> modules) {
109   - this.modules = modules;
110   - }
111   -
112   - public Set<Resource> getResources() {
113   - return resources;
114   - }
115   -
116   - public void setResources(Set<Resource> resources) {
117   - this.resources = resources;
118   - }
119   -
120   - public Date getCreateDate() {
121   - return createDate;
122   - }
123   -
124   - public void setCreateDate(Date createDate) {
125   - this.createDate = createDate;
126   - }
127   -
128   - public Date getUpdateDate() {
129   - return updateDate;
130   - }
131   -
132   - public void setUpdateDate(Date updateDate) {
133   - this.updateDate = updateDate;
134   - }
135   -
136   - public String getCodeName() {
137   - return codeName;
138   - }
139   -
140   - public void setCodeName(String codeName) {
141   - this.codeName = codeName;
142   - }
143   -
144   - public int getPic() {
145   - return pic;
146   - }
147   -
148   - public void setPic(int pic) {
149   - this.pic = pic;
150   - }
151   -
152   - @Override
153   - public boolean equals(Object obj) {
154   - return this.id.equals(((Role)obj).getId());
155   - }
156   -
157   - @Override
158   - public int hashCode() {
159   - return this.toString().hashCode();
160   - }
161   -
162   - @Override
163   - public String toString() {
164   - return this.id + "" + this.getCodeName();
165   - }
166   -}
  1 +package com.bsth.entity.sys;
  2 +
  3 +import java.io.Serializable;
  4 +import java.util.Date;
  5 +import java.util.LinkedHashSet;
  6 +import java.util.Set;
  7 +
  8 +import javax.persistence.Column;
  9 +import javax.persistence.Entity;
  10 +import javax.persistence.FetchType;
  11 +import javax.persistence.GeneratedValue;
  12 +import javax.persistence.GenerationType;
  13 +import javax.persistence.Id;
  14 +import javax.persistence.ManyToMany;
  15 +import javax.persistence.Table;
  16 +
  17 +import com.fasterxml.jackson.annotation.JsonIgnore;
  18 +import org.hibernate.annotations.Formula;
  19 +
  20 +@Entity
  21 +@Table(name = "bsth_c_sys_role")
  22 +public class Role implements Serializable {
  23 +
  24 + @Id
  25 + @GeneratedValue(strategy = GenerationType.IDENTITY)
  26 + private Integer id;
  27 +
  28 + private String codeName;
  29 +
  30 + private String roleName;
  31 +
  32 + private String descriptions;
  33 +
  34 + private boolean isSuperAdmin;
  35 +
  36 + private boolean enable;
  37 +
  38 + @JsonIgnore
  39 + @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
  40 + private Set<SysUser> users = new LinkedHashSet<>();
  41 +
  42 + @JsonIgnore
  43 + @ManyToMany
  44 + private Set<Module> modules = new LinkedHashSet<>();
  45 +
  46 + @JsonIgnore
  47 + @ManyToMany(mappedBy = "roles")
  48 + private Set<Resource> resources = new LinkedHashSet<>();
  49 +
  50 + @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
  51 + private Date createDate;
  52 +
  53 + @Column(name = "update_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  54 + private Date updateDate;
  55 +
  56 + /**
  57 + * 角色权限
  58 + *
  59 + * 角色树结构 本级只能管理下级角色,不能查看同级和上级的任何数据:这里主要为了规范管理 (管理员)层级的用户
  60 + *
  61 + * 只能看其他角色upCode 等于 本角色roleCode level字段等级比自己小的 其他角色 严格的树形结构,只能看自己分支下级节点
  62 + *
  63 + */
  64 + private int roleCode;
  65 +
  66 + private int upCode;
  67 +
  68 + private int level;
  69 +
  70 + /** 组合自己和父节点编码 */
  71 + @Formula(" concat(up_code, '_', role_code) ")
  72 + private String groupCode;
  73 +
  74 + @Formula(" concat(level, '_',role_code) ")
  75 + private String levelCode;
  76 +
  77 + private int pic;
  78 +
  79 + public Integer getId() {
  80 + return id;
  81 + }
  82 +
  83 + public void setId(Integer id) {
  84 + this.id = id;
  85 + }
  86 +
  87 + public String getRoleName() {
  88 + return roleName;
  89 + }
  90 +
  91 + public String getDescriptions() {
  92 + return descriptions;
  93 + }
  94 +
  95 + public void setDescriptions(String descriptions) {
  96 + this.descriptions = descriptions;
  97 + }
  98 +
  99 + public void setRoleName(String roleName) {
  100 + this.roleName = roleName;
  101 + }
  102 +
  103 + public boolean isEnable() {
  104 + return enable;
  105 + }
  106 +
  107 + public void setEnable(boolean enable) {
  108 + this.enable = enable;
  109 + }
  110 +
  111 + public Set<SysUser> getUsers() {
  112 + return users;
  113 + }
  114 +
  115 + public void setUsers(Set<SysUser> users) {
  116 + this.users = users;
  117 + }
  118 +
  119 + public boolean isSuperAdmin() {
  120 + return isSuperAdmin;
  121 + }
  122 +
  123 + public void setSuperAdmin(boolean isSuperAdmin) {
  124 + this.isSuperAdmin = isSuperAdmin;
  125 + }
  126 +
  127 + public Set<Module> getModules() {
  128 + return modules;
  129 + }
  130 +
  131 + public void setModules(Set<Module> modules) {
  132 + this.modules = modules;
  133 + }
  134 +
  135 + public Set<Resource> getResources() {
  136 + return resources;
  137 + }
  138 +
  139 + public void setResources(Set<Resource> resources) {
  140 + this.resources = resources;
  141 + }
  142 +
  143 + public Date getCreateDate() {
  144 + return createDate;
  145 + }
  146 +
  147 + public void setCreateDate(Date createDate) {
  148 + this.createDate = createDate;
  149 + }
  150 +
  151 + public Date getUpdateDate() {
  152 + return updateDate;
  153 + }
  154 +
  155 + public void setUpdateDate(Date updateDate) {
  156 + this.updateDate = updateDate;
  157 + }
  158 +
  159 + public String getCodeName() {
  160 + return codeName;
  161 + }
  162 +
  163 + public void setCodeName(String codeName) {
  164 + this.codeName = codeName;
  165 + }
  166 +
  167 + public int getRoleCode() {
  168 + return roleCode;
  169 + }
  170 +
  171 + public void setRoleCode(int roleCode) {
  172 + this.roleCode = roleCode;
  173 + }
  174 +
  175 + public int getUpCode() {
  176 + return upCode;
  177 + }
  178 +
  179 + public void setUpCode(int upCode) {
  180 + this.upCode = upCode;
  181 + }
  182 +
  183 + public int getLevel() {
  184 + return level;
  185 + }
  186 +
  187 + public void setLevel(int level) {
  188 + this.level = level;
  189 + }
  190 +
  191 + public String getGroupCode() {
  192 + return groupCode;
  193 + }
  194 +
  195 + public void setGroupCode(String groupCode) {
  196 + this.groupCode = groupCode;
  197 + }
  198 +
  199 +
  200 + public String getLevelCode() {
  201 + return levelCode;
  202 + }
  203 +
  204 + public void setLevelCode(String levelCode) {
  205 + this.levelCode = levelCode;
  206 + }
  207 +
  208 + public int getPic() {
  209 + return pic;
  210 + }
  211 +
  212 + public void setPic(int pic) {
  213 + this.pic = pic;
  214 + }
  215 +
  216 + @Override
  217 + public boolean equals(Object obj) {
  218 + return this.id.equals(((Role)obj).getId());
  219 + }
  220 +
  221 + @Override
  222 + public int hashCode() {
  223 + return this.toString().hashCode();
  224 + }
  225 +
  226 + @Override
  227 + public String toString() {
  228 + return this.id + "" + this.getCodeName();
  229 + }
  230 +}
... ...
src/main/java/com/bsth/entity/sys/SysUser.java
1   -package com.bsth.entity.sys;
2   -
3   -import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4   -
5   -import javax.persistence.*;
6   -import java.util.Date;
7   -import java.util.LinkedHashSet;
8   -import java.util.Set;
9   -
10   -@Entity
11   -@Table(name = "bsth_c_sys_user")
12   -@JsonIgnoreProperties(ignoreUnknown = true)
13   -@NamedEntityGraphs({
14   - @NamedEntityGraph(name = "sysUser_role", attributeNodes = {
15   - @NamedAttributeNode("roles")
16   - })
17   -})
18   -public class SysUser {
19   -
20   - @Id
21   - @GeneratedValue(strategy = GenerationType.IDENTITY)
22   - private Integer id;
23   -
24   - private String userName;
25   -
26   - private String name;
27   -
28   - private String password;
29   -
30   - @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
31   - private Date createDate;
32   -
33   - @Column(name = "last_loginDate", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
34   - private Date lastLoginDate;
35   -
36   - private String agencies;
37   -
38   - private boolean enabled;
39   -
40   - @ManyToMany(fetch = FetchType.EAGER)
41   - private Set<Role> roles = new LinkedHashSet<>();
42   -
43   -
44   - public Integer getId() {
45   - return id;
46   - }
47   -
48   - public void setId(Integer id) {
49   - this.id = id;
50   - }
51   -
52   - public String getUserName() {
53   - return userName;
54   - }
55   -
56   - public void setUserName(String userName) {
57   - this.userName = userName;
58   - }
59   -
60   - public String getName() {
61   - return name;
62   - }
63   -
64   - public void setName(String name) {
65   - this.name = name;
66   - }
67   -
68   - public Date getCreateDate() {
69   - return createDate;
70   - }
71   -
72   - public void setCreateDate(Date createDate) {
73   - this.createDate = createDate;
74   - }
75   -
76   - public Date getLastLoginDate() {
77   - return lastLoginDate;
78   - }
79   -
80   - public void setLastLoginDate(Date lastLoginDate) {
81   - this.lastLoginDate = lastLoginDate;
82   - }
83   -
84   - public String getAgencies() {
85   - return agencies;
86   - }
87   -
88   - public void setAgencies(String agencies) {
89   - this.agencies = agencies;
90   - }
91   -
92   - public boolean isEnabled() {
93   - return enabled;
94   - }
95   -
96   - public void setEnabled(boolean enabled) {
97   - this.enabled = enabled;
98   - }
99   -
100   - public String getPassword() {
101   - return password;
102   - }
103   -
104   - public void setPassword(String password) {
105   - this.password = password;
106   - }
107   -
108   - public Set<Role> getRoles() {
109   - return roles;
110   - }
111   -
112   - public void setRoles(Set<Role> roles) {
113   - this.roles = roles;
114   - }
115   -}
  1 +package com.bsth.entity.sys;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonIgnore;
  4 +import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  5 +import org.springframework.format.annotation.DateTimeFormat;
  6 +import org.springframework.util.StringUtils;
  7 +import org.joda.time.DateTime;
  8 +import javax.persistence.*;
  9 +import java.io.Serializable;
  10 +import java.util.Date;
  11 +import java.util.HashSet;
  12 +import java.util.LinkedHashSet;
  13 +import java.util.Set;
  14 +
  15 +@Entity
  16 +@Table(name = "bsth_c_sys_user")
  17 +@JsonIgnoreProperties(ignoreUnknown = true)
  18 +@NamedEntityGraphs({
  19 + @NamedEntityGraph(name = "sysUser_role", attributeNodes = {
  20 + @NamedAttributeNode("roles")
  21 + })
  22 +})
  23 +public class SysUser implements Serializable {
  24 +
  25 + @Id
  26 + @GeneratedValue(strategy = GenerationType.IDENTITY)
  27 + private Integer id;
  28 +
  29 + private String userName;
  30 +
  31 + private String name;
  32 +
  33 + @JsonIgnore
  34 + private String password;
  35 +
  36 + @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
  37 + private Date createDate;
  38 +
  39 + @Column(name = "update_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  40 + private Date updateDate;
  41 +
  42 + @DateTimeFormat(pattern = "yyyy-MM-dd")
  43 + private Date lastLoginDate;
  44 +
  45 + /** 最近密码更新时间 */
  46 + @Column(updatable = false, name = "last_pwd_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
  47 + @DateTimeFormat(pattern = "yyyy-MM-dd")
  48 + private Date lastPwdDate;
  49 + /** 密码有效期 */
  50 + private Integer pwdValidPeriod = 30;
  51 +
  52 + private String agencies;
  53 +
  54 + private boolean enabled;
  55 +
  56 + @ManyToMany(fetch = FetchType.EAGER)
  57 + private Set<Role> roles = new LinkedHashSet<>();
  58 +
  59 + private String jobCode;
  60 +
  61 + private String realName;
  62 +
  63 + /**
  64 + * 密码过期时间
  65 + */
  66 + @Transient
  67 + private Date pwdExpiredDate;
  68 +
  69 + public Integer getId() {
  70 + return id;
  71 + }
  72 +
  73 + public void setId(Integer id) {
  74 + this.id = id;
  75 + }
  76 +
  77 + public String getUserName() {
  78 + return userName;
  79 + }
  80 +
  81 + public void setUserName(String userName) {
  82 + this.userName = userName;
  83 + }
  84 +
  85 + public String getName() {
  86 + return name;
  87 + }
  88 +
  89 + public void setName(String name) {
  90 + this.name = name;
  91 + }
  92 +
  93 + public Date getCreateDate() {
  94 + return createDate;
  95 + }
  96 +
  97 + public void setCreateDate(Date createDate) {
  98 + this.createDate = createDate;
  99 + }
  100 +
  101 + public Date getUpdateDate() {
  102 + return updateDate;
  103 + }
  104 +
  105 + public void setUpdateDate(Date updateDate) {
  106 + this.updateDate = updateDate;
  107 + }
  108 +
  109 + public Date getLastLoginDate() {
  110 + return lastLoginDate;
  111 + }
  112 +
  113 + public void setLastLoginDate(Date lastLoginDate) {
  114 + this.lastLoginDate = lastLoginDate;
  115 + }
  116 +
  117 + public String getAgencies() {
  118 + return agencies;
  119 + }
  120 +
  121 + public void setAgencies(String agencies) {
  122 + this.agencies = agencies;
  123 + }
  124 +
  125 + public boolean isEnabled() {
  126 + return enabled;
  127 + }
  128 +
  129 + public void setEnabled(boolean enabled) {
  130 + this.enabled = enabled;
  131 + }
  132 +
  133 + public String getPassword() {
  134 + return password;
  135 + }
  136 +
  137 + public void setPassword(String password) {
  138 + this.password = password;
  139 + }
  140 +
  141 + public Set<Role> getRoles() {
  142 + return roles;
  143 + }
  144 +
  145 + public void setRoles(Set<Role> roles) {
  146 + this.roles = roles;
  147 + }
  148 +
  149 + public String getJobCode() {
  150 + return jobCode;
  151 + }
  152 +
  153 + public void setJobCode(String jobCode) {
  154 + this.jobCode = jobCode;
  155 + }
  156 +
  157 + public String getRealName() {
  158 + return realName;
  159 + }
  160 +
  161 + public void setRealName(String realName) {
  162 + this.realName = realName;
  163 + }
  164 +
  165 + @JsonIgnore
  166 + public Set<String> getLinks() {
  167 + Set<String> links = new HashSet<>();
  168 + if (links.size() == 0) {
  169 + for (Role role : roles) {
  170 + for (Module module : role.getModules()) {
  171 + String symbol = module.getMappSymbol();
  172 + if (!StringUtils.isEmpty(symbol)) {
  173 + String[] symbols = symbol.split(";");
  174 + for (String temp : symbols) {
  175 + if (!StringUtils.isEmpty(temp)) {
  176 + links.add(temp);
  177 + }
  178 + }
  179 + }
  180 + }
  181 + }
  182 + }
  183 +
  184 + return links;
  185 + }
  186 +
  187 + public Date getLastPwdDate() {
  188 + return lastPwdDate;
  189 + }
  190 +
  191 + public void setLastPwdDate(Date lastPwdDate) {
  192 + this.lastPwdDate = lastPwdDate;
  193 + }
  194 +
  195 + public Integer getPwdValidPeriod() {
  196 + return pwdValidPeriod;
  197 + }
  198 +
  199 + public void setPwdValidPeriod(Integer pwdValidPeriod) {
  200 + this.pwdValidPeriod = pwdValidPeriod;
  201 + }
  202 +
  203 + public Date getPwdExpiredDate() {
  204 + DateTime dateTime = new DateTime(getLastPwdDate());
  205 + if (pwdValidPeriod != null) {
  206 + dateTime = dateTime.plusDays(pwdValidPeriod);
  207 + }
  208 +
  209 + return dateTime.toDate();
  210 + }
  211 +
  212 + public void setPwdExpiredDate(Date pwdExpiredDate) {
  213 + this.pwdExpiredDate = pwdExpiredDate;
  214 + }
  215 +}
... ...
src/main/java/com/bsth/filter/AuthorityFilter.java 0 → 100644
  1 +package com.bsth.filter;
  2 +
  3 +import com.bsth.common.Constants;
  4 +import com.bsth.common.ResponseCode;
  5 +import com.bsth.data.SystemParamCache;
  6 +import com.fasterxml.jackson.databind.ObjectMapper;
  7 +import org.slf4j.Logger;
  8 +import org.slf4j.LoggerFactory;
  9 +import org.springframework.util.AntPathMatcher;
  10 +import org.springframework.util.PathMatcher;
  11 +
  12 +import javax.servlet.*;
  13 +import javax.servlet.http.HttpServletRequest;
  14 +import javax.servlet.http.HttpServletResponse;
  15 +import java.io.IOException;
  16 +import java.util.HashMap;
  17 +import java.util.Map;
  18 +import java.util.Set;
  19 +
  20 +/**
  21 + * 权限过滤器
  22 + * @author Hill
  23 + */
  24 +public class AuthorityFilter extends BaseFilter {
  25 +
  26 + Logger logger = LoggerFactory.getLogger(this.getClass());
  27 +
  28 + private ObjectMapper mapper = new ObjectMapper();
  29 +
  30 + private final String rootUri = "/";
  31 +
  32 + private final String scheduleReferer = "/real_control/v2";
  33 +
  34 + private PathMatcher matcher = new AntPathMatcher();
  35 +
  36 + private String[] pubUrls = new String[]{ "/pages/home.html", "/error", "/dictionary/all", "/user/validPWDExpired", "/user/isWeakCipher", "/user/isRealName", "/user/currentUser", "/user/companyData", "/user/changePWD", "/pages/permission/user/changePWD.html", "/module/findByCurrentUser", "/cars_sc/all", "/ee/all_py", "/eci/validate_get_destroy_info", "/business/all", "/personnel/all_py", "/companyAuthority/all", "/line/all", "/basic/refresh_person_data", "/downloadFile/download", "/report/lineList", "/adminUtils/**", "/pages/scheduleApp/module/common/**", "/e10adc3949ba59abbe56e057f20f883e.html", "/8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92.html"};
  37 +
  38 + @Override
  39 + public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
  40 + if (!SystemParamCache.getEnableFilterAuthority()) {
  41 + chain.doFilter(request, response);
  42 + return;
  43 + }
  44 +
  45 + String uri = request.getRequestURI(), referer = request.getHeader("Referer");
  46 + Set<String> links = (Set<String>) request.getSession().getAttribute(Constants.RESOURCE_AUTHORITYS);
  47 + if (rootUri.equals(uri) || (referer != null && referer.indexOf(scheduleReferer) > 0) || isPubURL(uri)) {
  48 + chain.doFilter(request, response);
  49 + return;
  50 + }
  51 + if (links != null) {
  52 + boolean matched = false;
  53 + for (String link : links) {
  54 + if (matcher.match(link, uri)) {
  55 + matched = true;
  56 + break;
  57 + }
  58 + }
  59 + if (!matched) {
  60 + Map<String, Object> result = new HashMap<>();
  61 + result.put("status", ResponseCode.ERROR);
  62 + result.put("msg", "未授权的访问");
  63 + response.setContentType("text/html;charset=utf-8");
  64 + response.getWriter().write(mapper.writeValueAsString(result));
  65 + return;
  66 + }
  67 + }
  68 +
  69 + chain.doFilter(request, response);
  70 + }
  71 +
  72 + protected boolean isPubURL(String uri) {
  73 + for (String pubUrl : pubUrls) {
  74 + if (matcher.match(pubUrl, uri)) {
  75 + return true;
  76 + }
  77 + }
  78 +
  79 + return false;
  80 + }
  81 +}
0 82 \ No newline at end of file
... ...
src/main/java/com/bsth/filter/BaseFilter.java
1   -package com.bsth.filter;
2   -
3   -import com.bsth.common.Constants;
4   -import org.springframework.util.AntPathMatcher;
5   -import org.springframework.util.PathMatcher;
6   -
7   -import javax.servlet.*;
8   -import javax.servlet.http.HttpServletRequest;
9   -import javax.servlet.http.HttpServletResponse;
10   -import java.io.IOException;
11   -
12   -public abstract class BaseFilter implements Filter {
13   -
14   - private final PathMatcher pathMatcher = new AntPathMatcher();
15   -
16   - /**
17   - * 白名单
18   - */
19   - private String[] whiteListURLs = { Constants.LOGIN_PAGE,Constants.CAPTCHA, Constants.SERVICE_INTERFACE,
20   - Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.METRONIC_URL, Constants.LOGIN, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.XD_REAL_GPS, Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT,Constants.XIANDIAO_LOGIN ,Constants.IPAD_IMG_URL};
21   -
22   - @Override
23   - public void destroy() {
24   -
25   - }
26   -
27   - @Override
28   - public void doFilter(ServletRequest request, ServletResponse response,
29   - FilterChain chain) throws IOException, ServletException {
30   -
31   - HttpServletRequest httpRequest = (HttpServletRequest) request;
32   - HttpServletResponse httpResponse = (HttpServletResponse) response;
33   -
34   - String currentURL = httpRequest.getServletPath();
35   -
36   - if (isWhiteURL(currentURL)) {
37   - chain.doFilter(request, response);
38   - return;
39   - }
40   -
41   - doFilter(httpRequest, httpResponse, chain);
42   - return;
43   - }
44   -
45   - public void doFilter(HttpServletRequest request,
46   - HttpServletResponse response, FilterChain chain)
47   - throws IOException, ServletException {
48   - chain.doFilter(request, response);
49   - }
50   -
51   - @Override
52   - public void init(FilterConfig arg0) throws ServletException {
53   -
54   - }
55   -
56   - private boolean isWhiteURL(String currentURL) {
57   - for (String whiteURL : whiteListURLs) {
58   - if (pathMatcher.match(whiteURL, currentURL)) {
59   - return true;
60   - }
61   - }
62   - return false;
63   - }
64   -}
  1 +package com.bsth.filter;
  2 +
  3 +import com.bsth.common.Constants;
  4 +import org.springframework.util.AntPathMatcher;
  5 +import org.springframework.util.PathMatcher;
  6 +
  7 +import javax.servlet.*;
  8 +import javax.servlet.http.HttpServletRequest;
  9 +import javax.servlet.http.HttpServletResponse;
  10 +import java.io.IOException;
  11 +
  12 +public abstract class BaseFilter implements Filter {
  13 +
  14 + private final PathMatcher pathMatcher = new AntPathMatcher();
  15 +
  16 + /**
  17 + * 白名单
  18 + */
  19 + private String[] whiteListURLs = { Constants.LOGIN_PAGE,Constants.CAPTCHA, Constants.SERVICE_INTERFACE,
  20 + Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.METRONIC_URL, Constants.LOGIN, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.XD_REAL_GPS, Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT,Constants.XIANDIAO_LOGIN ,Constants.IPAD_IMG_URL};
  21 +
  22 + @Override
  23 + public void destroy() {
  24 +
  25 + }
  26 +
  27 + @Override
  28 + public void doFilter(ServletRequest request, ServletResponse response,
  29 + FilterChain chain) throws IOException, ServletException {
  30 +
  31 + HttpServletRequest httpRequest = (HttpServletRequest) request;
  32 + HttpServletResponse httpResponse = (HttpServletResponse) response;
  33 + httpResponse.setHeader("Content-Security-Policy", "script-src 'unsafe-inline' 'unsafe-eval' http: https:; worker-src blob:;");
  34 +
  35 + String currentURL = httpRequest.getServletPath();
  36 +
  37 + if (isWhiteURL(currentURL)) {
  38 + chain.doFilter(request, response);
  39 + return;
  40 + }
  41 +
  42 + doFilter(httpRequest, httpResponse, chain);
  43 + return;
  44 + }
  45 +
  46 + public void doFilter(HttpServletRequest request,
  47 + HttpServletResponse response, FilterChain chain)
  48 + throws IOException, ServletException {
  49 + chain.doFilter(request, response);
  50 + }
  51 +
  52 + @Override
  53 + public void init(FilterConfig arg0) throws ServletException {
  54 +
  55 + }
  56 +
  57 + private boolean isWhiteURL(String currentURL) {
  58 + for (String whiteURL : whiteListURLs) {
  59 + if (pathMatcher.match(whiteURL, currentURL)) {
  60 + return true;
  61 + }
  62 + }
  63 + return false;
  64 + }
  65 +}
... ...
src/main/java/com/bsth/filter/WhiteIpFilter.java
1 1 package com.bsth.filter;
2 2  
3   -import com.bsth.common.Setting;
4   -import com.bsth.data.BasicData;
  3 +import com.bsth.data.SystemParamCache;
  4 +import com.bsth.data.WhiteIpCache;
5 5 import com.bsth.entity.WhiteIp;
6 6 import com.bsth.util.IpUtils;
7 7 import org.slf4j.Logger;
8 8 import org.slf4j.LoggerFactory;
9   -import org.springframework.stereotype.Component;
10 9  
11 10 import javax.servlet.*;
12 11 import javax.servlet.http.HttpServletRequest;
... ... @@ -21,17 +20,7 @@ import java.util.List;
21 20 //@Component
22 21 public class WhiteIpFilter implements Filter {
23 22  
24   - Logger logger = LoggerFactory.getLogger(this.getClass());
25   -
26   - private Setting setting;
27   -
28   - public Setting getSetting() {
29   - return setting;
30   - }
31   -
32   - public void setSetting(Setting setting) {
33   - this.setting = setting;
34   - }
  23 + Logger logger = LoggerFactory.getLogger(this.getClass());
35 24  
36 25 @Override
37 26 public void init(FilterConfig filterConfig) throws ServletException {
... ... @@ -39,29 +28,34 @@ public class WhiteIpFilter implements Filter {
39 28 }
40 29  
41 30 @Override
42   - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
43   - HttpServletRequest req = (HttpServletRequest)request;
44   - HttpServletResponse res = (HttpServletResponse)response;
  31 + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
45 32  
46   - String ip = IpUtils.getIpAddr(req);
47   - boolean isMatch = false;
48   - List<WhiteIp> whiteIps = BasicData.whiteIpList;
49   - if (whiteIps != null) {
50   - for (WhiteIp whiteIp : whiteIps) {
51   - if (ip.equals(whiteIp.getIp())) {
52   - isMatch = true;
53   - break;
54   - }
55   - }
56   - }
57   - if (isMatch || !setting.isWhiteipEnabled()) {
58   - chain.doFilter(request, response);
59   - } else {
60   - logger.info(ip + "未在白名单中,不予访问");
61   - res.setStatus(404);
62   - return;
63   - }
64   - }
  33 + if (!SystemParamCache.getEnabledWhiteIp()) {
  34 + chain.doFilter(request, response);
  35 + return;
  36 + }
  37 +
  38 + HttpServletRequest req = (HttpServletRequest)request;
  39 + HttpServletResponse res = (HttpServletResponse)response;
  40 +
  41 + String ip = IpUtils.getIpAddr(req);
  42 + boolean isMatch = false;
  43 + List<WhiteIp> whiteIps = WhiteIpCache.getWhiteIps();
  44 + if (whiteIps != null) {
  45 + for (WhiteIp whiteIp : whiteIps) {
  46 + if (ip.equals(whiteIp.getIp())) {
  47 + isMatch = true;
  48 + break;
  49 + }
  50 + }
  51 + }
  52 + if (isMatch) {
  53 + chain.doFilter(request, response);
  54 + } else {
  55 + logger.info("{}未在白名单中,不予访问", ip);
  56 + res.setStatus(404);
  57 + }
  58 + }
65 59  
66 60 @Override
67 61 public void destroy() {
... ...
src/main/java/com/bsth/repository/sys/RoleRepository.java
1   -package com.bsth.repository.sys;
2   -
3   -
4   -import javax.transaction.Transactional;
5   -
6   -import org.springframework.data.jpa.repository.Modifying;
7   -import org.springframework.data.jpa.repository.Query;
8   -import org.springframework.stereotype.Repository;
9   -
10   -import com.bsth.entity.sys.Role;
11   -import com.bsth.repository.BaseRepository;
12   -
13   -@Repository
14   -public interface RoleRepository extends BaseRepository<Role, Integer>{
15   -
16   - /**
17   - * @Title: update
18   - * @Description: TODO(简洁版更新(不需要级联的))
19   - */
20   - @Modifying
21   - @Transactional
22   - @Query("update Role r set r.codeName=?1, r.roleName=?2, r.enable=?3, r.descriptions=?4 where r.id=?5")
23   - void update(String codeName, String roleName, boolean enable, String descriptions, Integer id);
24   -}
  1 +package com.bsth.repository.sys;
  2 +
  3 +
  4 +import javax.transaction.Transactional;
  5 +
  6 +import org.springframework.data.jpa.repository.Modifying;
  7 +import org.springframework.data.jpa.repository.Query;
  8 +import org.springframework.stereotype.Repository;
  9 +
  10 +import com.bsth.entity.sys.Role;
  11 +import com.bsth.repository.BaseRepository;
  12 +
  13 +import java.util.List;
  14 +
  15 +@Repository
  16 +public interface RoleRepository extends BaseRepository<Role, Integer>{
  17 +
  18 + // 查询最大ID
  19 + @Query(value = "SELECT IFNULL(num,0) as maxId from (SELECT MAX(id) as num FROM bsth_c_sys_role) k"
  20 + , nativeQuery=true)
  21 + public int roleMaxId();
  22 +
  23 + /**
  24 + * @Title: update
  25 + * @Description: TODO(简洁版更新(不需要级联的))
  26 + */
  27 + @Modifying
  28 + @Transactional
  29 + @Query("update Role r set r.codeName=?1, r.roleName=?2, r.enable=?3, r.descriptions=?4 where r.id=?5")
  30 + void update(String codeName, String roleName, boolean enable, String descriptions, Integer id);
  31 +
  32 + @Query(value = "select * from role where id in(?1)",nativeQuery = true)
  33 + List<Role> findAllById(String ids);
  34 +
  35 +// @Query(value = "select r from Role r where < ?1")
  36 +// List<Role> findSubordinate(Integer pic);
  37 +}
... ...
src/main/java/com/bsth/repository/sys/SysUserRepository.java
1   -package com.bsth.repository.sys;
2   -
3   -import com.bsth.entity.sys.SysUser;
4   -import com.bsth.repository.BaseRepository;
5   -import org.springframework.data.jpa.repository.EntityGraph;
6   -import org.springframework.data.jpa.repository.Modifying;
7   -import org.springframework.data.jpa.repository.Query;
8   -import org.springframework.stereotype.Repository;
9   -import org.springframework.transaction.annotation.Transactional;
10   -
11   -import java.util.List;
12   -
13   -@Repository
14   -public interface SysUserRepository extends BaseRepository<SysUser, Integer>{
15   -
16   - SysUser findByUserName(String userName);
17   -
18   - @Transactional
19   - @Modifying
20   - @Query(value="update bsth_c_sys_user set enabled=?2 where id=?1",nativeQuery=true)
21   - int changeEnabled(int id,int enabled);
22   -
23   - @Transactional
24   - @Modifying
25   - @Query(value="update bsth_c_sys_user set password=?2 where id=?1",nativeQuery=true)
26   - int changePWD(int id,String newPWD);
27   -
28   - @EntityGraph(value = "sysUser_role", type = EntityGraph.EntityGraphType.FETCH)
29   - @Query(value = "select DISTINCT u from SysUser u")
30   - List<SysUser> findAll_distinct();
31   -}
  1 +package com.bsth.repository.sys;
  2 +
  3 +import com.bsth.entity.sys.SysUser;
  4 +import com.bsth.repository.BaseRepository;
  5 +import org.springframework.data.jpa.repository.EntityGraph;
  6 +import org.springframework.data.jpa.repository.Modifying;
  7 +import org.springframework.data.jpa.repository.Query;
  8 +import org.springframework.stereotype.Repository;
  9 +import org.springframework.transaction.annotation.Transactional;
  10 +
  11 +import java.util.List;
  12 +
  13 +@Repository
  14 +public interface SysUserRepository extends BaseRepository<SysUser, Integer>{
  15 +
  16 + SysUser findByUserName(String userName);
  17 +
  18 + @Transactional
  19 + @Modifying
  20 + @Query(value="update bsth_c_sys_user set enabled=?2 where id=?1",nativeQuery=true)
  21 + int changeEnabled(int id,int enabled);
  22 +
  23 + @Transactional
  24 + @Modifying
  25 + @Query(value="update bsth_c_sys_user set password=?2, last_pwd_date = now() where id=?1",nativeQuery=true)
  26 + int changePWD(int id,String newPWD);
  27 +
  28 + @EntityGraph(value = "sysUser_role", type = EntityGraph.EntityGraphType.FETCH)
  29 + @Query(value = "select DISTINCT u from SysUser u")
  30 + List<SysUser> findAll_distinct();
  31 +
  32 + @Modifying
  33 + @Query(value="update bsth_c_sys_user set last_login_date=now() where user_name = ?1",nativeQuery=true)
  34 + void recordLoginDate(String userName);
  35 +
  36 + @Modifying
  37 + @Query(value="update bsth_c_sys_user set job_code = ?1, real_name = ?2 where id = ?3",nativeQuery=true)
  38 + void realName(String jobCode, String realName, int id);
  39 +}
... ...
src/main/java/com/bsth/security/WebSecurityConfig.java
1 1 package com.bsth.security;
2 2  
3   -import com.bsth.common.Setting;
  3 +import com.bsth.common.Constants;
  4 +import com.bsth.filter.AccessLogFilter;
  5 +import com.bsth.filter.AuthorityFilter;
4 6 import com.bsth.filter.WhiteIpFilter;
  7 +import com.bsth.security.filter.LoginInterceptor;
5 8 import org.springframework.beans.factory.annotation.Autowired;
6   -import org.springframework.beans.factory.annotation.Value;
7 9 import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
8 10 import org.springframework.context.annotation.Bean;
9 11 import org.springframework.context.annotation.Configuration;
... ... @@ -20,9 +22,6 @@ import org.springframework.security.web.firewall.DefaultHttpFirewall;
20 22 import org.springframework.security.web.firewall.HttpFirewall;
21 23 import org.springframework.security.web.session.HttpSessionEventPublisher;
22 24  
23   -import com.bsth.common.Constants;
24   -import com.bsth.security.filter.LoginInterceptor;
25   -
26 25 @Configuration
27 26 @EnableWebSecurity
28 27 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
... ... @@ -36,15 +35,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
36 35 @Autowired
37 36 SecurityMetadataSourceService securityMetadataSourceService;
38 37  
39   - @Autowired
40   - private Setting setting;
41   -
42 38 @Override
43 39 public void configure(WebSecurity web) throws Exception {
44 40 // 白名单
45   - web.ignoring().antMatchers(Constants.LOGIN, Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.CAPTCHA,
46   - Constants.SERVICE_INTERFACE, Constants.METRONIC_URL, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL,
47   - Constants.XD_CHILD_PAGES, Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT);
  41 + web.ignoring().antMatchers(Constants.LOGIN_PAGE, Constants.LOGIN, Constants.ORIGINAL_LOGIN_PAGE, Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.CAPTCHA,
  42 + Constants.SERVICE_INTERFACE, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES,
  43 + Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT, Constants.FILE_AUTH);
48 44 }
49 45  
50 46 @Override
... ... @@ -75,11 +71,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
75 71 .expiredUrl(Constants.LOGIN_PAGE + "?error=true")
76 72 .maxSessionsPreventsLogin(false)
77 73 .sessionRegistry(sessionRegistry());
  74 + //edge游览器地图和轨迹播放不行的问题
  75 +// http.headers().contentSecurityPolicy(
  76 +// "script-src 'unsafe-inline' 'unsafe-eval' http: https:; worker-src blob:;"
  77 +// );
78 78  
79 79 WhiteIpFilter whiteIpFilter = new WhiteIpFilter();
80   - whiteIpFilter.setSetting(setting);
81 80 http.addFilterBefore(whiteIpFilter, FilterSecurityInterceptor.class);
82 81 http.addFilterBefore(new LoginInterceptor(), FilterSecurityInterceptor.class);
  82 + http.addFilterBefore(new AccessLogFilter(), FilterSecurityInterceptor.class);
  83 + http.addFilterBefore(new AuthorityFilter(), FilterSecurityInterceptor.class);
83 84 http.addFilter(filterSecurityInterceptor());
84 85 }
85 86  
... ...
src/main/java/com/bsth/service/SystemParamService.java
... ... @@ -6,4 +6,8 @@ import com.bsth.entity.SystemParam;
6 6 * @author Hill
7 7 */
8 8 public interface SystemParamService extends BaseService<SystemParam, Integer> {
  9 +
  10 + void refresh();
  11 +
  12 + String getValue(String key);
9 13 }
... ...
src/main/java/com/bsth/service/impl/SystemParamServiceImpl.java
1 1 package com.bsth.service.impl;
2 2  
3 3 import com.bsth.entity.SystemParam;
  4 +import com.bsth.repository.SystemParamRepository;
4 5 import com.bsth.service.SystemParamService;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.scheduling.annotation.EnableScheduling;
  8 +import org.springframework.scheduling.annotation.Scheduled;
  9 +import org.springframework.stereotype.Service;
  10 +
  11 +import java.util.HashMap;
  12 +import java.util.Map;
5 13  
6 14 /**
7 15 * @author Hill
8 16 */
  17 +@Service
  18 +@EnableScheduling
9 19 public class SystemParamServiceImpl extends BaseServiceImpl<SystemParam, Integer> implements SystemParamService {
  20 +
  21 + @Autowired
  22 + private SystemParamRepository systemParamRepository;
  23 +
  24 + private Map<String, String> pairs = new HashMap<>();
  25 +
  26 + @Scheduled(cron = "0 0/30 * * * ?")
  27 + public void refresh() {
  28 + for (SystemParam sp : systemParamRepository.findAll()) {
  29 + pairs.put(sp.getKey(), sp.getValue());
  30 + }
  31 + }
  32 +
  33 + public String getValue(String key) {
  34 + return pairs.get(key);
  35 + }
10 36 }
... ...
src/main/java/com/bsth/service/sys/RoleService.java
1   -package com.bsth.service.sys;
2   -
3   -import java.util.Map;
4   -
5   -import com.bsth.entity.sys.Role;
6   -import com.bsth.service.BaseService;
7   -
8   -public interface RoleService extends BaseService<Role, Integer>{
9   -
10   - Map<String, Object> settRoleModules(Integer roleId, String mIds);
11   -
12   - Map<String, Object> roleInfo(Integer id);
13   -}
  1 +package com.bsth.service.sys;
  2 +
  3 +import com.bsth.entity.sys.Role;
  4 +import com.bsth.service.BaseService;
  5 +
  6 +import java.util.List;
  7 +import java.util.Map;
  8 +
  9 +public interface RoleService extends BaseService<Role, Integer>{
  10 +
  11 + Map<String, Object> findSubordinate();
  12 +
  13 + Map<String, Object> add(Role role);
  14 +
  15 + Map<String, Object> settRoleModules(Integer roleId, String mIds);
  16 +
  17 + Map<String, Object> roleInfo(Integer id);
  18 +
  19 + List<Role> findAllByIds(String ids);
  20 +
  21 + boolean checkOperationLegality(Integer operationRoleId);
  22 +}
... ...
src/main/java/com/bsth/service/sys/SysUserService.java
1   -package com.bsth.service.sys;
2   -
3   -import com.bsth.entity.sys.SysUser;
4   -import com.bsth.service.BaseService;
5   -
6   -import java.util.List;
7   -import java.util.Map;
8   -
9   -public interface SysUserService extends BaseService<SysUser, Integer>{
10   -
11   - SysUser findByUserName(String name);
12   -
13   - int changeEnabled(int id,int enabled);
14   -
15   - int changePWD(int id,String newPWD);
16   -
17   - Map<String,Object> register(SysUser u);
18   -
19   - List<SysUser> findAll_distinct();
20   -}
  1 +package com.bsth.service.sys;
  2 +
  3 +import com.bsth.entity.sys.SysUser;
  4 +import com.bsth.service.BaseService;
  5 +
  6 +import java.util.List;
  7 +import java.util.Map;
  8 +
  9 +public interface SysUserService extends BaseService<SysUser, Integer>{
  10 +
  11 + SysUser findByUserName(String name);
  12 +
  13 + int changeEnabled(int id,int enabled);
  14 +
  15 + int changePWD(int id,String newPWD);
  16 +
  17 + /**
  18 + * 检测指定用户密码是否过期
  19 + * @param userName 用户名
  20 + */
  21 + boolean validPWDExpired(String userName);
  22 +
  23 + Map<String,Object> register(SysUser u);
  24 +
  25 + List<SysUser> findAll_distinct();
  26 +
  27 + Map<String, Object> resetPassword(Integer id, Integer pwdValidPeriod);
  28 +
  29 + void recordLoginDate(String userName);
  30 +
  31 + void realName(String jobCode, String realName, int id);
  32 +}
... ...
src/main/java/com/bsth/service/sys/impl/PwdGenerator.java 0 → 100644
  1 +package com.bsth.service.sys.impl;
  2 +
  3 +import java.util.Random;
  4 +
  5 +public class PwdGenerator {
  6 + private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";
  7 +
  8 + /**
  9 + * 查找一个char数组中还没有填充字符的位置
  10 + */
  11 + private static int nextIndex(char[] chars, Random rnd) {
  12 + int index = rnd.nextInt(chars.length);
  13 + while (chars[index] != 0) {
  14 + index = rnd.nextInt(chars.length);
  15 + }
  16 + return index;
  17 + }
  18 +
  19 + /**
  20 + * 返回一个随机的特殊字符
  21 + */
  22 + private static char nextSpecialChar(Random rnd) {
  23 + return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
  24 + }
  25 +
  26 + /**
  27 + * 返回一个随机的大写字母
  28 + */
  29 + private static char nextUpperLetter(Random rnd) {
  30 + return (char) ('A' + rnd.nextInt(26));
  31 + }
  32 +
  33 + /**
  34 + * 返回一个随机的小写字母
  35 + */
  36 + private static char nextLowerLetter(Random rnd) {
  37 + return (char) ('a' + rnd.nextInt(26));
  38 + }
  39 +
  40 + /**
  41 + * 返回一个随机的数字
  42 + */
  43 + private static char nextNumLetter(Random rnd) {
  44 + return (char) ('0' + rnd.nextInt(10));
  45 + }
  46 +
  47 + /**
  48 + * 返回一个随机的字符
  49 + */
  50 + private static char nextChar(Random rnd) {
  51 + switch (rnd.nextInt(4)) {
  52 + case 0:
  53 + return (char) ('a' + rnd.nextInt(26));
  54 + case 1:
  55 + return (char) ('A' + rnd.nextInt(26));
  56 + case 2:
  57 + return (char) ('0' + rnd.nextInt(10));
  58 + default:
  59 + return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
  60 + }
  61 + }
  62 +
  63 + /**
  64 + * 生成指定位数的随机数
  65 + */
  66 + public static String randomPassword(int length) {
  67 + if(length < 3){
  68 + return "";
  69 + }
  70 + char[] chars = new char[length];
  71 + Random rnd = new Random();
  72 +
  73 + //1. 至少生成一个大写字母、小写字母、特殊字符、数字
  74 + chars[nextIndex(chars, rnd)] = nextUpperLetter(rnd);
  75 + chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd);
  76 + chars[nextIndex(chars, rnd)] = nextNumLetter(rnd);
  77 +
  78 + //2. 填补其他位置的字符
  79 + for (int i = 0; i < length; i++) {
  80 + if (chars[i] == 0) {
  81 + chars[i] = nextChar(rnd);
  82 + }
  83 + }
  84 +
  85 + //3. 返回结果
  86 + return new String(chars);
  87 + }
  88 +
  89 +
  90 + /**
  91 + * 测试代码
  92 + */
  93 + public static void main(String[] args) {
  94 + for (int i = 0; i < 10; i++) {
  95 + System.out.println(randomPassword(16));
  96 + }
  97 +
  98 + }
  99 +
  100 +}
... ...
src/main/java/com/bsth/service/sys/impl/RoleServiceImpl.java
1   -package com.bsth.service.sys.impl;
2   -
3   -import java.text.SimpleDateFormat;
4   -import java.util.ArrayList;
5   -import java.util.HashMap;
6   -import java.util.Iterator;
7   -import java.util.List;
8   -import java.util.Map;
9   -import java.util.Set;
10   -
11   -import org.slf4j.Logger;
12   -import org.slf4j.LoggerFactory;
13   -import org.springframework.beans.factory.annotation.Autowired;
14   -import org.springframework.stereotype.Service;
15   -
16   -import com.bsth.common.ResponseCode;
17   -import com.bsth.entity.sys.Module;
18   -import com.bsth.entity.sys.Role;
19   -import com.bsth.entity.sys.SysUser;
20   -import com.bsth.repository.sys.ModuleRepository;
21   -import com.bsth.repository.sys.RoleRepository;
22   -import com.bsth.service.impl.BaseServiceImpl;
23   -import com.bsth.service.sys.RoleService;
24   -
25   -@Service
26   -public class RoleServiceImpl extends BaseServiceImpl<Role, Integer> implements
27   - RoleService {
28   -
29   - Logger logger = LoggerFactory.getLogger(this.getClass());
30   -
31   - @Autowired
32   - RoleRepository roleRepository;
33   -
34   - @Autowired
35   - ModuleRepository moduleRepository;
36   -
37   - SimpleDateFormat sdfMinute = new SimpleDateFormat("yyyy-MM-dd HH:mm");
38   -
39   - @Override
40   - public Map<String, Object> save(Role t) {
41   - if (t.getId() != null) {
42   - // 更新
43   - Map<String, Object> map = new HashMap<>();
44   - try {
45   - roleRepository.update(t.getCodeName(), t.getRoleName(),
46   - t.isEnable(), t.getDescriptions(), t.getId());
47   - map.put("status", ResponseCode.SUCCESS);
48   - } catch (Exception e) {
49   - map.put("status", ResponseCode.ERROR);
50   - }
51   - return map;
52   - }
53   - return super.save(t);
54   - }
55   -
56   - @Override
57   - public Map<String, Object> settRoleModules(Integer roleId, String mIds) {
58   -
59   - Map<String, Object> map = new HashMap<>();
60   - try {
61   - Role role = roleRepository.findOne(roleId);
62   -
63   - List<Integer> idList = new ArrayList<>();
64   - String[] array = mIds.split(",");
65   - for (String id : array) {
66   - if (null == id || id.trim().equals(""))
67   - continue;
68   - idList.add(Integer.parseInt(id));
69   - }
70   -
71   - Set<Module> mList = moduleRepository.findByIds(idList);
72   - role.setModules(mList);
73   - roleRepository.save(role);
74   - map.put("status", ResponseCode.SUCCESS);
75   - } catch (Exception e) {
76   - logger.error("", e);
77   - map.put("status", ResponseCode.ERROR);
78   - }
79   - return map;
80   - }
81   -
82   - @Override
83   - public Map<String, Object> roleInfo(Integer id) {
84   - Map<String, Object> map = new HashMap<>();
85   - Role role = roleRepository.findOne(id);
86   - map.put("codeName", role.getCodeName());
87   - map.put("roleName", role.getRoleName());
88   - map.put("createDate", sdfMinute.format(role.getCreateDate()));
89   - map.put("updateDate", sdfMinute.format(role.getUpdateDate()));
90   - map.put("enable", role.isEnable()==true?1:0);
91   - map.put("descriptions", role.getDescriptions());
92   - map.put("modules", role.getModules().size());
93   - map.put("resources", role.getResources().size());
94   - String userNames = "";
95   - Set<SysUser> users = role.getUsers();
96   - if(!users.isEmpty()){
97   - Iterator<SysUser> it = users.iterator();
98   - while(it.hasNext()){
99   - SysUser user = it.next();
100   - userNames = user.getUserName()+"...";
101   - }
102   - }
103   - map.put("userNames", userNames);
104   - return map;
105   - }
106   -}
  1 +package com.bsth.service.sys.impl;
  2 +
  3 +import java.beans.BeanInfo;
  4 +import java.beans.Introspector;
  5 +import java.beans.PropertyDescriptor;
  6 +import java.lang.reflect.Method;
  7 +import java.text.SimpleDateFormat;
  8 +import java.util.*;
  9 +
  10 +import com.bsth.security.util.SecurityUtils;
  11 +import org.slf4j.Logger;
  12 +import org.slf4j.LoggerFactory;
  13 +import org.springframework.beans.factory.annotation.Autowired;
  14 +import org.springframework.stereotype.Service;
  15 +
  16 +import com.bsth.common.ResponseCode;
  17 +import com.bsth.entity.sys.Module;
  18 +import com.bsth.entity.sys.Role;
  19 +import com.bsth.entity.sys.SysUser;
  20 +import com.bsth.repository.sys.ModuleRepository;
  21 +import com.bsth.repository.sys.RoleRepository;
  22 +import com.bsth.service.impl.BaseServiceImpl;
  23 +import com.bsth.service.sys.RoleService;
  24 +
  25 +@Service
  26 +public class RoleServiceImpl extends BaseServiceImpl<Role, Integer> implements
  27 + RoleService {
  28 +
  29 + Logger logger = LoggerFactory.getLogger(this.getClass());
  30 +
  31 + @Autowired
  32 + RoleRepository roleRepository;
  33 +
  34 + @Autowired
  35 + ModuleRepository moduleRepository;
  36 +
  37 + SimpleDateFormat sdfMinute = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  38 +
  39 + @Override
  40 + public Map<String, Object> findSubordinate() {
  41 + SysUser user = SecurityUtils.getCurrentUser();
  42 + Iterator<Role> itRole = user.getRoles().iterator();
  43 + Role ro = new Role();
  44 + while(itRole.hasNext()){//判断是否有下一个
  45 + ro = itRole.next();
  46 + }
  47 + Map<String, Object> map = new HashMap<>();
  48 + List<Map<String, Object>> rsRoleList = new ArrayList<>();
  49 + try {
  50 + // 读取层次数据结果集列表
  51 + Iterator<Role> roleList = roleRepository.findAll().iterator();
  52 +
  53 + // 节点列表(散列表,用于临时存储节点对象)
  54 + Map<String, Object> nodeList = new HashMap<>();
  55 + // 根节点
  56 + List rootlist = new ArrayList();
  57 + while(roleList.hasNext()){
  58 + Role role = roleList.next();
  59 + HashMap map0 = new HashMap();
  60 + map0.put("id", role.getId());
  61 + map0.put("roleCode", role.getRoleCode());
  62 + map0.put("upCode", role.getUpCode());
  63 + map0.put("roleName", role.getRoleName());
  64 + map0.put("codeName", role.getCodeName());
  65 + map0.put("level", role.getLevel());
  66 + map0.put("levelCode", role.getLevelCode());
  67 + nodeList.put(role.getLevelCode(), map0);
  68 + }
  69 + // 构造无序的多叉树
  70 + Set entrySet = nodeList.entrySet();
  71 + for (Iterator it = entrySet.iterator(); it.hasNext();) {
  72 + Map<String, Object> map1 = (HashMap) ((Map.Entry) it.next()).getValue();
  73 +// Map<String, Object> map1 = objectToMap(it.next());
  74 + if (map1.get("upCode") == null || map1.get("upCode").equals("")
  75 + || Integer.parseInt(map1.get("upCode").toString()) == 0) {
  76 + // root = node;
  77 + rootlist.add(map1);
  78 + } else {
  79 + Map<String, Object> tempmap = ((HashMap)nodeList.get((Integer.parseInt(map1.get("level").toString())-1)+"_"+map1.get("upCode")));
  80 +// Map<String, Object> tempmap = objectToMap(nodeList.get((Integer.parseInt(map1.get("level").toString())-1)+"_"+map1.get("upCode")));
  81 + System.out.println(tempmap);
  82 +
  83 + List templist = (List) tempmap.get("children");
  84 + if (null != templist) {
  85 + templist.add(map1);
  86 + } else {
  87 + templist = new ArrayList();
  88 + templist.add(map1);
  89 + }
  90 + tempmap.put("children", templist);
  91 + }
  92 + }
  93 + getRoleList(rootlist,ro.getLevelCode(),rsRoleList,false);
  94 +
  95 + // 排序后输出
  96 +// ComparatorSysrole(rootlist);
  97 + map.put("list", rsRoleList);
  98 + map.put("status", ResponseCode.SUCCESS);
  99 + map.put("msg", "成功");
  100 + } catch (Exception e) {
  101 + map.put("status", ResponseCode.ERROR);
  102 + map.put("msg", e);
  103 + logger.error("error",e);
  104 + }
  105 + return map;
  106 + }
  107 +
  108 + private void getRoleList(List<Map<String, Object>> list, String levelCode, List<Map<String, Object>> roleList,boolean isChildren){
  109 + try{
  110 + if(isChildren){
  111 + for (Map<String, Object> map : list) {
  112 + roleList.add(map);
  113 + List mapList = (List) map.get("children");
  114 + if (mapList != null && mapList.size() > 0) {
  115 + getRoleList(mapList,levelCode,roleList,isChildren);
  116 + }
  117 + }
  118 +
  119 + } else {
  120 + for (Map<String, Object> map : list) {
  121 + if(map.get("levelCode").equals(levelCode)){
  122 + isChildren = true;
  123 + List mapList = (List) map.get("children");
  124 + if (mapList != null && mapList.size() > 0) {
  125 + getRoleList(mapList,levelCode,roleList,isChildren);
  126 + }
  127 + break;
  128 + } else {
  129 + List mapList = (List) map.get("children");
  130 + if (mapList != null && mapList.size() > 0) {
  131 + getRoleList(mapList,levelCode,roleList,isChildren);
  132 + }
  133 + }
  134 + }
  135 + }
  136 + } catch (Exception e) {
  137 + logger.error("error",e);
  138 + }
  139 + }
  140 +
  141 + public Map<String, Object> objectToMap(Object obj) throws Exception {
  142 + if(obj == null)
  143 + return null;
  144 +
  145 + Map<String, Object> map = new HashMap<>();
  146 +
  147 + BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  148 + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  149 + for (PropertyDescriptor property : propertyDescriptors) {
  150 + String key = property.getName();
  151 + if (key.compareToIgnoreCase("class") == 0) {
  152 + continue;
  153 + }
  154 + Method getter = property.getReadMethod();
  155 + Object value = getter!=null ? getter.invoke(obj) : null;
  156 + map.put(key, value);
  157 + }
  158 +
  159 + return map;
  160 + }
  161 +
  162 + private void ComparatorSysrole(List<HashMap> list) {
  163 + ComparatorSysrole comparator = new ComparatorSysrole();
  164 + Collections.sort(list, comparator);
  165 + for (HashMap map : list) {
  166 + List mapList = (List) map.get("children");
  167 + if (mapList != null && mapList.size() > 0) {
  168 + ComparatorSysrole(mapList);
  169 + }
  170 + }
  171 + }
  172 +
  173 + private class ComparatorSysrole implements Comparator {
  174 + public int compare(Object arg0, Object arg1) {
  175 + HashMap role0 = (HashMap) arg0;
  176 + HashMap role1 = (HashMap) arg1;
  177 +
  178 + // 首先比较父节点 相同比较 子 位序
  179 + Long role0Pid = (Long) (role0.get("upCode") == null ? (long) 0 : role0.get("upCode"));
  180 + Long role1Pid = (Long) (role1.get("upCode") == null ? (long) 0 : role1.get("upCode"));
  181 + int flag = role0Pid.compareTo(role1Pid);
  182 + if (flag == 0) {
  183 + return (Integer.valueOf(role0.get("roleIndex").toString())).compareTo(Integer.valueOf(role1.get(
  184 + "roleIndex").toString()));
  185 + } else {
  186 + return flag;
  187 + }
  188 + }
  189 + }
  190 +
  191 + @Override
  192 + public Map<String, Object> add(Role role) {
  193 + Map<String, Object> rs = new HashMap();
  194 + try{
  195 + SysUser user = SecurityUtils.getCurrentUser();
  196 + Iterator<Role> itRole = user.getRoles().iterator();
  197 + Role ro = new Role();
  198 + while(itRole.hasNext()){//判断是否有下一个
  199 + ro = itRole.next();
  200 + }
  201 + int id = roleRepository.roleMaxId()+1;
  202 + role.setUpCode(ro.getRoleCode());
  203 + role.setLevel(ro.getLevel()+1);
  204 + role.setRoleCode(id);
  205 + role.setId(id);
  206 + return super.save(role);
  207 + }catch (Exception e){
  208 + logger.error("", e);
  209 + rs.put("status", ResponseCode.ERROR);
  210 + rs.put("msg", e.getMessage());
  211 + }
  212 + return rs;
  213 + }
  214 +
  215 + @Override
  216 + public Map<String, Object> save(Role t) {
  217 + if (t.getId() != null) {
  218 + // 更新
  219 + Map<String, Object> map = new HashMap<>();
  220 + try {
  221 + roleRepository.update(t.getCodeName(), t.getRoleName(),
  222 + t.isEnable(), t.getDescriptions(), t.getId());
  223 + map.put("status", ResponseCode.SUCCESS);
  224 + } catch (Exception e) {
  225 + map.put("status", ResponseCode.ERROR);
  226 + }
  227 + return map;
  228 + }
  229 + return super.save(t);
  230 + }
  231 +
  232 + @Override
  233 + public Map<String, Object> settRoleModules(Integer roleId, String mIds) {
  234 +
  235 + Map<String, Object> map = new HashMap<>();
  236 + try {
  237 + Role role = roleRepository.findOne(roleId);
  238 +
  239 + List<Integer> idList = new ArrayList<>();
  240 + String[] array = mIds.split(",");
  241 + for (String id : array) {
  242 + if (null == id || id.trim().equals(""))
  243 + continue;
  244 + idList.add(Integer.parseInt(id));
  245 + }
  246 +
  247 + Set<Module> mList = moduleRepository.findByIds(idList);
  248 + role.setModules(mList);
  249 + roleRepository.save(role);
  250 + map.put("status", ResponseCode.SUCCESS);
  251 + } catch (Exception e) {
  252 + logger.error("", e);
  253 + map.put("status", ResponseCode.ERROR);
  254 + }
  255 + return map;
  256 + }
  257 +
  258 + @Override
  259 + public Map<String, Object> roleInfo(Integer id) {
  260 + Map<String, Object> map = new HashMap<>();
  261 + Role role = roleRepository.findOne(id);
  262 + map.put("codeName", role.getCodeName());
  263 + map.put("roleName", role.getRoleName());
  264 + map.put("createDate", sdfMinute.format(role.getCreateDate()));
  265 + map.put("updateDate", sdfMinute.format(role.getUpdateDate()));
  266 + map.put("enable", role.isEnable()==true?1:0);
  267 + map.put("descriptions", role.getDescriptions());
  268 + map.put("modules", role.getModules().size());
  269 + map.put("resources", role.getResources().size());
  270 + String userNames = "";
  271 + Set<SysUser> users = role.getUsers();
  272 + if(!users.isEmpty()){
  273 + Iterator<SysUser> it = users.iterator();
  274 + while(it.hasNext()){
  275 + SysUser user = it.next();
  276 + userNames = user.getUserName()+"...";
  277 + }
  278 + }
  279 + map.put("userNames", userNames);
  280 + return map;
  281 + }
  282 +
  283 + @Override
  284 + public List<Role> findAllByIds(String ids) {
  285 + return roleRepository.findAllById(ids);
  286 + }
  287 +
  288 + @Override
  289 + public boolean checkOperationLegality(Integer operationRoleId){
  290 + boolean isLegality = false;
  291 + Map<String, Object> roleMap = findSubordinate();
  292 + isLegality = (roleMap.get(operationRoleId) == null ? true:false );
  293 + return isLegality;
  294 + }
  295 +}
... ...
src/main/java/com/bsth/service/sys/impl/SysUserServiceImpl.java
1   -package com.bsth.service.sys.impl;
2   -
3   -import com.bsth.common.ResponseCode;
4   -import com.bsth.entity.sys.SysUser;
5   -import com.bsth.repository.sys.SysUserRepository;
6   -import com.bsth.service.impl.BaseServiceImpl;
7   -import com.bsth.service.sys.SysUserService;
8   -import org.slf4j.Logger;
9   -import org.slf4j.LoggerFactory;
10   -import org.springframework.beans.factory.annotation.Autowired;
11   -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
12   -import org.springframework.stereotype.Service;
13   -
14   -import java.util.HashMap;
15   -import java.util.List;
16   -import java.util.Map;
17   -
18   -@Service
19   -public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements SysUserService{
20   -
21   - @Autowired
22   - SysUserRepository sysUserRepository;
23   -
24   - Logger logger = LoggerFactory.getLogger(this.getClass());
25   -
26   - @Override
27   - public SysUser findByUserName(String name) {
28   - return sysUserRepository.findByUserName(name);
29   - }
30   -
31   - @Override
32   - public Map<String, Object> save(SysUser t) {
33   - //
34   - if(t.getPassword() == null || t.getPassword().trim().equals("")){
35   - SysUser user = sysUserRepository.findOne(t.getId());
36   - t.setPassword(user.getPassword());
37   - }else{
38   - t.setPassword(new BCryptPasswordEncoder(4).encode(t.getPassword()));
39   - }
40   - return super.save(t);
41   - }
42   -
43   - @Override
44   - public int changeEnabled(int id, int enabled) {
45   - sysUserRepository.changeEnabled(id,enabled);
46   - return 0;
47   - }
48   -
49   - @Override
50   - public int changePWD(int id,String newPWD) {
51   - return sysUserRepository.changePWD(id,new BCryptPasswordEncoder(4).encode(newPWD));
52   - }
53   -
54   - @Override
55   - public Map<String, Object> register(SysUser u) {
56   - Map<String, Object> rs = new HashMap();
57   - try{
58   - //检查用户名是否存在
59   - if(findByUserName(u.getUserName()) != null){
60   - rs.put("status", ResponseCode.ERROR);
61   - rs.put("msg", "用户名" + u.getUserName() + "已存在!");
62   - }
63   - else{
64   - u.setPassword(new BCryptPasswordEncoder(4).encode(u.getPassword()));
65   - rs = super.save(u);
66   - }
67   - }catch (Exception e){
68   - logger.error("", e);
69   - rs.put("status", ResponseCode.ERROR);
70   - rs.put("msg", e.getMessage());
71   - }
72   - return rs;
73   - }
74   -
75   - @Override
76   - public List<SysUser> findAll_distinct() {
77   - return sysUserRepository.findAll_distinct();
78   - }
79   -}
  1 +package com.bsth.service.sys.impl;
  2 +
  3 +import com.bsth.common.ResponseCode;
  4 +import com.bsth.controller.sys.util.RSAUtils;
  5 +import com.bsth.email.entity.EmailBean;
  6 +import com.bsth.entity.sys.Role;
  7 +import com.bsth.entity.sys.SysUser;
  8 +import com.bsth.repository.sys.SysUserRepository;
  9 +import com.bsth.security.util.SecurityUtils;
  10 +import com.bsth.service.impl.BaseServiceImpl;
  11 +import com.bsth.service.sys.RoleService;
  12 +import com.bsth.service.sys.SysUserService;
  13 +import com.bsth.util.IpUtils;
  14 +import com.bsth.util.MailUtils;
  15 +import com.google.gson.Gson;
  16 +import com.google.gson.reflect.TypeToken;
  17 +import org.joda.time.DateTime;
  18 +import org.joda.time.Days;
  19 +import org.slf4j.Logger;
  20 +import org.slf4j.LoggerFactory;
  21 +import org.springframework.beans.factory.annotation.Autowired;
  22 +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  23 +import org.springframework.stereotype.Service;
  24 +import org.springframework.transaction.annotation.Transactional;
  25 +
  26 +import java.util.ArrayList;
  27 +import java.util.HashMap;
  28 +import java.util.Iterator;
  29 +import java.util.List;
  30 +import java.util.Map;
  31 +
  32 +@Service
  33 +public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements SysUserService{
  34 +
  35 + @Autowired
  36 + SysUserRepository sysUserRepository;
  37 +
  38 + @Autowired
  39 + RoleService roleService;
  40 +
  41 + // 发送邮件
  42 + @Autowired
  43 + private MailUtils mailUtils;
  44 +
  45 + Logger logger = LoggerFactory.getLogger(this.getClass());
  46 +
  47 + @Override
  48 + public SysUser findByUserName(String name) {
  49 + return sysUserRepository.findByUserName(name);
  50 + }
  51 +
  52 + @Override
  53 + public Map<String, Object> save(SysUser t) {
  54 + //
  55 + if(t.getPassword() == null || t.getPassword().trim().equals("")){
  56 + SysUser user = sysUserRepository.findOne(t.getId());
  57 + t.setPassword(user.getPassword());
  58 + }else{
  59 + t.setPassword(new BCryptPasswordEncoder(4).encode(t.getPassword()));
  60 + }
  61 + return super.save(t);
  62 + }
  63 +
  64 + @Override
  65 + public int changeEnabled(int id, int enabled) {
  66 + sysUserRepository.changeEnabled(id,enabled);
  67 + return 0;
  68 + }
  69 +
  70 + @Override
  71 + public int changePWD(int id,String newPWD) {
  72 + return sysUserRepository.changePWD(id,new BCryptPasswordEncoder(4).encode(newPWD));
  73 + }
  74 +
  75 + @Override
  76 + public boolean validPWDExpired(String userName) {
  77 + SysUser sysUser = this.sysUserRepository.findByUserName(userName);
  78 + if (sysUser == null) {
  79 + throw new RuntimeException("用户[" + userName + "]不存在!");
  80 + }
  81 + if (sysUser.getPwdValidPeriod() == null || sysUser.getLastPwdDate() == null) {
  82 + // 如果没有设定密码过期时间,判定为不过期
  83 + return true;
  84 + }
  85 + DateTime now = new DateTime();
  86 + DateTime lastPwdDate = new DateTime(sysUser.getLastPwdDate());
  87 + Integer now_period_days = Days.daysBetween(lastPwdDate, now).getDays();
  88 + Integer expiredTipDays = 3; // 密码过期提前提示天数
  89 + if (now_period_days < (sysUser.getPwdValidPeriod() - expiredTipDays)) {
  90 + return true;
  91 + } else if (now_period_days >= (sysUser.getPwdValidPeriod() - expiredTipDays) &&
  92 + now_period_days < sysUser.getPwdValidPeriod()) {
  93 + // 快过期前提示
  94 + throw new RuntimeException("当前用户密码还有[" + (sysUser.getPwdValidPeriod() - now_period_days) + "]天过期!");
  95 + } else {
  96 + throw new RuntimeException("当前用户密码已过期!");
  97 + }
  98 +
  99 + }
  100 +
  101 + @Override
  102 + public Map<String, Object> register(SysUser u) {
  103 + Map<String, Object> rs = new HashMap();
  104 + boolean isLegality = false;
  105 + Iterator<Role> itRole = u.getRoles().iterator();
  106 + Role ro = new Role();
  107 + while(itRole.hasNext()){//判断是否有下一个
  108 + ro = itRole.next();
  109 + if(roleService.checkOperationLegality(ro.getId())){
  110 + isLegality = true;
  111 + } else {
  112 + rs.put("status", ResponseCode.ERROR);
  113 + rs.put("msg", "用户权限不够,请联系管理员!");
  114 + return rs;
  115 + }
  116 + }
  117 + if(isLegality){
  118 + try{
  119 + //解密RSA
  120 + try{
  121 + u.setUserName(RSAUtils.decryptBase64(u.getUserName()));
  122 + u.setPassword(RSAUtils.decryptBase64(u.getPassword()));
  123 + }catch (RuntimeException e) {
  124 + rs.put("msg", "网络延迟,解密失败,请重新添加!");
  125 + }
  126 + //检查用户名是否存在
  127 + if(findByUserName(u.getUserName()) != null){
  128 + rs.put("status", ResponseCode.ERROR);
  129 + rs.put("msg", "用户名" + u.getUserName() + "已存在!");
  130 + }
  131 + else{
  132 + u.setPassword(new BCryptPasswordEncoder(4).encode(u.getPassword()));
  133 + rs = super.save(u);
  134 + }
  135 + }catch (Exception e){
  136 + logger.error("", e);
  137 + rs.put("status", ResponseCode.ERROR);
  138 + rs.put("msg", e.getMessage());
  139 + }
  140 + }else {
  141 + rs.put("status", ResponseCode.ERROR);
  142 + rs.put("msg", "用户权限不够,请联系管理员!");
  143 + }
  144 + return rs;
  145 + }
  146 +
  147 + @Override
  148 + public List<SysUser> findAll_distinct() {
  149 + Map<String, Object> map = roleService.findSubordinate();
  150 + Object object = roleService.findSubordinate().get("list");
  151 + List<SysUser> rsList = new ArrayList<>();
  152 +
  153 + // 有权限查看的角色
  154 +// List<Role> roleList = JSONArray.parseArray(map.get("list").toString(), Role.class);
  155 +
  156 + try{
  157 + Gson gson = new Gson();
  158 + // 有权限查看的角色
  159 + List<Role> roleList = gson.fromJson(map.get("list").toString(), new TypeToken<List<Role>>(){}.getType());
  160 +
  161 + if(roleList.size() != 0 && !roleList.isEmpty()){
  162 + // 遍历有权限查看的角色
  163 + Map<Integer,Role> roleMap = new HashMap<>();
  164 + for (Role role: roleList) {
  165 + roleMap.put(role.getId(),role);
  166 + }
  167 +
  168 + List<SysUser> list = new ArrayList<>();
  169 + list = sysUserRepository.findAll_distinct();
  170 + for (SysUser sysUsers:list) {
  171 +
  172 + Iterator<Role> itUser = sysUsers.getRoles().iterator();
  173 + Role roleUser = new Role();
  174 + while(itUser.hasNext()){//判断是否有下一个
  175 + roleUser = itUser.next();
  176 + }
  177 + // 添加权限内的用户
  178 + if(roleMap.get(roleUser.getId()) != null){
  179 + rsList.add(sysUsers);
  180 + }
  181 + }
  182 + }
  183 + } catch (Exception e){
  184 + logger.error("error", e);
  185 + }
  186 + return rsList;
  187 + }
  188 +
  189 + @Override
  190 + @Transactional
  191 + public Map<String, Object> resetPassword(Integer id, Integer pwdValidPeriod){
  192 + Map<String, Object> rs = new HashMap();
  193 + try{
  194 + // 获取当前用户
  195 + SysUser user = SecurityUtils.getCurrentUser();
  196 + Iterator<Role> itRole = user.getRoles().iterator();
  197 + Role ro = new Role();
  198 + boolean Legality = false;
  199 + while(itRole.hasNext()){//判断是否有下一个
  200 + ro = itRole.next();
  201 + if(ro.getLevel() == 1)
  202 + Legality = true;
  203 + }
  204 + if(Legality){
  205 + String pwd = PwdGenerator.randomPassword(16);
  206 + user = sysUserRepository.findOne(id);
  207 + user.setPwdValidPeriod(pwdValidPeriod);
  208 + sysUserRepository.save(user);
  209 + sysUserRepository.changePWD(id, new BCryptPasswordEncoder(4).encode(pwd));
  210 + //发送邮件
  211 + EmailBean mail = new EmailBean();
  212 + mail.setSubject(IpUtils.getLocalIpAddress() +":密码重置");
  213 + mail.setContent(pwd);
  214 + mailUtils.sendMail(mail);
  215 + logger.info("setLD-sendMail:邮件发送成功!");
  216 + rs.put("status", ResponseCode.SUCCESS);
  217 + rs.put("msg", "密码重置成功!");
  218 + }else {
  219 + rs.put("status", ResponseCode.ERROR);
  220 + rs.put("msg", "您不是管理员无权限重置其他用户密码");
  221 + }
  222 + }catch (Exception e){
  223 + logger.error("", e);
  224 + rs.put("status", ResponseCode.ERROR);
  225 + rs.put("msg", e.getMessage());
  226 + }
  227 + return rs;
  228 + }
  229 +
  230 + @Override
  231 + @Transactional(rollbackFor = Exception.class)
  232 + public void recordLoginDate(String userName) {
  233 + sysUserRepository.recordLoginDate(userName);
  234 + }
  235 +
  236 + @Override
  237 + @Transactional(rollbackFor = Exception.class)
  238 + public void realName(String jobCode, String realName, int id) {
  239 + sysUserRepository.realName(jobCode, realName, id);
  240 + }
  241 +}
... ...
src/main/java/com/bsth/util/IpUtils.java
... ... @@ -12,17 +12,11 @@ public class IpUtils {
12 12 if (request == null) {
13 13 return "unknown";
14 14 }
15   - String ip = request.getHeader("x-forwarded-for");
16   - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
17   - ip = request.getHeader("Proxy-Client-IP");
18   - }
  15 + String ip = null;
19 16 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
20 17 ip = request.getHeader("X-Forwarded-For");
21 18 }
22 19 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
23   - ip = request.getHeader("WL-Proxy-Client-IP");
24   - }
25   - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
26 20 ip = request.getHeader("X-Real-IP");
27 21 }
28 22 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
... ...
src/main/java/com/bsth/util/MailUtils.java 0 → 100644
  1 +package com.bsth.util;
  2 +
  3 +import com.bsth.data.SystemParamCache;
  4 +import com.bsth.email.SimpleMailSender;
  5 +import com.bsth.email.entity.EmailBean;
  6 +import org.springframework.stereotype.Component;
  7 +
  8 +import java.util.List;
  9 +
  10 +/**
  11 + * @author Hill
  12 + */
  13 +@Component
  14 +public class MailUtils {
  15 +
  16 + private Tools tools = new Tools("mailbox.properties");
  17 +
  18 + private SimpleMailSender sms = new SimpleMailSender(tools.getValue("username"),tools.getValue("password"));
  19 +
  20 + /**
  21 + * recipients
  22 + * 收件人集合
  23 + * mail
  24 + * 邮件
  25 + */
  26 + public int sendMail(List<String> recipients, EmailBean mail){
  27 + try {
  28 + for (String recipient : recipients) {
  29 + sms.send(recipient, mail.getSubject(),mail.getContent());
  30 + }
  31 + } catch (Exception e) {
  32 + e.printStackTrace();
  33 + return -1;
  34 + }
  35 + return 1;
  36 + }
  37 +
  38 + /**
  39 + * recipient
  40 + * 收件人
  41 + * mail
  42 + * 邮件
  43 + */
  44 + public int sendMail(String recipient, EmailBean mail){
  45 + try {
  46 + sms.send(recipient, mail.getSubject(), mail.getContent());
  47 + } catch (Exception e) {
  48 + e.printStackTrace();
  49 + return -1;
  50 + }
  51 + return 1;
  52 + }
  53 +
  54 + public int sendMail(EmailBean mail){
  55 + return sendMail(SystemParamCache.getMailAdmin(), mail);
  56 + }
  57 +}
0 58 \ No newline at end of file
... ...