作者 朱兆平

修改权限信息后可以刷新缓存形式更新redis权限

1 package com.tianbo.warehouse.controller; 1 package com.tianbo.warehouse.controller;
2 2
  3 +import com.alibaba.fastjson.JSON;
3 import com.github.pagehelper.PageInfo; 4 import com.github.pagehelper.PageInfo;
4 import com.tianbo.warehouse.annotation.LogAnnotation; 5 import com.tianbo.warehouse.annotation.LogAnnotation;
5 import com.tianbo.warehouse.annotation.RequestRequire; 6 import com.tianbo.warehouse.annotation.RequestRequire;
@@ -7,7 +8,10 @@ import com.tianbo.warehouse.annotation.UserPasswordMd5; @@ -7,7 +8,10 @@ import com.tianbo.warehouse.annotation.UserPasswordMd5;
7 import com.tianbo.warehouse.controller.response.ResultJson; 8 import com.tianbo.warehouse.controller.response.ResultJson;
8 import com.tianbo.warehouse.model.USERS; 9 import com.tianbo.warehouse.model.USERS;
9 import com.tianbo.warehouse.model.UserRole; 10 import com.tianbo.warehouse.model.UserRole;
  11 +import com.tianbo.warehouse.security.CustomUserDetailService;
  12 +import com.tianbo.warehouse.security.filter.JwtTokenUtil;
10 import com.tianbo.warehouse.service.UserService; 13 import com.tianbo.warehouse.service.UserService;
  14 +import com.tianbo.warehouse.util.RedisUtils;
11 import io.swagger.annotations.Api; 15 import io.swagger.annotations.Api;
12 import io.swagger.annotations.ApiImplicitParam; 16 import io.swagger.annotations.ApiImplicitParam;
13 import io.swagger.annotations.ApiImplicitParams; 17 import io.swagger.annotations.ApiImplicitParams;
@@ -32,6 +36,12 @@ public class UserController { @@ -32,6 +36,12 @@ public class UserController {
32 @Autowired 36 @Autowired
33 UserService userService; 37 UserService userService;
34 38
  39 + @Autowired
  40 + CustomUserDetailService userDetailService;
  41 +
  42 + @Autowired
  43 + RedisUtils redisUtils;
  44 +
35 @ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息") 45 @ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息")
36 @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"), 46 @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"),
37 @ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")}) 47 @ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")})
@@ -95,20 +105,43 @@ public class UserController { @@ -95,20 +105,43 @@ public class UserController {
95 int i = userService.deleteByPrimaryKey(user.getUserId()); 105 int i = userService.deleteByPrimaryKey(user.getUserId());
96 ResultJson resultJson = new ResultJson(); 106 ResultJson resultJson = new ResultJson();
97 return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild"); 107 return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild");
98 -  
99 } 108 }
100 109
101 @PutMapping("/roleset") 110 @PutMapping("/roleset")
102 - public ResultJson roleSet(@RequestBody Map<String,Object> map){ 111 + public ResultJson roleSet(@RequestBody Map<String,Object> map,HttpServletRequest request,HttpServletResponse respons){
103 Integer id = (Integer) map.get("userId"); 112 Integer id = (Integer) map.get("userId");
104 List<Integer> roles = (List<Integer>) map.get("roleIds"); 113 List<Integer> roles = (List<Integer>) map.get("roleIds");
105 UserRole userRole = new UserRole(); 114 UserRole userRole = new UserRole();
106 userRole.setUserId(id); 115 userRole.setUserId(id);
107 userRole.setRoleIds(roles); 116 userRole.setRoleIds(roles);
108 int i = userService.setUserRole(userRole); 117 int i = userService.setUserRole(userRole);
109 -  
110 return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败"); 118 return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
111 -  
112 } 119 }
113 120
  121 + /**
  122 + * 刷新redis权限缓存
  123 + */
  124 + @ApiOperation(value = "更新用户权限缓存", notes = "重新生成用户的信息到redis")
  125 + @PutMapping("/resetToken")
  126 + public ResultJson resetToken(HttpServletRequest request,HttpServletResponse respons) {
  127 + /**
  128 + * 更新目标用户的权限缓存
  129 + */
  130 + String authHeader = request.getHeader("Authorization");
  131 + if (authHeader != null && authHeader.startsWith("Bearer ")) {
  132 + final String authToken = authHeader.substring("Bearer ".length());
  133 +
  134 + String username = JwtTokenUtil.parseToken(authToken);
  135 + //有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录
  136 + if (username != null) {
  137 + UserDetails userDetails = userDetailService.loadUserByUsername(username);
  138 + if (userDetails != null) {
  139 + String json = JSON.toJSONString(userDetails);
  140 + redisUtils.set(authToken, json);
  141 + return new ResultJson("200","缓存更新成功");
  142 + }
  143 + }
  144 + }
  145 + return new ResultJson("500","缓存更新失败");
  146 + }
