Commit 3730d816 authored by fangzhipeng's avatar fangzhipeng

继续完善shiro管理权限功能

parent c82cdacc
......@@ -2,17 +2,19 @@ package com.bigsys.auth.project.config;
import com.bigsys.auth.project.db.model.User;
import com.bigsys.auth.project.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.nio.charset.Charset;
@Component("myRealm")
public class MyRealm extends AuthorizingRealm{
......@@ -28,7 +30,10 @@ public class MyRealm extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
User user = userService.getUser((String) authenticationToken.getPrincipal());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, authenticationToken.getCredentials(), this.getClass().getName());
if (!user.getPassward().equals((new String((char[]) authenticationToken.getCredentials())))) {
throw new IncorrectCredentialsException("密码错误!!");
}
AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassward(), this.getClass().getName());
return info;
}
}
......@@ -4,21 +4,28 @@ import com.bigsys.auth.project.db.model.User;
import com.bigsys.auth.project.util.response.BSResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
......@@ -44,6 +51,8 @@ public class ShiroConfig {
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setFilters(getMyFilters());
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
......@@ -57,7 +66,7 @@ public class ShiroConfig {
// 拦截器.
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/hello", "anon");
filterChainDefinitionMap.put("/**", "anon");
filterChainDefinitionMap.put("/**", "authc");
// // 配置不会被拦截的链接 顺序判断
// filterChainDefinitionMap.put("/static/**", "anon");
// filterChainDefinitionMap.put("/ajaxLogin", "anon");
......@@ -76,17 +85,46 @@ public class ShiroConfig {
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(myRealm);
return securityManager;
}
private Map<String, Filter> getMyFilters() {
Map<String, Filter> filters = new HashMap<>();
filters.put("authc", new FormAuthenticationFilter() {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
if (isLoginSubmission(request, response)) {
return executeLogin(request, response);
} else {
//allow them to see the login page ;)
return true;
}
} else {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
BSResponse bsResponse = BSResponse.needLogin("您已经退出,请重新登录。");
OutputStream outputStream = null;
outputStream = response.getOutputStream();
outputStream.write(new ObjectMapper().writeValueAsString(bsResponse).getBytes("utf-8"));
return false;
}
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
try {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
BSResponse bsResponse = BSResponse.error(e.getMessage());
OutputStream outputStream = null;
outputStream = response.getOutputStream();
outputStream.write(new ObjectMapper().writeValueAsString(bsResponse).getBytes("utf-8"));
return false;
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
@Bean
public FormAuthenticationFilter authc() {
return new FormAuthenticationFilter() {
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
response.setContentType("application/json");
......@@ -98,9 +136,32 @@ public class ShiroConfig {
outputStream.write(new ObjectMapper().writeValueAsString(bsResponse).getBytes("utf-8"));
return false;
}
};
});
return filters;
}
@Bean
public SecurityManager securityManager(SessionManager sessionManager) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setSessionManager(sessionManager);
// 设置realm.
securityManager.setRealm(myRealm);
return securityManager;
}
@Bean
public SessionManager sessionManager() {
Cookie sessionIdCookie = new SimpleCookie();
sessionIdCookie.setName("MySessionId");
sessionIdCookie.setHttpOnly(false);
sessionIdCookie.setPath("/");
DefaultWebSessionManager manager = new DefaultWebSessionManager();
manager.setSessionIdCookie(sessionIdCookie);
return manager;
}
// /**
// * 身份认证realm; (这个需要自己写,账号密码校验;权限等)
// *
......
package com.bigsys.auth.project.config;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
......@@ -29,6 +30,14 @@ public class SpringInit implements ApplicationContextAware{
}
@PostConstruct
public void test() {
Map<String, FormAuthenticationFilter> beans = applicationContext.getBeansOfType(FormAuthenticationFilter.class);
for (Map.Entry<String, FormAuthenticationFilter> stringFormAuthenticationFilterEntry : beans.entrySet()) {
System.out.println(stringFormAuthenticationFilterEntry.getKey() + stringFormAuthenticationFilterEntry.getValue().getClass().getName());
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
......
......@@ -51,4 +51,9 @@ public class RoleController {
return BSResponse.ok(links);
}
@RequestMapping(value = "/getSubRoles")
public BSResponse getSubRoles(String roleId) {
List<Role> roles = roleService.getSubRoles(roleId);
return BSResponse.ok(roles);
}
}
......@@ -40,15 +40,7 @@ public class UserController {
@RequestMapping(value = "/page")
public PageInfo<User> page (User model, PageInfo<User> page) {
return userService.selectByExampleAndPage(page, (example, criteria) -> {
if (!StringUtils.isEmpty(model.getName())) {
criteria.andNameLike("%" + model.getName() + "%");
}
if (!StringUtils.isEmpty(model.getPhone())) {
criteria.andPhoneLike("%" + model.getPhone() + "%");
}
example.setOrderByClause("updateTime desc");
});
return userService.page(model, page);
}
}
......@@ -2,9 +2,8 @@ package com.bigsys.auth.project.db.dao;
import com.bigsys.auth.project.db.model.User;
import com.bigsys.auth.project.db.model.UserExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
long countByExample(UserExample example);
......
......@@ -3,6 +3,7 @@
<mapper namespace="com.bigsys.auth.project.db.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.bigsys.auth.project.db.model.User">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="passward" jdbcType="VARCHAR" property="passward" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
......@@ -68,7 +69,7 @@
</where>
</sql>
<sql id="Base_Column_List">
id, name, passward, phone, createTime, updateTime
id, username, name, passward, phone, createTime, updateTime
</sql>
<select id="selectByExample" parameterType="com.bigsys.auth.project.db.model.UserExample" resultMap="BaseResultMap">
select
......@@ -101,12 +102,12 @@
</if>
</delete>
<insert id="insert" parameterType="com.bigsys.auth.project.db.model.User">
insert into bigsys_user (id, name, passward,
phone, createTime, updateTime
)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{passward,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}
)
insert into bigsys_user (id, username, name,
passward, phone, createTime,
updateTime)
values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR},
#{passward,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.bigsys.auth.project.db.model.User">
insert into bigsys_user
......@@ -114,6 +115,9 @@
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="name != null">
name,
</if>
......@@ -134,6 +138,9 @@
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
......@@ -163,6 +170,9 @@
<if test="record.id != null">
id = #{record.id,jdbcType=VARCHAR},
</if>
<if test="record.username != null">
username = #{record.username,jdbcType=VARCHAR},
</if>
<if test="record.name != null">
name = #{record.name,jdbcType=VARCHAR},
</if>
......@@ -186,6 +196,7 @@
<update id="updateByExample" parameterType="map">
update bigsys_user
set id = #{record.id,jdbcType=VARCHAR},
username = #{record.username,jdbcType=VARCHAR},
name = #{record.name,jdbcType=VARCHAR},
passward = #{record.passward,jdbcType=VARCHAR},
phone = #{record.phone,jdbcType=VARCHAR},
......@@ -198,6 +209,9 @@
<update id="updateByPrimaryKeySelective" parameterType="com.bigsys.auth.project.db.model.User">
update bigsys_user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
......@@ -218,7 +232,8 @@
</update>
<update id="updateByPrimaryKey" parameterType="com.bigsys.auth.project.db.model.User">
update bigsys_user
set name = #{name,jdbcType=VARCHAR},
set username = #{username,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
passward = #{passward,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
createTime = #{createTime,jdbcType=TIMESTAMP},
......
package com.bigsys.auth.project.db.dao;
import com.bigsys.auth.project.db.model.UserRole;
import com.bigsys.auth.project.db.model.UserRoleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserRoleMapper {
long countByExample(UserRoleExample example);
int deleteByExample(UserRoleExample example);
int deleteByPrimaryKey(Integer id);
int insert(UserRole record);
int insertSelective(UserRole record);
List<UserRole> selectByExample(UserRoleExample example);
UserRole selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") UserRole record, @Param("example") UserRoleExample example);
int updateByExample(@Param("record") UserRole record, @Param("example") UserRoleExample example);
int updateByPrimaryKeySelective(UserRole record);
int updateByPrimaryKey(UserRole record);
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bigsys.auth.project.db.dao.UserRoleMapper">
<resultMap id="BaseResultMap" type="com.bigsys.auth.project.db.model.UserRole">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="role" jdbcType="VARCHAR" property="role" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, username, role
</sql>
<select id="selectByExample" parameterType="com.bigsys.auth.project.db.model.UserRoleExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from bigsys_user_role
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from bigsys_user_role
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from bigsys_user_role
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.bigsys.auth.project.db.model.UserRoleExample">
delete from bigsys_user_role
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.bigsys.auth.project.db.model.UserRole">
insert into bigsys_user_role (id, username, role
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{role,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.bigsys.auth.project.db.model.UserRole">
insert into bigsys_user_role
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="role != null">
role,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="role != null">
#{role,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.bigsys.auth.project.db.model.UserRoleExample" resultType="java.lang.Long">
select count(*) from bigsys_user_role
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update bigsys_user_role
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.username != null">
username = #{record.username,jdbcType=VARCHAR},
</if>
<if test="record.role != null">
role = #{record.role,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update bigsys_user_role
set id = #{record.id,jdbcType=INTEGER},
username = #{record.username,jdbcType=VARCHAR},
role = #{record.role,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.bigsys.auth.project.db.model.UserRole">
update bigsys_user_role
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="role != null">
role = #{role,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.bigsys.auth.project.db.model.UserRole">
update bigsys_user_role
set username = #{username,jdbcType=VARCHAR},
role = #{role,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
package com.bigsys.auth.project.db.model;
import com.bigsys.auth.project.service.WrapperRole;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class User {
public class User implements WrapperRole{
private String id;
private String username;
private String name;
private String passward;
......@@ -19,6 +24,8 @@ public class User {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
private List<String> roleIds = new ArrayList<>();
public String getId() {
return id;
}
......@@ -27,6 +34,14 @@ public class User {
this.id = id == null ? null : id.trim();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getName() {
return name;
}
......@@ -66,4 +81,12 @@ public class User {
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public List<String> getRoleIds() {
return roleIds;
}
public void setRoleIds(List<String> roleIds) {
this.roleIds = roleIds;
}
}
\ No newline at end of file
......@@ -175,6 +175,76 @@ public class UserExample {
return (Criteria) this;
}
public Criteria andUsernameIsNull() {
addCriterion("username is null");
return (Criteria) this;
}
public Criteria andUsernameIsNotNull() {
addCriterion("username is not null");
return (Criteria) this;
}
public Criteria andUsernameEqualTo(String value) {
addCriterion("username =", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotEqualTo(String value) {
addCriterion("username <>", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThan(String value) {
addCriterion("username >", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
addCriterion("username >=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThan(String value) {
addCriterion("username <", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThanOrEqualTo(String value) {
addCriterion("username <=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLike(String value) {
addCriterion("username like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotLike(String value) {
addCriterion("username not like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameIn(List<String> values) {
addCriterion("username in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameNotIn(List<String> values) {
addCriterion("username not in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameBetween(String value1, String value2) {
addCriterion("username between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsernameNotBetween(String value1, String value2) {
addCriterion("username not between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
......
package com.bigsys.auth.project.db.model;
public class UserRole {
private Integer id;
private String username;
private String role;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role == null ? null : role.trim();
}
}
\ No newline at end of file
......@@ -18,4 +18,11 @@ public interface RoleService extends BaseService<String, Role, RoleExample, Role
* @param id
*/
void deleteRole(String id);
/**
* 获取给定roleId下面的所有子角色
* @param roleId
* @return
*/
List<Role> getSubRoles(String roleId);
}
package com.bigsys.auth.project.service;
import com.bigsys.auth.project.db.model.UserRole;
import com.bigsys.auth.project.db.model.UserRoleExample;
import com.bigsys.auth.project.util.service.BaseService;
import java.util.List;
public interface UserRoleService extends BaseService<Integer, UserRole, UserRoleExample, UserRoleExample.Criteria> {
/**
* 为用户包裹上用户对应的角色信息
* @param list
*/
void wrapperRoles(List<? extends WrapperRole> list);
/**
* 通过用户名称获取用户对应的角色
* @param username
* @return
*/
List<UserRole> getUserRoles(String username);
/**
* 根据角色id查询有该角色id的用户
* @param roleIds
* @return
*/
List<UserRole> getUserRoles(List<String> roleIds);
}
......@@ -9,6 +9,12 @@ public interface UserService extends BaseService<String, User, UserExample, User
void addOrUpdate(User model);
/**
* 根据当前登录人角色返回对应的角色下的用户
* @param condition
* @param pager
* @return
*/
PageInfo<User> page(User condition, PageInfo<User> pager);
User getUser(String username);
......
package com.bigsys.auth.project.service;
import java.util.List;
public interface WrapperRole {
void setRoleIds(List<String> roleIds);
String getUsername();
}
......@@ -51,6 +51,20 @@ public class RoleServiceImpl extends BaseServiceImpl<String, Role, RoleExample,
doDeleteRole(id);
}
@Override
public List<Role> getSubRoles(String roleId) {
List<Role> roles = new ArrayList<>();
roles = selectByExample((a, b) -> {
b.andParentIdEqualTo(roleId);
});
List<Role> subSubRoles = new ArrayList<>();
for (Role role : roles) {
subSubRoles.addAll(getSubRoles(role.getId()));
}
roles.addAll(subSubRoles);
return roles;
}
private void doDeleteRole(String id) {
List<Role> subRoles = selectByExample((a, b) -> {
b.andParentIdEqualTo(id);
......
package com.bigsys.auth.project.service.impl;
import com.bigsys.auth.project.db.dao.UserRoleMapper;
import com.bigsys.auth.project.db.model.UserRole;
import com.bigsys.auth.project.db.model.UserRoleExample;
import com.bigsys.auth.project.service.WrapperRole;
import com.bigsys.auth.project.service.UserRoleService;
import com.bigsys.auth.project.util.service.BaseServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@Service("userRoleService")
public class UserRoleServiceImpl extends BaseServiceImpl<Integer, UserRole, UserRoleExample, UserRoleExample.Criteria> implements UserRoleService{
@Resource
private UserRoleMapper userRoleMapper;
@Override
public Object getDao() {
return userRoleMapper;
}
@Override
public Class getExample() {
return UserRoleExample.class;
}
@Override
public void wrapperRoles(List<? extends WrapperRole> list) {
for (WrapperRole wrapperRole : list) {
List<UserRole> userRoles = selectByExample((a, b) -> {
b.andUsernameEqualTo(wrapperRole.getUsername());
});
wrapperRole.setRoleIds(userRoles.stream().map(userRole -> userRole.getRole()).collect(Collectors.toList()));
}
}
@Override
public List<UserRole> getUserRoles(String username) {
List<UserRole> userRoles = selectByExample((a, b) -> {
b.andUsernameEqualTo(username);
});
return userRoles;
}
@Override
public List<UserRole> getUserRoles(List<String> roleIds) {
List<UserRole> userRoles = selectByExample((a, b) -> {
b.andRoleIn(roleIds);
});
return userRoles;
}
}
package com.bigsys.auth.project.service.impl;
import com.bigsys.auth.project.db.dao.UserMapper;
import com.bigsys.auth.project.db.model.Role;
import com.bigsys.auth.project.db.model.User;
import com.bigsys.auth.project.db.model.UserExample;
import com.bigsys.auth.project.db.model.UserRole;
import com.bigsys.auth.project.service.RoleService;
import com.bigsys.auth.project.service.UserRoleService;
import com.bigsys.auth.project.service.UserService;
import com.bigsys.auth.project.util.UUIDGenarator;
import com.bigsys.auth.project.util.service.BaseServiceImpl;
import com.github.pagehelper.PageInfo;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<String, User, UserExample, UserExample.Criteria> implements UserService {
......@@ -21,6 +29,12 @@ public class UserServiceImpl extends BaseServiceImpl<String, User, UserExample,
@Resource
private UserMapper userMapper;
@Resource
private UserRoleService userRoleService;
@Resource
private RoleService roleService;
@Override
public Object getDao() {
return userMapper;
......@@ -43,20 +57,38 @@ public class UserServiceImpl extends BaseServiceImpl<String, User, UserExample,
} else {
userMapper.updateByPrimaryKeySelective(model);
}
userRoleService.deleteByExample((a, b) -> {
b.andUsernameEqualTo(model.getUsername());
});
for (String roleId : model.getRoleIds()) {
UserRole userRole = new UserRole();
userRole.setUsername(model.getUsername());
userRole.setRole(roleId);
userRoleService.insert(userRole);
}
}
@Override
public PageInfo<User> page(User condition, PageInfo<User> pager) {
User curUser = (User) SecurityUtils.getSubject().getPrincipal();
List<UserRole> userRoles = userRoleService.getUserRoles(curUser.getUsername());
List<Role> subRoles = new ArrayList<>();
for (UserRole userRole : userRoles) {
subRoles.addAll(roleService.getSubRoles(userRole.getRole()));
}
List<UserRole> subUserRoles = userRoleService.getUserRoles(subRoles.stream().map(subRole -> subRole.getId()).collect(Collectors.toList()));
pager = selectByExampleAndPage(pager, (example, criteria) -> {
example.setOrderByClause("name asc");
example.setOrderByClause("updateTime desc");
criteria.andUsernameIn(subUserRoles.stream().map(subUserRole -> subUserRole.getUsername()).collect(Collectors.toList()));
});
userRoleService.wrapperRoles(pager.getList());
return pager;
}
@Override
public User getUser(String username) {
List<User> users = selectByExample((a, b) -> {
b.andNameLike(username);
b.andUsernameEqualTo(username);
});
return users.get(0);
}
......
......@@ -5,6 +5,8 @@ import java.util.HashMap;
public class BSResponse extends HashMap{
private static final String OK = "OK";
private static final String FAIL = "FAIL";
private static final String NEEDLOGIN = "NEEDLOGIN";
public static BSResponse ok() {
BSResponse bsResponse = new BSResponse();
......@@ -22,8 +24,15 @@ public class BSResponse extends HashMap{
public static BSResponse error(String msg) {
BSResponse bsResponse = new BSResponse();
bsResponse.put("status", OK);
bsResponse.put("error", msg);
bsResponse.put("status", FAIL);
bsResponse.put("msg", msg);
return bsResponse;
}
public static BSResponse needLogin(String msg) {
BSResponse bsResponse = new BSResponse();
bsResponse.put("status", NEEDLOGIN);
bsResponse.put("msg", msg);
return bsResponse;
}
......
......@@ -50,9 +50,12 @@
<!--<table tableName="bigsys_user" domainObjectName="User">-->
<!--<property name="useActualColumnNames" value="true"/>-->
<!--</table>-->
<table tableName="bigsys_role_menu" domainObjectName="RoleMenu">
<table tableName="bigsys_user_role" domainObjectName="UserRole">
<property name="useActualColumnNames" value="true"/>
</table>
<!--<table tableName="bigsys_role_menu" domainObjectName="RoleMenu">-->
<!--<property name="useActualColumnNames" value="true"/>-->
<!--</table>-->
<!--<table tableName="sub_line" domainObjectName="SubLine">-->
<!--<property name="useActualColumnNames" value="true"/>-->
<!--<columnOverride column="createTime" javaType="String"></columnOverride>-->
......
import axios from 'axios'
import querystring from 'querystring'
import router from '../router'
axios.interceptors.response.use(
response => {
console.log('打印响应。。')
if (response.data.status === 'NEEDLOGIN') {
alert(response.data.msg)
router.push({ path: '/login' })
}
return response
},
error => {
if (error.response) {
}
return Promise.reject(error.response.data) // 返回接口返回的错误信息
})
export default {
login (data) {
......
<template>
<el-menu :default-active="activeIndex2" class="el-menu-demo navbar" style="position: fixed; left: 180px; right: 0px; z-index: 10000;" mode="horizontal" @select="handleSelect">
<el-submenu index="1" style="float: right;">
<template slot="title">{{username}}</template>
<router-link to="/login"><el-menu-item index="2-1">退出</el-menu-item></router-link>
<el-menu-item index="2-2" @click="editPwd">修改密码</el-menu-item>
<el-menu :default-active='activeIndex2' class='el-menu-demo navbar'
style='position: fixed; left: 180px; right: 0px; z-index: 10000;' mode='horizontal'>
<el-submenu index='1' style='float: right;'>
<template slot='title'>{{username}}</template>
<el-menu-item index='2-1' @click='exit()'>退出</el-menu-item>
<el-menu-item index='2-2' @click='editPwd'>修改密码</el-menu-item>
</el-submenu>
</el-menu>
</template>
......@@ -22,11 +23,24 @@
}
},
methods: {
handleSelect (key, keyPath) {
console.log(key, keyPath)
exit () {
this.set('MySessionId', '1111', -1)
this.$router.push({ path: '/login' })
},
editPwd () {
// this.$store.dispatch('GET_MENUS')
},
set: function (name, value, days) {
var d = new Date()
d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days)
window.document.cookie = name + '=' + value + ';path=/;expires=' + d.toGMTString()
},
get: function (name) {
var v = window.document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)')
return v ? v[2] : null
},
delete: function (name) {
this.set(name, '', -1)
}
}
}
......
......@@ -10,7 +10,6 @@
:expand-on-click-node="false"
:render-content="renderContent">
</el-tree>
<el-button @click="getCheckedNodes">测试</el-button>
<el-dialog
title="编辑角色访问权限"
:visible.sync="dialogVisible"
......
......@@ -16,8 +16,12 @@
:data="tdata"
stripe
style="width: 100%">
<el-table-column prop="name"
<el-table-column prop="username"
label="用户名"
:width="100">
</el-table-column>
<el-table-column prop="name"
label="昵称"
:width="180">
</el-table-column>
<el-table-column prop="phone"
......@@ -63,12 +67,12 @@
<el-input v-model="formLabelAlign.phone" @keyup.enter.native="saveUser"></el-input>
</el-form-item>
<el-form-item label="角色">
<el-select v-model="formLabelAlign.roleId" @click.native="selectRole" multiple placeholder="请选择">
<el-select v-model="formLabelAlign.roleIds" @visible-change="selectRole" multiple placeholder="请选择">
<el-option style="display: none"
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
:key="item.id"
:label="item.name"
:value="item.id">
</el-option>
</el-select>
</el-form-item>
......@@ -92,7 +96,7 @@
</el-tree>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogRoleVisible = false">取 消</el-button>
<el-button type="primary" @click="saveUser()">确 定</el-button>
<el-button type="primary" @click="dialogRoleVisible = false">确 定</el-button>
</div>
</el-dialog>
</div>
......@@ -147,40 +151,66 @@
username: '',
name: '',
phone: '',
roleId: []
roleIds: []
}
}
},
methods: {
checkParentIsCheck (data) {
var roleMap = {}
this.options.forEach((option) => {
roleMap[option.id] = option
})
if (this.formLabelAlign.roleIds.indexOf(data.parentId) !== -1) {
return true
} else {
if (data.parentId) {
return this.checkParentIsCheck(roleMap[data.parentId])
} else {
return false
}
}
},
checkChildrenIsCheck (data) {
var roleMap = {}
this.options.forEach((option) => {
roleMap[option.id] = option
})
for (let i = 0; i < data.roles.length; i++) {
var subRole = data.roles[i]
if (this.formLabelAlign.roleIds.indexOf(subRole.id) !== -1) {
return true
}
if (subRole.roles.length > 0 && this.checkChildrenIsCheck(subRole)) {
return true
}
}
return false
},
addRole (data, isCheck, subDatas) {
console.log(subDatas)
// checkParentIsCheck(data)
// checkChildrenIsCheck(data)
if ((this.checkParentIsCheck(data) || this.checkChildrenIsCheck(data)) && isCheck) {
alert('有父角色或子角色已被选中,若要添加当前角色请取消其他选中角色')
setTimeout(() => {
var keys = this.$refs.role.getCheckedKeys()
keys.remove(data.id)
this.$refs.role.setCheckedKeys(keys)
})
return
}
if (isCheck) {
this.formLabelAlign.roleId.push(data.id)
this.formLabelAlign.roleIds.push(data.id)
} else {
this.formLabelAlign.roleId.remove(data.id)
this.formLabelAlign.roleIds.remove(data.id)
}
},
selectRole () {
axios.get('/api/role/getRole').then((response) => {
this.role = response.data.data
this.options = []
var addOptions = (role) => {
role.forEach((item) => {
this.options.push({label: item.name, value: item.id})
if (item.roles.length > 0) {
addOptions(item.roles)
}
})
}
addOptions(this.role)
console.log(this.options)
selectRole (isDown) {
if (isDown) {
this.dialogRoleVisible = true
setTimeout(() => {
this.$refs.role.setCheckedKeys(this.formLabelAlign.roleId)
this.$refs.role.setCheckedKeys(this.formLabelAlign.roleIds)
})
})
}
},
initData () {
console.log('初始化数据中。。。')
......@@ -213,8 +243,22 @@
this.formLabelAlign.username = ''
this.formLabelAlign.name = ''
this.formLabelAlign.phone = ''
this.formLabelAlign.roleId = []
this.formLabelAlign.roleIds = []
this.dialogFormVisible = true
axios.get('/api/role/getRole').then((response) => {
this.role = response.data.data
this.options = []
var addOptions = (role) => {
role.forEach((item) => {
this.options.push(item)
if (item.roles.length > 0) {
addOptions(item.roles)
}
})
}
addOptions(this.role)
console.log(this.options)
})
},
modifyUser: function (user) {
this.title = '修改用户'
......@@ -222,8 +266,22 @@
this.formLabelAlign.username = user.username
this.formLabelAlign.name = user.name
this.formLabelAlign.phone = user.phone
this.formLabelAlign.roleId = user.roleId
this.formLabelAlign.roleIds = user.roleIds
this.dialogFormVisible = true
axios.get('/api/role/getRole').then((response) => {
this.role = response.data.data
this.options = []
var addOptions = (role) => {
role.forEach((item) => {
this.options.push(item)
if (item.roles.length > 0) {
addOptions(item.roles)
}
})
}
addOptions(this.role)
console.log(this.options)
})
},
deleteUser (id) {
this.$store.dispatch('DELETE_USER', id).then((response) => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment