作者 朱兆平

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

package com.tianbo.warehouse.controller;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.annotation.LogAnnotation;
import com.tianbo.warehouse.annotation.RequestRequire;
... ... @@ -7,7 +8,10 @@ import com.tianbo.warehouse.annotation.UserPasswordMd5;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.model.UserRole;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.security.filter.JwtTokenUtil;
import com.tianbo.warehouse.service.UserService;
import com.tianbo.warehouse.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
... ... @@ -32,6 +36,12 @@ public class UserController {
@Autowired
UserService userService;
@Autowired
CustomUserDetailService userDetailService;
@Autowired
RedisUtils redisUtils;
@ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息")
@ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"),
@ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")})
... ... @@ -95,20 +105,43 @@ public class UserController {
int i = userService.deleteByPrimaryKey(user.getUserId());
ResultJson resultJson = new ResultJson();
return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild");
}
@PutMapping("/roleset")
public ResultJson roleSet(@RequestBody Map<String,Object> map){
public ResultJson roleSet(@RequestBody Map<String,Object> map,HttpServletRequest request,HttpServletResponse respons){
Integer id = (Integer) map.get("userId");
List<Integer> roles = (List<Integer>) map.get("roleIds");
UserRole userRole = new UserRole();
userRole.setUserId(id);
userRole.setRoleIds(roles);
int i = userService.setUserRole(userRole);
return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
int i = userService.setUserRole(userRole);
return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
}
/**
* 刷新redis权限缓存
*/
@ApiOperation(value = "更新用户权限缓存", notes = "重新生成用户的信息到redis")
@PutMapping("/resetToken")
public ResultJson resetToken(HttpServletRequest request,HttpServletResponse respons) {
/**
* 更新目标用户的权限缓存
*/
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
final String authToken = authHeader.substring("Bearer ".length());
String username = JwtTokenUtil.parseToken(authToken);
//有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录
if (username != null) {
UserDetails userDetails = userDetailService.loadUserByUsername(username);
if (userDetails != null) {
String json = JSON.toJSONString(userDetails);
redisUtils.set(authToken, json);
return new ResultJson("200","缓存更新成功");
}
}
}
return new ResultJson("500","缓存更新失败");
}
}
... ...
... ... @@ -21,4 +21,5 @@ public interface USERSMapper {
List<USERS> selectByUsername(String userName);
List<USERS> selectAllUser(USERS users);
}
\ No newline at end of file
... ...
... ... @@ -34,6 +34,8 @@ public class ROLE implements GrantedAuthority {
private String departmentid;
private String mqcode;
private List<ROLE> children;
... ...
... ... @@ -56,6 +56,10 @@ public class USERS implements UserDetails {
private String token;
private Integer companyId;
private ROLE companyInfo;
@JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
private List<ROLE> roles;
... ... @@ -200,6 +204,22 @@ public class USERS implements UserDetails {
this.token = token;
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public ROLE getCompanyInfo() {
return companyInfo;
}
public void setCompanyInfo(ROLE companyInfo) {
this.companyInfo = companyInfo;
}
/**
*
* @return 账户未过期
... ... @@ -233,7 +253,10 @@ public class USERS implements UserDetails {
*/
@Override
public boolean isEnabled(){
return true;
if(state!=null && state){
return true;
}
return false;
}
/**
... ...
... ... @@ -46,17 +46,10 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//返回前端原因
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer();
sb.append("{\"status\":\"error\",\"msg\":\"");
if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
sb.append("用户名或密码输入错误,登录失败!");
} else if (exception instanceof DisabledException) {
sb.append("账户被禁用,登录失败,请联系管理员!");
} else {
sb.append("登录失败!");
}
sb.append("\"}");
// PrintWriter out = response.getWriter();
// StringBuffer sb = new StringBuffer();
// sb.append("{\"status\":\"error\",\"msg\":\"");
// sb.append("\"}");
// out.write(sb.toString());
// out.flush();
// out.close();
... ... @@ -72,20 +65,27 @@ public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureH
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(exception));
}
if (this.defaultFailureUrl == null) {
this.logger.debug("No failure URL set, sending 401 Unauthorized error");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
response.sendError(HttpStatus.UNAUTHORIZED.value(),"用户不存在或者密码错误");
} else if (exception instanceof DisabledException) {
response.sendError(HttpStatus.UNAUTHORIZED.value(),"账户被禁用,登录失败,请联系管理员!");
} else {
this.saveException(request, exception);
if (this.forwardToDestination) {
this.logger.debug("Forwarding to " + this.defaultFailureUrl);
request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
} else {
this.logger.debug("Redirecting to " + this.defaultFailureUrl);
this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
}
response.sendError(HttpStatus.UNAUTHORIZED.value(),"登录失败");
}
// if (this.defaultFailureUrl == null) {
// this.logger.debug("No failure URL set, sending 401 Unauthorized error");
// response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
// } else {
// this.saveException(request, exception);
// if (this.forwardToDestination) {
// this.logger.debug("Forwarding to " + this.defaultFailureUrl);
// request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
// } else {
// this.logger.debug("Redirecting to " + this.defaultFailureUrl);
// this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
// }
// }
}
}
... ...
package com.tianbo.warehouse.service;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.model.UserRole;
... ... @@ -18,4 +19,8 @@ public interface UserService {
int deleteByPrimaryKey(Integer userId);
int setUserRole(UserRole userRole);
ROLE getUserCompany(Integer company_id);
USERS selectByUserId(Integer userid);
}
... ...
... ... @@ -16,13 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
@Service(value = "userService")
public class UserServiceImpl implements UserService{
@Autowired
@Resource
private USERSMapper usersMapper;
@Autowired
... ... @@ -120,6 +121,10 @@ public class UserServiceImpl implements UserService{
userRoleMapper.insertSelective(ur);
}
}
/**
* 重写redis用户权限等相关资料
*/
return 1;
}catch (Exception e){
e.printStackTrace();
... ... @@ -128,4 +133,19 @@ public class UserServiceImpl implements UserService{
}
/**
* 获取用户所属公司信息
* @param company_id 所属公司id
* @return
*/
@Override
public ROLE getUserCompany(Integer company_id){
return new ROLE();
}
@Override
public USERS selectByUserId(Integer userid){
return usersMapper.selectByPrimaryKey(userid);
}
}
... ...
... ... @@ -12,12 +12,13 @@
<result column="customs_reg_code" jdbcType="VARCHAR" property="customsRegCode" />
<result column="business_license" jdbcType="VARCHAR" property="businessLicense" />
<result column="departmentId" jdbcType="VARCHAR" property="departmentid" />
<result column="mq_code" jdbcType="VARCHAR" property="mqcode" />
<collection column="role_id" javaType="java.util.ArrayList" ofType="com.tianbo.warehouse.model.PERMISSION" property="permissions" select="com.tianbo.warehouse.dao.PERMISSIONMapper.getRolePermisson" />
<collection column="role_id" property="children" select="selectByParentId" />
</resultMap>
<sql id="Base_Column_List">
role_id, role_name, role_sign, description, type, parentId, rsort, customs_reg_code,
business_license, departmentId
business_license, departmentId, mq_code
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
... ... @@ -39,11 +40,11 @@
insert into role (role_id, role_name, role_sign,
description, type, parentId,
rsort, customs_reg_code, business_license,
departmentId)
departmentId, mq_code)
values (#{roleId,jdbcType=INTEGER}, #{roleName,jdbcType=VARCHAR}, #{roleSign,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{parentid,jdbcType=INTEGER},
#{rsort,jdbcType=INTEGER}, #{customsRegCode,jdbcType=VARCHAR}, #{businessLicense,jdbcType=VARCHAR},
#{departmentid,jdbcType=VARCHAR})
#{departmentid,jdbcType=VARCHAR},#{mqcode,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.tianbo.warehouse.model.ROLE">
insert into role
... ... @@ -78,6 +79,9 @@
<if test="departmentid != null">
departmentId,
</if>
<if test="mqcode != null">
mq_code,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="roleId != null">
... ... @@ -110,6 +114,9 @@
<if test="departmentid != null">
#{departmentid,jdbcType=VARCHAR},
</if>
<if test="mqcode != null">
#{mqcode,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.ROLE">
... ... @@ -142,6 +149,9 @@
<if test="departmentid != null">
departmentId = #{departmentid,jdbcType=VARCHAR},
</if>
<if test="mqcode != null">
mq_code = #{mqcode,jdbcType=VARCHAR},
</if>
</set>
where role_id = #{roleId,jdbcType=INTEGER}
</update>
... ... @@ -155,7 +165,8 @@
rsort = #{rsort,jdbcType=INTEGER},
customs_reg_code = #{customsRegCode,jdbcType=VARCHAR},
business_license = #{businessLicense,jdbcType=VARCHAR},
departmentId = #{departmentid,jdbcType=VARCHAR}
departmentId = #{departmentid,jdbcType=VARCHAR},
mq_code = #{mqcode,jdbcType=VARCHAR},
where role_id = #{roleId,jdbcType=INTEGER}
</update>
... ...
... ... @@ -16,6 +16,7 @@
<result column="realName" property="realname" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="company_id" property="companyId" jdbcType="INTEGER" />
</resultMap>
<resultMap id="SecurityResult" type="com.tianbo.warehouse.model.USERS">
<id column="user_id" property="userId" jdbcType="INTEGER" />
... ... @@ -29,10 +30,11 @@
<result column="realName" property="realname" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="company_id" property="companyId" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
user_id, username, password, birthday, sex, address, state, mobilePhone, creatTime,
updateTime, userFace, realName, email, age
updateTime, userFace, realName, email, age,company_id
</sql>
<sql id="user_List" >
user_id, username, birthday, sex, address, state, mobilePhone,userFace, realName, email, age
... ... @@ -51,7 +53,7 @@
</select>
<select id="selectAllUser" resultMap="BaseResultMap" parameterType="com.tianbo.warehouse.model.USERS" >
select
*
<include refid="Base_Column_List" />
from users
WHERE 1=1
<if test=" username != null" >
... ...