114 } 147 }
@@ -21,4 +21,5 @@ public interface USERSMapper { @@ -21,4 +21,5 @@ public interface USERSMapper {
21 List<USERS> selectByUsername(String userName); 21 List<USERS> selectByUsername(String userName);
22 22
23 List<USERS> selectAllUser(USERS users); 23 List<USERS> selectAllUser(USERS users);
  24 +
24 } 25 }
@@ -34,6 +34,8 @@ public class ROLE implements GrantedAuthority { @@ -34,6 +34,8 @@ public class ROLE implements GrantedAuthority {
34 34
35 private String departmentid; 35 private String departmentid;
36 36
  37 + private String mqcode;
  38 +
37 private List<ROLE> children; 39 private List<ROLE> children;
38 40
39 41
@@ -56,6 +56,10 @@ public class USERS implements UserDetails { @@ -56,6 +56,10 @@ public class USERS implements UserDetails {
56 56
57 private String token; 57 private String token;
58 58
  59 + private Integer companyId;
  60 +
  61 + private ROLE companyInfo;
  62 +
59 @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty}) 63 @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
60 private List<ROLE> roles; 64 private List<ROLE> roles;
61 65
@@ -200,6 +204,22 @@ public class USERS implements UserDetails { @@ -200,6 +204,22 @@ public class USERS implements UserDetails {
200 this.token = token; 204 this.token = token;
201 } 205 }
202 206
  207 + public Integer getCompanyId() {
  208 + return companyId;
  209 + }
  210 +
  211 + public void setCompanyId(Integer companyId) {
  212 + this.companyId = companyId;
  213 + }
  214 +
  215 + public ROLE getCompanyInfo() {
  216 + return companyInfo;
  217 + }
  218 +
  219 + public void setCompanyInfo(ROLE companyInfo) {
  220 + this.companyInfo = companyInfo;
  221 + }
  222 +
203 /** 223 /**
204 * 224 *
205 * @return 账户未过期 225 * @return 账户未过期
@@ -233,8 +253,11 @@ public class USERS implements UserDetails { @@ -233,8 +253,11 @@ public class USERS implements UserDetails {
233 */ 253 */
234 @Override 254 @Override
235 public boolean isEnabled(){ 255 public boolean isEnabled(){
  256 + if(state!=null && state){
236 return true; 257 return true;
237 } 258 }
  259 + return false;
  260 + }
238 261
239 /** 262 /**
240 * 263 *
@@ -46,17 +46,10 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH @@ -46,17 +46,10 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH
46 public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 46 public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
47 47
48 //返回前端原因 48 //返回前端原因
49 - PrintWriter out = response.getWriter();  
50 - StringBuffer sb = new StringBuffer();  
51 - sb.append("{\"status\":\"error\",\"msg\":\"");  
52 - if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {  
53 - sb.append("用户名或密码输入错误,登录失败!");  
54 - } else if (exception instanceof DisabledException) {  
55 - sb.append("账户被禁用,登录失败,请联系管理员!");  
56 - } else {  
57 - sb.append("登录失败!");  
58 - }  
59 - sb.append("\"}"); 49 +// PrintWriter out = response.getWriter();
  50 +// StringBuffer sb = new StringBuffer();
  51 +// sb.append("{\"status\":\"error\",\"msg\":\"");
  52 +// sb.append("\"}");
60 // out.write(sb.toString()); 53 // out.write(sb.toString());
61 // out.flush(); 54 // out.flush();
62 // out.close(); 55 // out.close();
@@ -72,20 +65,27 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH @@ -72,20 +65,27 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH
72 response.setContentType("application/json;charset=UTF-8"); 65 response.setContentType("application/json;charset=UTF-8");
73 response.getWriter().write(objectMapper.writeValueAsString(exception)); 66 response.getWriter().write(objectMapper.writeValueAsString(exception));
74 } 67 }
75 -  
76 - if (this.defaultFailureUrl == null) {  
77 - this.logger.debug("No failure URL set, sending 401 Unauthorized error");  
78 - response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());  
79 - } else {  
80 - this.saveException(request, exception);  
81 - if (this.forwardToDestination) {  
82 - this.logger.debug("Forwarding to " + this.defaultFailureUrl);  
83 - request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response); 68 + if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
  69 + response.sendError(HttpStatus.UNAUTHORIZED.value(),"用户不存在或者密码错误");
  70 + } else if (exception instanceof DisabledException) {
  71 + response.sendError(HttpStatus.UNAUTHORIZED.value(),"账户被禁用,登录失败,请联系管理员!");
84 } else { 72 } else {
85 - this.logger.debug("Redirecting to " + this.defaultFailureUrl);  
86 - this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);  
87 - } 73 + response.sendError(HttpStatus.UNAUTHORIZED.value(),"登录失败");
88 } 74 }
89 75
  76 +// if (this.defaultFailureUrl == null) {
  77 +// this.logger.debug("No failure URL set, sending 401 Unauthorized error");
  78 +// response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
  79 +// } else {
  80 +// this.saveException(request, exception);
  81 +// if (this.forwardToDestination) {
  82 +// this.logger.debug("Forwarding to " + this.defaultFailureUrl);
  83 +// request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
  84 +// } else {
  85 +// this.logger.debug("Redirecting to " + this.defaultFailureUrl);
  86 +// this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
  87 +// }
  88 +// }
  89 +
90 } 90 }
91 } 91 }
1 package com.tianbo.warehouse.service; 1 package com.tianbo.warehouse.service;
2 2
3 import com.github.pagehelper.PageInfo; 3 import com.github.pagehelper.PageInfo;
  4 +import com.tianbo.warehouse.model.ROLE;
4 import com.tianbo.warehouse.model.USERS; 5 import com.tianbo.warehouse.model.USERS;
5 import com.tianbo.warehouse.model.UserRole; 6 import com.tianbo.warehouse.model.UserRole;
6 7
@@ -18,4 +19,8 @@ public interface UserService { @@ -18,4 +19,8 @@ public interface UserService {
18 int deleteByPrimaryKey(Integer userId); 19 int deleteByPrimaryKey(Integer userId);
19 20
20 int setUserRole(UserRole userRole); 21 int setUserRole(UserRole userRole);
  22 +
  23 + ROLE getUserCompany(Integer company_id);
  24 +
  25 + USERS selectByUserId(Integer userid);
21 } 26 }
@@ -16,13 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired; @@ -16,13 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.stereotype.Service; 16 import org.springframework.stereotype.Service;
17 import org.springframework.transaction.annotation.Transactional; 17 import org.springframework.transaction.annotation.Transactional;
18 18
  19 +import javax.annotation.Resource;
19 import java.util.List; 20 import java.util.List;
20 import java.util.Random; 21 import java.util.Random;
21 22
22 @Service(value = "userService") 23 @Service(value = "userService")
23 public class UserServiceImpl implements UserService{ 24 public class UserServiceImpl implements UserService{
24 25
25 - @Autowired 26 + @Resource
26 private USERSMapper usersMapper; 27 private USERSMapper usersMapper;
27 28
28 @Autowired 29 @Autowired
@@ -120,6 +121,10 @@ public class UserServiceImpl implements UserService{ @@ -120,6 +121,10 @@ public class UserServiceImpl implements UserService{
120 userRoleMapper.insertSelective(ur); 121 userRoleMapper.insertSelective(ur);
121 } 122 }
122 } 123 }
  124 + /**
  125 + * 重写redis用户权限等相关资料
  126 + */
  127 +
123 return 1; 128 return 1;
124 }catch (Exception e){ 129 }catch (Exception e){
125 e.printStackTrace(); 130 e.printStackTrace();
@@ -128,4 +133,19 @@ public class UserServiceImpl implements UserService{ @@ -128,4 +133,19 @@ public class UserServiceImpl implements UserService{
128 133
129 } 134 }
130 135
  136 + /**
  137 + * 获取用户所属公司信息
  138 + * @param company_id 所属公司id
  139 + * @return
  140 + */
  141 + @Override
  142 + public ROLE getUserCompany(Integer company_id){
  143 + return new ROLE();
  144 + }
  145 +
  146 + @Override
  147 + public USERS selectByUserId(Integer userid){
  148 + return usersMapper.selectByPrimaryKey(userid);
  149 + }
  150 +
131 } 151 }
@@ -12,12 +12,13 @@ @@ -12,12 +12,13 @@
12 <result column="customs_reg_code" jdbcType="VARCHAR" property="customsRegCode" /> 12 <result column="customs_reg_code" jdbcType="VARCHAR" property="customsRegCode" />
13 <result column="business_license" jdbcType="VARCHAR" property="businessLicense" /> 13 <result column="business_license" jdbcType="VARCHAR" property="businessLicense" />
14 <result column="departmentId" jdbcType="VARCHAR" property="departmentid" /> 14 <result column="departmentId" jdbcType="VARCHAR" property="departmentid" />
  15 + <result column="mq_code" jdbcType="VARCHAR" property="mqcode" />
