实际项目自定义权限管理;项目中对角色及url的控制,查询数据库完成权限控制
public_home.html
每个模块都有data-prevID=”“,都定义好的
<div class="crm-top t_top">
<div class="ctop-left"><img src="../img/t_logo.png" /></div>
<div class="ctop-right">
<div class="ctop-user">
<i>欢迎您,
<span id="getusername"></span>
<input type="hidden" id="userRole"/>
<input type="hidden" id="sysUserRoleId"/>
<span title="注销" class="iconfont icon-zhuxiao" onclick="loginOut()"></span>
</i>
</div>
<ul class="nav navbar-nav ctop-nav">
<li data-prevID="600" >
<a class="N6 system" data-modal="system" data-href="systemuser/systemuser_userlist.html">系统管理</a>
</li>
<li data-prevID="900">
<a class="agentManager" data-modal="agentManager" data-href="agentManagement/agent_list.html">代理商管理</a>
</li>
<li data-prevID="800">
<a class="bills" data-modal="bills" data-href="bills/account_bill.html">账单管理</a>
</li>
<li data-prevID="500">
<a class="N7 trafficMng" data-modal="trafficMng" data-href="subscriberCDR/subTrafficCDR_list.html">话单管理</a>
</li>
<li data-prevID="400">
<a data-href="product/product_list.html" data-modal="product" class="product">产品管理</a>
</li>
<li data-prevID="700">
<a data-href="customer/customer_list.html" data-modal="customerManager" class="customerManager">客户管理</a>
</li>
</ul>
</div>
</div>
common.js
html中每个模块都有对应的prevID,登录时通过roleId查询出 对应权限表id字段 的集合,也就是prevID集合,数据库对应priv_id;遍历该集合与所有权限对比,有的则显示出来,没有的就隐藏起来,对应前端代码为common.js ,对应调用接口为SystemUserController的getPrevIdListByRoleCode
//全局变量 用户权限列表
var login_user_potence_list=null;
var contextPath ='/crm_web';
function get_jurisdiction(){
var user_jurisdiction = new Array();
var roleId='';
$.ajax({
type:'post',
url:contextPath+'/user/getUserDetails.do',
async : false,
dataType: "json",
success: function(result) {
roleId=result.roleId;
if(roleId!=undefined){
$.ajax({
type:'post',
url:contextPath+'/user/getPrevIdSetByRoleCode.do',
async : false,
dataType: "json",
data:{'roleId': roleId},
success:function(data){
var rr = data.result;
for(var i=0;i<rr.length;i++){
user_jurisdiction[i]=rr[i];
}
login_user_potence_list=user_jurisdiction;
return user_jurisdiction;
}
})
}else{
console.log('请登录~')
}
}
})
}
get_jurisdiction();
//从全局变量中得到用户权限,根据页面的父标签Id控制叶签tab在有权限动态显示
function tab_jurisdiction(parentTabId){
var page_jurisdiction= new Array();
var str="subscriber-tab";
jQuery('#'+parentTabId+' *[data-prevID]').each(function(key,value){
page_jurisdiction[key] = $(this).attr('data-prevID');
});
$.each(page_jurisdiction,function(i,obj){
var tag=$.inArray(obj,login_user_potence_list);
if(tag>-1){
$('#'+parentTabId +' *[data-prevID="'+obj+'"]').trigger('click');
return false;
}
});
}
//从全局变量得到用户权限,如果没有从后台获取后存到全局变量中 ,在获取数据库全部权限,动态展示页面按钮 控制显示和隐藏
function check_jurisdiction(){
var page_jurisdiction= new Array();
jQuery('*[data-prevID]').each(function(key,value){
page_jurisdiction[key] = $(this).attr('data-prevID');
})
if(login_user_potence_list==null){
login_user_potence_list=get_jurisdiction();
//debugger;
$.each(page_jurisdiction,function(i,data){
var tag=$.inArray(data,login_user_potence_list); //,
if(tag>-1){
$('*[data-prevID = "'+data+'"]').show();
}else{
$('*[data-prevID = "'+data+'"]').hide();
//隐藏
}
})
}else{
$.each(page_jurisdiction,function(i,data){
var tag=$.inArray(data,login_user_potence_list); //,
if(tag>-1){
$('*[data-prevID = "'+data+'"]').show();
}else{
$('*[data-prevID = "'+data+'"]').hide();
//隐藏
}
})
}
}
role.js
//分配权限
function addpreRole(roleId,data){
$.post("/crm_web/user/addpreRole", {'roleId':roleId,'data':data}, function(result) {
//Toast(result.result);
Modal.alert(
{
msg: result.result,
title: '提示',
});
getTree(roleId);
if(result.errCode==0){
var update_user_jurisdiction = new Array();
$.post("/crm_web/user/getPrevIdSetByRoleCode",{'roleId':roleId},function(data){
$.each(data.result,function(i,data){
update_user_jurisdiction[i]=data;
})
$.post("/crm_web/user/getUserDetails ", {}, function(data) {
if (data.role==role_name){
login_user_potence_list=update_user_jurisdiction;
check_jurisdiction();
}
})
})
}
})
};
$(contentDiv).on('click','#grid_body_role i.but_insertpro',function(){
//检测是否越级操作
var agentId = $(this).attr('data-agentId');
methodData = $(this);
indexDao.sendData({
"type":"post",
"method":"distributePrev",
"methodUrl":"insertpro",
"agentId":agentId
});
});
$(contentDiv).on('click','#savePrev',function(){
//获取页面上勾选的prev_code
var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
var checkedObj = treeObj.getCheckedNodes(true)
if(checkedObj.length!=0){
for (var i=0, l=checkedObj.length; i<l; i++) {
//勾选的权限集合
//prevArray[i] = checkedObj[i].id;
if(i!=l-1){
prev=prev+checkedObj[i].id+"=on&"
}else{
prev=prev+checkedObj[i].id+"=on";
}
}
addpreRole(role_name,prev);
prev='';
}else{
return app.toast('请至少选择一项权限');
}
})
SystemUserController对权限的操作
@Controller("SystemUserController")
@RequestMapping("/user")
public class SystemUserController extends CommonController {
private static final Logger log = LoggerFactory.getLogger(SystemUserController.class);
private static final String ACTION_NAME="user";
@Autowired
private SystemUserIntf systemUserIntf;
@Autowired
private SystemPreviledgeIntf systemPreviledgeIntf;
@Autowired
private SystemPriRoleIntf systemPriRoleIntf;
@Autowired
private SystemRoleIntf systemRoleIntf;
@Autowired
private AgentInfoIntf agentInfoIntf;
protected Map<String,Object> getParamMap(HttpServletRequest request){
Map<String,Object> paramMap = new HashMap<>();
String connStatus = request.getParameter("connStatus");
String elementName = request.getParameter("elementName");
String elementStatus = request.getParameter("elementStatus");
String role_name = request.getParameter("role_name");
String roleName = request.getParameter("roleName");
String prev_code = request.getParameter("prev_code");
String roleId = request.getParameter("roleId");
String name = request.getParameter("uname");
String user_code = request.getParameter("user_code");
if(StringUtil.isNotNull(roleId)){
paramMap.put("roleId", roleId);
}
if(StringUtil.isNotNull(role_name)){
paramMap.put("role_name",role_name);
}
if(StringUtil.isNotNull(roleName)){
paramMap.put("roleName",roleName);
}
if(StringUtil.isNotNull(connStatus)){
paramMap.put("connStatus", Integer.valueOf(connStatus));
}
if(StringUtil.isNotNull(name)){
paramMap.put("name", name);
}
if(StringUtil.isNotNull(user_code)){
paramMap.put("user_code", user_code);
}
if(StringUtil.isNotNull(prev_code)){
paramMap.put("prev_code", prev_code);
}
if(StringUtil.isNotNull(elementName)){
paramMap.put("elementName", elementName);
}
if(StringUtil.isNotNull(elementStatus)){
paramMap.put("elementStatus", Integer.valueOf(elementStatus));
}
SystemUser onlineUser =getSystemUser(request);
if(onlineUser!=null){
paramMap.put(SystemUserConstant.agentId, onlineUser.getAgentId());
}
return paramMap;
}
@RequestMapping(value="/getValiCode")
public void getValidate(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
OutputStream os = response.getOutputStream();
String path=request.getSession().getServletContext().getRealPath("/")+"resources\\html\\img\\validate\\code.jpg";
VerificationCodeUtil va=new VerificationCodeUtil();
va.setPATH(path);
BufferedImage image=va.getImage();
String code=va.getVerificationCode();
request.getSession().setAttribute("code", code);
// 输出图像到页面
ImageIO.write(image, "JPEG", os);
os.close();
}
private int RndNum(int n) {
int rnd =0;
for (int i = 0; i < 20; i++){
rnd += Math.floor(Math.random() * 5);
}
return rnd;
}
@RequestMapping(value="/checkValiCode")
public void checkValiCode(HttpServletRequest request,HttpServletResponse response){
int code1=RndNum(2);
int code2=RndNum(2);
String code=(code1+code2)+"";
request.getSession(true).setAttribute("code", code);
JSONObject json = new JSONObject();
json.put("code2", code2);
json.put("code1", code1);
OutputJson(json, response);
}
/**
* 用户登录
* @param username 用户登录名
* @param password 用户密码
*/
@RequestMapping(value="/login")
public void login(HttpServletRequest request, HttpServletResponse response) {
log.info("/开始登录");
JSONObject json = new JSONObject();
String sessionCode = null;
HttpSession session = request.getSession();
sessionCode = (String) session.getAttribute("code");
log.info("sessionCode" + sessionCode);
String code = request.getParameter("code");
if (StringUtil.isNull(sessionCode)) {
sessionCode = request.getParameter("sessionCode");
}
log.info("用户输入的验证码:{" + code + "}--缓存验证码:{" + sessionCode + "} ---"
+ sessionCode.equalsIgnoreCase(code));
if (sessionCode.equalsIgnoreCase(code)) {
try {
String username = request.getParameter("username").toLowerCase();
String password = request.getParameter("password");
password = MD5Util.getMD5String(password);
SystemUser user = systemUserIntf.getByName(username);
AgentInfo agentInfo = agentInfoIntf.getAgentInfoById(user
.getAgentId());
boolean agentStatus = true;
if (agentInfo != null) {
if (CommonConstant.AGENT_STATUS_CLOSE.equals(agentInfo
.getStatus())) {// 如果状态为冻结 则不让登录
agentStatus = false;
}
}
log.info("用户名是否是否匹配" + user.getUser_code().equals(username)
+ "密码是否是否匹配" + user.getPassword().equals(password));
String UTCTime = request
.getParameter(CommonConstant.UTC_TIMESTAMP);
Date time = DateUtil.string2Date(UTCTime,
DateUtil.PATTERN_STANDARD);
if (agentStatus) {
if (user.getPassword().equals(password)) {
String sId = session.getId();
log.info("denglu:" + sId);
Cookie cookie = new Cookie("JSESSIONID", sId);// session_id默认是存放在一个name为JSESSIOINID里面的
response.addCookie(cookie);
json.put("result", "login success");
json.put("status", "1");
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("last_login", time);
userMap.put("user_code", user.getUser_code());
boolean tag = systemUserIntf.update(userMap);
log.info("用户" + username + "-----login 是否成功:{" + tag
+ "}" + "用户信息:---" + user);
if (tag) {
user.setLast_login(time);
}
try {
RedisClientUtil.setRedisStringTtl(sId, 7200,
username);
RedisClientUtil.setRedisEntityTtl(
RedisKeyConstant.REDIS_USER + username,
7200, user);
} catch (Exception e) {
json.put("result", "内存空间不足!");
json.put("status", "2");
OutputJson(json, response);
log.error("内存磁盘空间不足" + e);
}
} else {
json.put("result", "用户名和密码不匹配!");
json.put("status", "2");
}
} else {
json.put("result", "该代理商已冻结,请联系管理员!");
json.put("status", "2");
}
} catch (Exception e) {
json.put("result", "用户名和密码不匹配!");
json.put("status", "2");
OutputJson(json, response);
log.error("stream error" + e);
}
} else {
json.put("result", "验证码错误!");
json.put("status", "2");
}
log.info("返回的登录信息为:{" + json.get("status") + "}");
/* return new ModelAndView("login"); */
OutputJson(json, response);
}
/**
* 从session中获取用户详细信息
*/
@RequestMapping(value="/getUserDetails")
public void getUserDetails(HttpServletRequest request,HttpServletResponse response){
HttpSession session = request.getSession();
String sId=session.getId();
String username=RedisClientUtil.getRedisString(sId);
SystemUser user =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
JSONObject json=(JSONObject) JSONObject.toJSON(user);
json.put("method","getUserDetails");
json.put("action","user");
OutputJson(json, response);
}
/**
* 退出登录
*/
@RequestMapping(value="/loginOut")
public void loginOut(HttpServletRequest request,HttpServletResponse response){
HttpSession session = request.getSession();
String sId=session.getId();
RedisClientUtil.remove(sId);
JSONObject json=new JSONObject();
json.put(SystemConstants.RESULT, "登出成功");
OutputJson(json, response);
}
/**
* 判断是否登录,如果登录获取登录名
*/
@RequestMapping(value="/getusername")
public void getusername(HttpServletRequest request,HttpServletResponse response){
JSONObject json=new JSONObject();
HttpSession session = request.getSession();
String sId=session.getId();
Cookie cookie = new Cookie("JSESSIONID", sId);
response.addCookie(cookie);
String username=RedisClientUtil.getRedisString(sId);
if(StringUtil.isNotNull(username)){
SystemUser user =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
if(user==null){
json.put("loginStatus", 2);
}else{
SystemRole sr = systemRoleIntf.load(user.getRoleId());
json.put("username", user.getUser_code());
json.put("userrole", sr.getRole_name());
json.put("loginStatus", 0);
json.put("roleId", sr.getId());
}
}else{
json.put("loginStatus", 2);
}
log.info("getusername json"+json);
OutputJson(json, response);
}
@RequestMapping(value="/CKAddUser")
public void CKAddUser(HttpServletRequest request,HttpServletResponse response){
JSONObject json = JsonResult.getResult(ACTION_NAME, "CKAddUser",0, true);
OutputJson(json, response);
}
@RequestMapping(value="/CKAddRole")
public void CKAddRole(HttpServletRequest request,HttpServletResponse response){
JSONObject json = JsonResult.getResult(ACTION_NAME, "CKAddRole",0, true);
OutputJson(json, response);
}
/**
* 为administrator用户分配权限,直接从数据库中分配全部权限
*/
@RequestMapping(value="/test")
public void test1(HttpServletRequest req,HttpServletResponse response){
String data1=req.getParameter("data");
String data2=req.getParameter("serializeData");
log.info("-------------------"+data1+"----"+data2);
}
@RequestMapping(value="/initTopUser")
public void initTopUser(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
log.info("addrole");
SystemRole newRole = new SystemRole();
newRole.setRole_code("administrator");
newRole.setRole_name("administrator");
String roleId = newRole.getId();
systemPriRoleIntf.delete(roleId);
List<SystemPreviledge> list = systemPreviledgeIntf.listAll();
boolean tag2 = false;
for (int i = 0; i < list.size(); i++) {
SystemPriRole systemPriRole = new SystemPriRole();
systemPriRole.setPrevCode(list.get(i).getPrev_code());
systemPriRole.setRoleId(roleId);
systemPriRole.setPrevId(systemPreviledgeIntf.getByCode(
list.get(i).getPrev_code()).getId());
boolean tag3 = systemPriRoleIntf.insert(systemPriRole);
if (tag3) {
tag2 = true;
}
}
;
log.info("-----------------------------------加权限分配:" + tag2);
}
/**
* 为角色分配权限
* @param 角色名 role_name
* @param 权限列表 data
*/
@RequestMapping(value="/addpreRole")
public void addpreRole(HttpServletRequest request,HttpServletResponse response,PageParam pageParam)
throws UnsupportedEncodingException {
log.info("-----------------------------------权限分配");
String data = request.getParameter("data");
String roleId = request.getParameter("roleId");
SystemRole sr = systemRoleIntf.load(roleId);
JSONObject json = null;
String msg = "";
if ("administrator".equals(sr.getRole_name())) {
json = JsonResult.getResult(ACTION_NAME, "addpreRole", 4,
"该角色不能分配权限");
OutputJson(json, response);
} else {
/*SystemRole role = systemRoleIntf.getByName(role_name);
String role_code = role.getRole_code();*/
systemPriRoleIntf.delete(roleId);
log.info("role_code:============" + sr.getRole_name() + " 权限是:" + data);
data = data.replace("%7B", "{");
data = data.replace("%7D", "}");
data = data.replace("", "");
log.info("--------------------权限数据:" + data);
String[] array = data.split("&");
log.info("info--->" + data.replace("+", ""));
boolean tag = false;
for (int i = 0; i < array.length; i++) {
String[] prevcodearray = array[i].split("=");
SystemPriRole systemPriRole = new SystemPriRole();
systemPriRole.setPrevCode(prevcodearray[0]);
systemPriRole.setRoleId(roleId);
systemPriRole.setPrevId(systemPreviledgeIntf.getByCode(
prevcodearray[0]).getId());
tag = systemPriRoleIntf.insert(systemPriRole);
if (tag) {
msg = "保存成功";
}
}
//重置当前角色所属代理商下所有代理商角色权限
List<String> agentIdList = agentInfoIntf.getAllIdByParentId(sr.getAgentId());
for(String agentIds:agentIdList){//遍历所有下级代理商
if(!agentIds.equals(sr.getAgentId())){//不为当前代理商id才做操作
//根据agentId获取代理商下所有角色,并重置角色权限
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("agentId", agentIds);
List<SystemRole> roleList = systemRoleIntf.listAllByAgentId(paramMap);
for(SystemRole roles:roleList){
List<SystemPriRole> sysPriRoleList = systemPriRoleIntf.lgetPrevByRolecode(roles.getId());
for(SystemPriRole sysPriRoles:sysPriRoleList){
boolean flag = true; //是否需要删除超范围权限
for (int i = 0; i < array.length; i++) {
String[] prevcodearray = array[i].split("=");
if(sysPriRoles.getPrevCode().equals(prevcodearray[0])){//拿原有角色权限跟当前权限作对比
flag = false; //如果原有角色权限在当前所分配权限中存在,则不需要删除
break;
}
}
if(flag){ //如果需要删除超出范围权限,做删除角色权限表数据
systemPriRoleIntf.deleteById(sysPriRoles.getId());
}
}
}
}
}
json = JsonResult.getResult(ACTION_NAME, "addpreRole", 0, "重置角色权限:"
+ msg);
log.info("-----------------------------------权限分配:" + json);
OutputJson(json, response);
}
}
/**
* 根据角色名获取权限列表
* @param 角色名 role_name
* @return 权限列表 data
*/
@RequestMapping(value="/getPrevListByRoleCode")
public void getPrevListByRoleCode(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("------------------------------------通过rolecode获取权限列表");
String roleId=request.getParameter("roleId");;
if(StringUtil.isNull(roleId)){
SystemUser user = getSystemUser(request);
roleId = user.getRoleId();
}
/*SystemRole role=systemRoleIntf.getByName(role_name);
String roleId=role.getId();*/
log.info("获取的roleId为:-----》》"+roleId);
JSONArray prevArray=new JSONArray();
List<SystemPriRole> list=systemPriRoleIntf.lgetPrevByRolecode(roleId);
for(int i=0;i<list.size();i++){
prevArray.add(list.get(i).getPrevCode());
}
JSONObject obj = JsonResult.getResult(ACTION_NAME, "getPrevListByRoleCode", 0, prevArray);
log.info("------------------------------------getPrevListByRoleCode返回信息为:"+obj);
OutputJson(obj, response);
}
@RequestMapping(value="/getPrevIdSetByRoleCode")
public void getPrevIdListByRoleCode(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("------------------------------------通过rolecode获取权限列表");
String roleId=request.getParameter("roleId");;
/*SystemRole role=systemRoleIntf.getByName(role_name);
String roleId=role.getId();*/
log.info("获取的rolecode为:-----》》"+roleId);
JSONArray prevArray=new JSONArray();
List<SystemPriRole> list=systemPriRoleIntf.lgetPrevByRolecode(roleId);
for(int i=0;i<list.size();i++){
prevArray.add(list.get(i).getPrevId());
}
JSONObject obj = JsonResult.getResult(ACTION_NAME, "getPrevIdSetByRoleCode", 0, prevArray);
log.info("------------------------------------getPrevListByRoleCode返回信息为:"+obj);
OutputJson(obj, response);
}
/**
* 获取用户列表
*/
@RequestMapping(value="/getUserList")
public void getUserList(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("------------------------------------getUserList");
Map<String, Object> paramMap =getParamMap(request);
PageBean<SystemUser> list=systemUserIntf.listSysUser(pageParam, paramMap);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "getUserList", 0, list);
log.info("------------------------------------getUserList返回信息为:"+obj);
OutputJson(obj, response);
}
/**
* 分页获取角色列表
*/
@RequestMapping(value="/getRoleList")
public void getRoleList(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("------------------------------------getRoleList");
Map<String, Object> paramMap = getParamMap(request);
//TODO
SystemUser user = getSystemUser(request);
AgentInfo agentInfo = agentInfoIntf.getAgentInfoById(user.getAgentId());
paramMap.put("firstId", agentInfo.getId());//不需要展示下级代理商非'agent_admin'角色
List<String> ids = agentInfoIntf.getAllIdByParentId(user.getAgentId());
if(ids!=null && ids.size()>0){
paramMap.put(SystemUserConstant.agentId, ids);
}
PageBean<SystemRole> list=systemRoleIntf.listSystemRole(pageParam, paramMap);
//获取代理商下第一个角色
paramMap.clear();
paramMap.put("agentId", user.getAgentId());
SystemRole sr = systemRoleIntf.listAllByAgentId(paramMap).get(0);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "getRoleList", 0, list);
obj.put("baseRole", sr);
log.info("------------------------------------getRoleList返回信息为:"+obj);
OutputJson(obj, response);
}
/**
* 获取全部角色
* @return 全部角色 list
*/
@RequestMapping(value="/selectRole")
public void selectRole(HttpServletRequest request,HttpServletResponse response,PageParam pageParam,HttpSession session){
log.info("------------------------------------查询列表");
//获得sessionid
String sId=session.getId();
//根据sessionid获得用户名
String username=RedisClientUtil.getRedisString(sId);
SystemUser sysUser=systemUserIntf.getByName(username);
Map<String,Object> map = new HashMap<>();
String role=request.getParameter("role");
String agentId = request.getParameter("agentId");
if(StringUtil.isNull(agentId)){
agentId = sysUser.getAgentId();
}
map.put("agentId", agentId);
log.info("选择角色"+role);
if(StringUtil.isNotNull(role)){
List<SystemRole> list=systemRoleIntf.listAllByAgentId(map);
JSONObject json = JsonResult.getResult(ACTION_NAME, "selectRole", 0, list);
json.put("role", role);
log.info("------------------------selectRole--------返回信息为:"+json);
OutputJson(json, response);
}else{
List<SystemRole> list=systemRoleIntf.listAllByAgentId(map);
JSONObject json = JsonResult.getResult(ACTION_NAME, "selectRole", 0, list);
OutputJson(json, response);
}
}
/**
* 获取全部权限
* @param 角色名 role_name
* @return 权限列表 data
*/
@RequestMapping(value="/selectPrev")
public void selectPrev(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("------------------------------------selectPrev");
List<SystemPreviledge> list = null;
HttpSession session=request.getSession();
String sId=session.getId();
String username=RedisClientUtil.getRedisString(sId);
SystemUser onlineUser =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
String roleId = onlineUser.getRoleId();
if(StringUtil.isNotNull(roleId)){
Map<String, Object> map = new HashMap<>();
map.put("roleId", roleId);
list = systemPreviledgeIntf.listAllByRoleId(map);
}else{
systemPreviledgeIntf.listAll();
}
JSONObject json = JsonResult.getResult(ACTION_NAME, "selectPrev", 0, list);
log.info("---------------------------selectPrev---------返回信息为:"+json);
OutputJson(json, response);
}
/**
* 获取当前登录用户代理商以及所有下级代理商
* @param agentId
* @return 代理商列表 data
*/
@RequestMapping(value="/selectAgent")
public void selectAgent(HttpServletRequest request,HttpServletResponse response,PageParam pageParam,HttpSession session){
JSONObject obj = null;
String parentId = request.getParameter("agentId");
String isSelect = request.getParameter("isSelect"); //是否查询所有
if(StringUtil.isNotNull(isSelect)&&isSelect.equals("0")){//只查询当前代理商信息
AgentInfo agentInfo = agentInfoIntf.getAgentInfoById(parentId);
obj = JsonResult.getResult(ACTION_NAME, "inputAgent",0,agentInfo);
obj.put("role", request.getParameter("role"));
}else{
if(StringUtil.isNull(parentId)){
//获得sessionid
String sId=session.getId();
//根据sessionid获得用户名
String username=RedisClientUtil.getRedisString(sId);
//从缓存中获取
SystemUser user =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
parentId = user.getAgentId();
}
Map<String, Object>AgentList=new HashMap<>();
List<AgentInfo> infoList = agentInfoIntf.getAgentinfoByParentIds(parentId);
AgentList.put("groupList", infoList);
AgentList.put("checkedId",parentId);
obj = JsonResult.getResult(ACTION_NAME, "selectAgent",0,AgentList);
}
OutputJson(obj, response);
}
/**
* 分页获取权限列表展示
* @return 权限列表 PageBean<SystemPreviledge> list
*/
@RequestMapping(value="/getPrevList")
public void getPrevList(HttpServletRequest request,HttpServletResponse response,PageParam pageParam){
log.info("-----------------------------------getPrevList");
Map<String, Object> paramMap=getParamMap(request);
PageBean<SystemPreviledge> list=systemPreviledgeIntf.listSystemPreviledge(pageParam, paramMap);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "getPrevList", 0, list);
OutputJson(obj, response);
}
/**
* 分页获取权限列表展示
* @return 权限列表 PageBean<SystemPreviledge> list
*/
@RequestMapping(value="/addUser")
public void test(HttpServletRequest request,HttpServletResponse response,HttpSession session){
String user_code=request.getParameter("user_code").toLowerCase();
SystemUser user=systemUserIntf.getByName(user_code);
if(user!=null){
JSONObject json = JsonResult.getResult(ACTION_NAME, "usersave",4, "该用户已存在");
log.info("----------------------------------新增用户返回信息"+json);
OutputJson(json, response);
}else{
String UTCTime=request.getParameter(CommonConstant.UTC_TIMESTAMP);
Date time=DateUtil.string2Date(UTCTime, DateUtil.PATTERN_STANDARD);
log.info(" utc 时间:{"+UTCTime+"}---服务器当前时间:{"+new Date()+"}");
String password=request.getParameter("password");
password=MD5Util.getMD5String(password);
String roleId = request.getParameter("roleId");
String agentId = request.getParameter("agentId");
user=new SystemUser();
user.setUser_code(user_code);
user.setPassword(password);
user.setName(request.getParameter("name"));
user.setRoleId(roleId);
user.setMail(request.getParameter("mail"));
user.setCell_phone(request.getParameter("phone"));
user.setCreate_time(time);
user.setLast_login(null);
SystemUser su = getSystemUser(request);
user.setCreator(su.getUser_code());
user.setAgentId(agentId);
boolean tag=systemUserIntf.saveUser(user);
JSONObject json = JsonResult.getResult(ACTION_NAME, "usersave", 0, tag);
log.info("----------------------------------新增用户返回信息"+json);
OutputJson(json, response);
}
}
/**
* 增加角色
*/
@RequestMapping(value="/addRole")
public void addRole(HttpServletRequest request,HttpServletResponse response){
log.info("addrole");
String roleName=request.getParameter("role_name");
// SystemRole newRole=systemRoleIntf.getByName(role_name);
if(StringUtil.isNull(roleName)){
JSONObject obj = JsonResult.getResult(ACTION_NAME, "rolesave",4, "角色名不能为空!");
OutputJson(obj, response);
}else{
SystemRole newRole1=new SystemRole();
newRole1.setRole_code(IDGenerator.generateID());
newRole1.setRole_name(roleName.toLowerCase());
SystemUser user = getSystemUser(request);
newRole1.setAgentId(user.getAgentId());
boolean tag=systemRoleIntf.save(newRole1);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "rolesave",0, tag);
log.info("----------------------------------addRole"+obj);
OutputJson(obj, response);
}
}
/**
* 增加权限
* @param prev_code 权限url
* @param prev_name 权限名字
* @param parent_code 父级权限url
*/
@RequestMapping(value="/addPrev")
public void addPrev(HttpServletRequest request,HttpServletResponse response){
SystemPreviledge ystemPreviledge=new SystemPreviledge();
ystemPreviledge.setPrev_code(request.getParameter("prev_code"));
ystemPreviledge.setPrev_name(request.getParameter("prev_name"));
ystemPreviledge.setParent_code(request.getParameter("parent_code"));
boolean tag=systemPreviledgeIntf.insert(ystemPreviledge);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "prevsave", 0, tag);
log.info("----------------------------------addPrev"+obj);
OutputJson(obj, response);
}
/**
* 修改权限信息
*/
@RequestMapping(value="/updatePrev")
public void updatePrev(HttpServletRequest request,HttpServletResponse response){
Map<String,Object> prev=new HashMap<String,Object>();
prev.put("prev_code",request.getParameter("prev_code"));
prev.put("prev_name",request.getParameter("prev_name"));
prev.put("parent_code",request.getParameter("parent_code"));
log.info("-----updatePrevMap"+prev);
boolean tag=systemPreviledgeIntf.updatePrevInfo(prev);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "prevupdate", 0, tag);
log.info("--------------------------------updatePrev"+obj);
OutputJson(obj, response);
}
@RequestMapping(value="/updateUserPassword")
public void updateUserPassword(HttpServletRequest request,HttpServletResponse response){
String password=request.getParameter("newpassword");
String oldpassword=request.getParameter("oldpassword");
String user_code=request.getParameter("user_code");
Map<String,Object> user=new HashMap<String,Object>();
user.put("user_code",user_code);
HttpSession session=request.getSession();
String sId=session.getId();
String username=RedisClientUtil.getRedisString(sId);
SystemUser onlineUser =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
/* String sessionUser_code=(String)session.getAttribute("username");
SystemUser onlineUser=(SystemUser)session.getAttribute(sessionUser_code);*/
log.info("用户修密码为:--------->>>>>"+password);
if(StringUtil.isNotNull(password)&&StringUtil.isNotNull(oldpassword)){
oldpassword=MD5Util.getMD5String(oldpassword);
log.info("用户是不是本登录用户"+oldpassword.equals(onlineUser.getPassword()));
if(oldpassword.equals(onlineUser.getPassword())){
password=MD5Util.getMD5String(password);
user.put("password",password);
boolean tag=systemUserIntf.update(user);
if(tag){
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate",0, "修改密码成功");
OutputJson(obj, response);
}
}else{
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate",4, "请正确输入登录密码");
OutputJson(obj, response);
return;
}
}else{
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate",4, "请求异常");
OutputJson(obj, response);
return;
}
}
/**
* 修改用户信息,三种修改业务共用此方法
* 1,修改密码
* @param password
* 2,修改登录时间
* @param last_login
* 3,修改用户其他信息
* @param name 名字
* @param role 角色
* @param email 邮箱
* @param phone 电话
*
* @return boolean tag 修改成功或失败标志
*/
@RequestMapping(value="/updateUser")
public void updateUser(HttpServletRequest request,HttpServletResponse response){
String password=request.getParameter("newpassword");
String oldpassword=request.getParameter("oldpassword");
String user_code=request.getParameter("user_code");
Map<String,Object> user=new HashMap<String,Object>();
user.put("user_code",user_code);
HttpSession session=request.getSession();
String sId=session.getId();
String username=RedisClientUtil.getRedisString(sId);
SystemUser onlineUser =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
/* String sessionUser_code=(String)session.getAttribute("username");
SystemUser onlineUser=(SystemUser)session.getAttribute(sessionUser_code);*/
log.info("用户修密码为:--------->>>>>"+password);
if(StringUtil.isNotNull(password)&&StringUtil.isNotNull(oldpassword)){
oldpassword=MD5Util.getMD5String(oldpassword);
log.info("用户是不是本登录用户"+oldpassword.equals(onlineUser.getPassword()));
if(oldpassword.equals(onlineUser.getPassword())){
password=MD5Util.getMD5String(password);
user.put("password",password);
boolean tag=systemUserIntf.update(user);
if(tag){
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate",0, "修改密码成功");
OutputJson(obj, response);
}
}else{
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate",4, "请正确输入登录密码");
OutputJson(obj, response);
return;
}
}else{
user.put("name",request.getParameter("name"));
//TODO
user.put("roleId",request.getParameter("roleId"));
user.put("mail",request.getParameter("mail"));
user.put("cell_phone",request.getParameter("phone"));
user.put("agentId",request.getParameter("agentId"));
log.info("-----userUpdateMap:"+user);
boolean tag=systemUserIntf.update(user);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "userupdate", 0, tag);
log.info("-----修改的用户是不是当前用户:"+onlineUser.getUser_code().equals(user_code));
if(onlineUser.getUser_code().equals(user_code)){
SystemUser NEWuser=systemUserIntf.getByName(user_code);
//session.setAttribute(user_code, NEWuser);
RedisClientUtil.setRedisEntityTtl(RedisKeyConstant.REDIS_USER+username,1800, NEWuser);
};
log.info("----------------------------------修改用户返回信息"+obj);
OutputJson(obj, response);
}
}
/**
* 删除用户
* @param String user_code 用户名 唯一主键
* @return boolean 删除标志 tag
*/
@RequestMapping(value="/userDelete")
public void userDelete(HttpServletRequest request,HttpServletResponse response){
String msg="";
String user_code=request.getParameter("user_code");
log.info("用户名为:"+user_code);
HttpSession session=request.getSession();
String sId=session.getId();
// String onlineUser_code=(String) session.getAttribute(CommonConstant.USER_NAME);
String onlineUser_code=RedisClientUtil.getRedisString(sId);
if (user_code.equals("admin")){
msg="此用户不能删除。";
JSONObject json = JsonResult.getResult(ACTION_NAME, "userdelete", 4, msg);
OutputJson(json, response);
return;
}else if(user_code.equals(onlineUser_code)){
msg="用户不能删除自己。";
JSONObject json = JsonResult.getResult(ACTION_NAME, "userdelete", 4, msg);
OutputJson(json, response);
return;
}else{
boolean tag=systemUserIntf.delete(user_code);
if(tag){
msg="删除成功";
RedisClientUtil.remove(RedisKeyConstant.REDIS_USER+user_code);
}else{
msg="删除失败";
}
JSONObject json = JsonResult.getResult(ACTION_NAME, "userdelete", 0, msg);
log.info("----------------------------------删除用户返回信息"+json);
OutputJson(json, response);
return;
}
}
/**
* 删除角色
* 同时删除角色对应的权限,置空用户的角色信息
* @param String role_code 角色url 角色表主键
*/
@RequestMapping(value="/roleDelete")
public void roleDelete(HttpServletRequest request,HttpServletResponse response){
String msg="";
String roleId=request.getParameter("roleId");
SystemRole s=systemRoleIntf.load(roleId);
if(s.getRole_name().equals("administrator")){
log.info("这个用户是:---》》"+s.getRole_name());
JSONObject obj = JsonResult.getResult(ACTION_NAME, "roledelete", 4, "该角色不能删除");
OutputJson(obj, response);
}else{
int ct = systemUserIntf.countUserOfRole( s.getId());
JSONObject obj = null;
if(ct>0){
msg ="删除失败,有用户拥有此角色";
obj = JsonResult.getResult(ACTION_NAME, "roledelete", 4, msg);
}else{
boolean tag=systemRoleIntf.delete(roleId);
if(tag){
msg="删除成功";
boolean flag1=systemPriRoleIntf.delete(roleId);
log.info("置空角色对应权限---》"+flag1);
log.info("用户角色名为---》"+s.getRole_name());
boolean flag=systemUserIntf.initNullRole(s.getId());
log.info("置空用户角色---》"+flag);
}
obj = JsonResult.getResult(ACTION_NAME, "roledelete", 0, msg);
}
log.info("----------------------------------删除角色返回信息"+obj);
OutputJson(obj, response);
}
}
/**
* 删除权限
* @param String prev_code 权限表主键
*/
@RequestMapping(value="/prevDelete")
public void prevDelete(HttpServletRequest request,HttpServletResponse response){
String prev_code=request.getParameter("prev_code");
boolean tag=systemPreviledgeIntf.delete(prev_code);
JSONObject obj = JsonResult.getResult(ACTION_NAME, "prevdelete", 0, tag);
log.info("---------------------------------prevDelete"+obj);
OutputJson(obj, response);
}
/**
* 通过用户id(用户名)查询用户详细信息
* @param String user_code 用户id(登录名)
* @return SystemUser user 用户实体对象
*/
@RequestMapping(value="/findUserByid")
public void findUserByid(HttpServletRequest request,HttpServletResponse response){
String user_code=request.getParameter("user_code");
JSONObject json = new JSONObject();
SystemUser user=systemUserIntf.getByName(user_code);
json.put(SystemConstants.RESULT,user);
log.info("--------------------------------findUserByid"+json);
OutputJson(json, response);
}
/**
* 检测不能越级操作
* @param request
* @param response
* @param id
*/
@RequestMapping(value="/distributePrev",method=RequestMethod.POST)
public void distributeProduct(HttpServletRequest request,HttpServletResponse response){
//1.获取当前用户代理商id
String currentAgentId = getSystemUser(request).getAgentId();
//2.查询当前用户下的直接子代理商Ids
List<String> list = agentInfoIntf.getNextAgentIdsById(currentAgentId);
list.add(currentAgentId);
//3.判断目标id是否存在于ids中
String agentId = request.getParameter("agentId");
//String method = request.getParameter("method");
String methodData = request.getParameter("methodData");
String methodUrl = request.getParameter("methodUrl");
int num = 0;
if(!list.contains(agentId)){
num = 1;
}
JSONObject obj = JsonResult.getResult(ACTION_NAME, methodUrl, num, methodData);
OutputJson(obj,response);
}
}
数据库表
登录时先进行安全拦截
package com.snt.crm.web.accessor.interceptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.snt.crm.sys.manage.intf.SystemPreviledgeIntf;
import com.snt.crm.sys.manage.intf.SystemPriRoleIntf;
import com.snt.crm.sys.manage.intf.SystemRoleIntf;
import com.snt.crm.sys.manage.intf.entity.SystemPreviledge;
import com.snt.crm.sys.manage.intf.entity.SystemPriRole;
import com.snt.crm.sys.manage.intf.entity.SystemRole;
import com.snt.crm.sys.manage.intf.entity.SystemUser;
import com.snt.crm.common.constants.RedisKeyConstant;
import com.snt.crm.common.core.redis.RedisClientUtil;
public class SecurityInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);
@Autowired
private SystemPriRoleIntf systemPriRoleIntf;
@Autowired
private SystemRoleIntf systemRoleIntf;
@Autowired
private SystemPreviledgeIntf systemPreviledgeIntf;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
HttpSession session = req.getSession();
res.setContentType("application/json");
res.setCharacterEncoding("utf-8");
JSONObject o=new JSONObject();
PrintWriter writer = res.getWriter();
log.info(" 拦截器开始==========");
// 从session 里面获取当前session的sid
String sId=session.getId();
Cookie cookie = new Cookie("JSESSIONID", sId);
res.addCookie(cookie);
String username=RedisClientUtil.getRedisString(sId);
SystemUser obj =RedisClientUtil.getRedisEntity(RedisKeyConstant.REDIS_USER+username, SystemUser.class);
// 判断如果没有取到用户信息或者用户名,就跳转到登陆页面,提示用户进行登陆
if (obj == null ){
log.info("未登录========="+req.getContextPath()+req.getRequestURI());
// ajax异步请求无法重定向 res.sendRedirect(req.getContextPath() + "/login.html");
o.put("errCode","outlogin");
o.put("errMessage", "请刷新登录");
//清除cookie
cookie.setMaxAge(0);
writer.print(o);//验证失败
return false;
}else{
RedisClientUtil.setRedisStringTtl(sId, 3600, username);
RedisClientUtil.setRedisEntityTtl(RedisKeyConstant.REDIS_USER+username, 3600, obj);
//“admin”用户直接放行
if(obj.getUser_code().equals("admin")){
log.info(obj.getUser_code()+"用户,无需验证权限");
return true;
}
String url=req.getRequestURI();
//如果请求url有点“。”直接截取前面8位到‘。’之前的部分
if(url.indexOf(".")==-1){
url=url.substring(8);
}else{
url=url.substring(8, url.indexOf("."));
}
Pattern p = Pattern.compile("(/+[a-zA-Z_0-9]*/+[a-zA-Z_0-9]*)");
Matcher m = p.matcher(url);
while(m.find()){
url=m.group();
}
//双‘//’路径请求直接拦截,告诉其无权限
Pattern p1 = Pattern.compile("(/{2,})");
Matcher m1 = p1.matcher(url);
if(m1.find()){
o.put("errCode", 1);
o.put("errMessage", "没有权限");
writer.print(o);//验证失败
return false;
}
log.info("====== 当前请求url:{"+url+"}");
List<String> AllprevString=getAllPrevCodeListFromApplication(req);
log.info("数据库中是否包含此权限:{"+AllprevString.contains(url)+"}--数据库中总权限数为:{"+AllprevString.size()+"}");
//先判断请求在不在所有权限请求中
if(AllprevString.contains(url)){
List<String> UserprevlistStirng=new ArrayList<String>();
String roleId=obj.getRoleId();
SystemRole role=systemRoleIntf.load(roleId);
log.info("该用户的角色名:"+role.getRole_name());
// String roleId=role.getId();
List<SystemPriRole> list=systemPriRoleIntf.lgetPrevByRolecode(roleId);
log.info("用户是否拥有此权限:{"+UserprevlistStirng.contains(url)+"}此用户拥有的权限总数为:"+list.size());
for(int i=0;i<list.size();i++){
SystemPriRole systemPriRole=list.get(i);
String prevCode=systemPriRole.getPrevCode();
UserprevlistStirng.add(prevCode);
};
//
//判断请求在不在该用户对应权限中
if(UserprevlistStirng.contains(url)){
o.put("errCode", 0);
return true;
}else{
//0正常 1: 没有权限
o.put("errCode", 1);
o.put("errMessage", "没有权限");
writer.print(o);//验证失败
return false;
}
}else{
log.info("此url不在拦截范围内");
return true;
}
}
}
/*
* 从application 中获取权限列表,如果没有就调用生成方法
* */
private List getAllPrevCodeListFromApplication(HttpServletRequest req){
ServletContext apc = req.getSession().getServletContext();
List AllprevString=(List) apc.getAttribute("AllprevString");
if(AllprevString==null){
return getAllPrevCodeList(req);
}else{
return AllprevString;
}
}
/*
* 生成权限列表
* */
private List getAllPrevCodeList(HttpServletRequest req){
ServletContext apc = req.getSession().getServletContext();
List<SystemPreviledge> allPrevList=systemPreviledgeIntf.listAll();
List<String> AllprevString=new ArrayList<String>();
for(int i=0;i<allPrevList.size();i++){
SystemPreviledge systemPriRole=allPrevList.get(i);
AllprevString.add(systemPriRole.getPrev_code());
log.info("数据库中所有权限:"+i+"{"+systemPriRole.getPrev_code()+"}");
};
apc.setAttribute("AllprevString", AllprevString);
return AllprevString;
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object arg2, ModelAndView arg3) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object arg2, Exception arg3) throws Exception {
}
}