15 <collection column="role_id" javaType="java.util.ArrayList" ofType="com.tianbo.warehouse.model.PERMISSION" property="permissions" select="com.tianbo.warehouse.dao.PERMISSIONMapper.getRolePermisson" /> 16 <collection column="role_id" javaType="java.util.ArrayList" ofType="com.tianbo.warehouse.model.PERMISSION" property="permissions" select="com.tianbo.warehouse.dao.PERMISSIONMapper.getRolePermisson" />
16 <collection column="role_id" property="children" select="selectByParentId" /> 17 <collection column="role_id" property="children" select="selectByParentId" />
17 </resultMap> 18 </resultMap>
18 <sql id="Base_Column_List"> 19 <sql id="Base_Column_List">
19 role_id, role_name, role_sign, description, type, parentId, rsort, customs_reg_code, 20 role_id, role_name, role_sign, description, type, parentId, rsort, customs_reg_code,
20 - business_license, departmentId 21 + business_license, departmentId, mq_code
21 </sql> 22 </sql>
22 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> 23 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
23 select 24 select
@@ -39,11 +40,11 @@ @@ -39,11 +40,11 @@
39 insert into role (role_id, role_name, role_sign, 40 insert into role (role_id, role_name, role_sign,
40 description, type, parentId, 41 description, type, parentId,
41 rsort, customs_reg_code, business_license, 42 rsort, customs_reg_code, business_license,
42 - departmentId) 43 + departmentId, mq_code)
43 values (#{roleId,jdbcType=INTEGER}, #{roleName,jdbcType=VARCHAR}, #{roleSign,jdbcType=VARCHAR}, 44 values (#{roleId,jdbcType=INTEGER}, #{roleName,jdbcType=VARCHAR}, #{roleSign,jdbcType=VARCHAR},
44 #{description,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{parentid,jdbcType=INTEGER}, 45 #{description,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{parentid,jdbcType=INTEGER},
45 #{rsort,jdbcType=INTEGER}, #{customsRegCode,jdbcType=VARCHAR}, #{businessLicense,jdbcType=VARCHAR}, 46 #{rsort,jdbcType=INTEGER}, #{customsRegCode,jdbcType=VARCHAR}, #{businessLicense,jdbcType=VARCHAR},
46 - #{departmentid,jdbcType=VARCHAR}) 47 + #{departmentid,jdbcType=VARCHAR},#{mqcode,jdbcType=VARCHAR})
47 </insert> 48 </insert>
48 <insert id="insertSelective" parameterType="com.tianbo.warehouse.model.ROLE"> 49 <insert id="insertSelective" parameterType="com.tianbo.warehouse.model.ROLE">
49 insert into role 50 insert into role
@@ -78,6 +79,9 @@ @@ -78,6 +79,9 @@
78 <if test="departmentid != null"> 79 <if test="departmentid != null">
79 departmentId, 80 departmentId,
80 </if> 81 </if>
  82 + <if test="mqcode != null">
  83 + mq_code,
  84 + </if>
81 </trim> 85 </trim>
82 <trim prefix="values (" suffix=")" suffixOverrides=","> 86 <trim prefix="values (" suffix=")" suffixOverrides=",">
83 <if test="roleId != null"> 87 <if test="roleId != null">
@@ -110,6 +114,9 @@ @@ -110,6 +114,9 @@
110 <if test="departmentid != null"> 114 <if test="departmentid != null">
111 #{departmentid,jdbcType=VARCHAR}, 115 #{departmentid,jdbcType=VARCHAR},
112 </if> 116 </if>
  117 + <if test="mqcode != null">
  118 + #{mqcode,jdbcType=VARCHAR},
  119 + </if>
113 </trim> 120 </trim>
114 </insert> 121 </insert>
115 <update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.ROLE"> 122 <update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.ROLE">
@@ -142,6 +149,9 @@ @@ -142,6 +149,9 @@
142 <if test="departmentid != null"> 149 <if test="departmentid != null">
143 departmentId = #{departmentid,jdbcType=VARCHAR}, 150 departmentId = #{departmentid,jdbcType=VARCHAR},
144 </if> 151 </if>
  152 + <if test="mqcode != null">
  153 + mq_code = #{mqcode,jdbcType=VARCHAR},
  154 + </if>
145 </set> 155 </set>
146 where role_id = #{roleId,jdbcType=INTEGER} 156 where role_id = #{roleId,jdbcType=INTEGER}
147 </update> 157 </update>
@@ -155,7 +165,8 @@ @@ -155,7 +165,8 @@
155 rsort = #{rsort,jdbcType=INTEGER}, 165 rsort = #{rsort,jdbcType=INTEGER},
156 customs_reg_code = #{customsRegCode,jdbcType=VARCHAR}, 166 customs_reg_code = #{customsRegCode,jdbcType=VARCHAR},
157 business_license = #{businessLicense,jdbcType=VARCHAR}, 167 business_license = #{businessLicense,jdbcType=VARCHAR},
158 - departmentId = #{departmentid,jdbcType=VARCHAR} 168 + departmentId = #{departmentid,jdbcType=VARCHAR},
  169 + mq_code = #{mqcode,jdbcType=VARCHAR},
159 where role_id = #{roleId,jdbcType=INTEGER} 170 where role_id = #{roleId,jdbcType=INTEGER}
160 </update> 171 </update>
161 172
@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 <result column="realName" property="realname" jdbcType="VARCHAR" /> 16 <result column="realName" property="realname" jdbcType="VARCHAR" />
17 <result column="email" property="email" jdbcType="VARCHAR" /> 17 <result column="email" property="email" jdbcType="VARCHAR" />
18 <result column="age" property="age" jdbcType="INTEGER" /> 18 <result column="age" property="age" jdbcType="INTEGER" />
  19 + <result column="company_id" property="companyId" jdbcType="INTEGER" />
19 </resultMap> 20 </resultMap>
20 <resultMap id="SecurityResult" type="com.tianbo.warehouse.model.USERS"> 21 <resultMap id="SecurityResult" type="com.tianbo.warehouse.model.USERS">
21 <id column="user_id" property="userId" jdbcType="INTEGER" /> 22 <id column="user_id" property="userId" jdbcType="INTEGER" />
@@ -29,10 +30,11 @@ @@ -29,10 +30,11 @@
29 <result column="realName" property="realname" jdbcType="VARCHAR" /> 30 <result column="realName" property="realname" jdbcType="VARCHAR" />
30 <result column="email" property="email" jdbcType="VARCHAR" /> 31 <result column="email" property="email" jdbcType="VARCHAR" />
31 <result column="age" property="age" jdbcType="INTEGER" /> 32 <result column="age" property="age" jdbcType="INTEGER" />
  33 + <result column="company_id" property="companyId" jdbcType="INTEGER" />
32 </resultMap> 34 </resultMap>
33 <sql id="Base_Column_List" > 35 <sql id="Base_Column_List" >
34 user_id, username, password, birthday, sex, address, state, mobilePhone, creatTime, 36 user_id, username, password, birthday, sex, address, state, mobilePhone, creatTime,
35 - updateTime, userFace, realName, email, age 37 + updateTime, userFace, realName, email, age,company_id
36 </sql> 38 </sql>
37 <sql id="user_List" > 39 <sql id="user_List" >
38 user_id, username, birthday, sex, address, state, mobilePhone,userFace, realName, email, age 40 user_id, username, birthday, sex, address, state, mobilePhone,userFace, realName, email, age
@@ -51,7 +53,7 @@ @@ -51,7 +53,7 @@
51 </select> 53 </select>
52 <select id="selectAllUser" resultMap="BaseResultMap" parameterType="com.tianbo.warehouse.model.USERS" > 54 <select id="selectAllUser" resultMap="BaseResultMap" parameterType="com.tianbo.warehouse.model.USERS" >
53 select 55 select
54 - * 56 + <include refid="Base_Column_List" />
55 from users 57 from users
56 WHERE 1=1 58 WHERE 1=1
57 <if test=" username != null" > 59 <if test=" username != null" >