码迷,mamicode.com
首页 > 其他好文 > 详细

在realm中动态查询用户的权限&角色

时间:2017-08-26 22:14:34      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:pager   smi   md5   分享   dht   lvg   fbi   名称   ddb   

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("struts-default")
@Results({ @Result(name = "login", location = "/login.jsp"),
        @Result(name = "index", type = "redirect", location = "/index.jsp"),
        @Result(name = "list", type = "redirect", location = "/pages/system/user.jsp"), })
public class UserAction extends BaseAction<User> {

    @Autowired
    private UserService userService;

    // 接收验证码
    private String checkCode;

    public void setCheckCode(String checkCode) {
        this.checkCode = checkCode;
    }

    /**
     * @Description: 基于shiro实现登陆(认证)
     * @return
     * @throws Exception
     * 
     */
    @Action("userAction_login")
    public String login() throws Exception {
        // if(StringUtils.isNotBlank(model.getUsername())&&
        // StringUtils.isNoneBlank(model.getPassword())&&StringUtils.isNotBlank(checkCode)){
        // //判断验证码
        // String realCheckCode = (String)
        // ServletActionContext.getRequest().getSession().getAttribute("key");
        // if(checkCode.equals(realCheckCode)){
        // 相等,开始通过shiro实现认证
        // 通过工具类获取subject对象
        Subject subject = SecurityUtils.getSubject(); // 当前“用户”,未认证状态
        // 创建认证令牌; 封装页面提交用户名,密码
        AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), Md5Util.encode(model.getPassword()));
        ;
        // logion方法调用安全管理器;
        try {
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 认证失败
            return "login";
        }
        // 认证通过
        // 从主角中获取用户信息,将用户的信息存Session中
        User user = (User) subject.getPrincipal();
        ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
        return "index";
        // }
        // }else{
        // return "login";
        // }
        // return super.execute();
    }

    // 属性驱动接收页面提交角色id
    private Integer[] roleIds;

    public void setRoleIds(Integer[] roleIds) {
        this.roleIds = roleIds;
    }

    // 保存用户,用户关联角色
    @Action("userAction_save")
    public String save() throws Exception {
        userService.save(model, roleIds);
        return "list";
    }

    // 用户分页查询
    @Action("userAction_pageQuery")
    public String pageQuery() {
        Pageable pageable = new PageRequest(page-1, rows);
        Page<User> page = userService.findAll(pageable);
        this.java2Json(page, new String[]{"roles"});
        return null;
    }

}

 

 

 

/**
 * @Description: 安全管理器最终调用realm,进行访问安全数据
 *
 * @Title: BosRealm.java
 */
public class BosRealm extends AuthorizingRealm{
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private PermissionDao permissionDao;
    
    @Autowired
    private RoleDao roleDao;
    /**
      * @Description: 
      * @param token subject.login方法中传 用户名密码令牌
      * @return 
    */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("开始认证");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //页面输入的用户名
        //根据用户名查询数据库中真实密码
        String username = usernamePasswordToken.getUsername();
        User user = userDao.findByUsername(username);
        if(user==null){
            //用户名输出错误
            return null;  //当此方法中返回null,shiro会抛出异常 :未知账户异常
        }
        //比对密码工作交给shiro框架
        //p1:主角  p2:令牌/真实密码  p3:当前realm名称
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        return info;
    }


/*    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("开始授权");
        //TODO 后期改造查询数据库中对应的权限,角色
        //返回简单授权信息:包含当前用户有的权限点;角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加用户权限
        info.addStringPermission("standard_page");
        info.addStringPermission("courier_delete");
        //添加用户角色
        info.addRole("admin");
        return info;
    }*/

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        List<Permission> permissionList = new ArrayList<>();
        List<Role> roleList = new ArrayList<>();
        System.out.println("开始授权");
        //返回简单授权信息:包含当前用户有的权限点;角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //如果系统内置账户:管理员账户,有所有的权限以及角色
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if(user.getUsername().equals("admin")){
            permissionList = permissionDao.findAll();
            roleList = roleDao.findAll();
        }else{
            //根据用户ID进行查询
            permissionList = permissionDao.findByUserId(user.getId());
            roleList = roleDao.findByUserId(user.getId());
        }
        
        //添加用户权限
        for (Permission permission : permissionList) {
            info.addStringPermission(permission.getKeyword());
        }
        //添加用户角色
        for (Role role : roleList) {
            info.addRole(role.getKeyword());
        }
        return info;
    }
    
}

 

 

技术分享

 

 

 

 

 

public interface RoleDao extends JpaRepository<Role, Integer> {

    @Query("select r from Role r inner join r.users u where u.id=?")
    List<Role> findByUserId(Integer userId);

}

 

 

 

 

public interface PermissionDao extends JpaRepository<Permission, Integer> {

    /**
     * select distinct p.*
        from t_permission p 
        inner join t_role_permission rp on rp.c_permission_id = p.c_id
        inner join t_role r on  rp.c_role_id = r.c_id
        inner join t_user_role ur on ur.c_role_id = r.c_id
        inner join t_user u on ur.c_user_id = u.c_id
        where u.c_id = 52;
     */
    @Query("select distinct p from Permission p inner join p.roles r inner join r.users u where u.id = ?")
    List<Permission> findByUserId(Integer userId);

}

 

 技术分享

 

/**
 * @description:后台用户
 */
@Entity
@Table(name = "T_USER")
public class User implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Integer id; // 主键
    @Column(name = "C_BIRTHDAY")
    private Date birthday; // 生日
    @Column(name = "C_GENDER")
    private String gender; // 性别
    @Column(name = "C_PASSWORD")
    private String password; // 密码
    @Column(name = "C_REMARK")
    private String remark; // 备注
    @Column(name = "C_STATION")
    private String station; // 状态
    @Column(name = "C_TELEPHONE")
    private String telephone; // 联系电话
    @Column(name = "C_USERNAME", unique = true)
    private String username; // 登陆用户名
    @Column(name = "C_NICKNAME")
    private String nickname; // 真实姓名

    @ManyToMany(fetch=FetchType.EAGER) //为了页面展示角色信息,设置立即加载
    @JoinTable(name = "T_USER_ROLE", joinColumns = {
            @JoinColumn(name = "C_USER_ID", referencedColumnName = "C_ID") }, inverseJoinColumns = {
                    @JoinColumn(name = "C_ROLE_ID", referencedColumnName = "C_ID") })
    private Set<Role> roles = new HashSet<Role>(0);

    public String getRoleString(){
        String roleStrings = "";
        for (Role role : roles) {
            roleStrings+=role.getName() + " ";
        }
        return roleStrings;
    }
    
    public String getBirthdayString(){
        if(birthday!=null){
            return new SimpleDateFormat("yyyy-MM-dd").format(birthday);
        }
        return "暂无数据";
    }
    
......

 

 

 

 

/**
 * @description:角色
 */
@Entity
@Table(name = "T_ROLE")
public class Role implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Integer id;
    @Column(name = "C_NAME")
    private String name; // 角色名称
    @Column(name = "C_KEYWORD")
    private String keyword; // 角色关键字,用于权限控制
    @Column(name = "C_DESCRIPTION")
    private String description; // 描述

    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<User>(0);

    @ManyToMany
    @JoinTable(name = "T_ROLE_PERMISSION", joinColumns = {
            @JoinColumn(name = "C_ROLE_ID", referencedColumnName = "C_ID") }, inverseJoinColumns = {
                    @JoinColumn(name = "C_PERMISSION_ID", referencedColumnName = "C_ID") })
    private Set<Permission> permissions = new HashSet<Permission>(0);

    @ManyToMany
    @JoinTable(name = "T_ROLE_MENU", joinColumns = {
            @JoinColumn(name = "C_ROLE_ID", referencedColumnName = "C_ID") }, inverseJoinColumns = {
                    @JoinColumn(name = "C_MENU_ID", referencedColumnName = "C_ID") })
    private Set<Menu> menus = new HashSet<Menu>(0);

......

 

 

 

/**
 * @description:权限名称
 */
@Entity
@Table(name = "T_PERMISSION")
public class Permission implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Integer id;
    @Column(name = "C_NAME")
    private String name; // 权限名称
    @Column(name = "C_KEYWORD")
    private String keyword; // 权限关键字,用于权限控制
    @Column(name = "C_DESCRIPTION")
    private String description; // 描述

    @ManyToMany(mappedBy = "permissions")
    private Set<Role> roles = new HashSet<Role>(0);

......

 

 

 

 

/**
 * @description:菜单
 */
@Entity
@Table(name = "T_MENU")
public class Menu implements Serializable{
    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Integer id;
    @Column(name = "C_NAME")
    private String name; // 菜单名称
    @Column(name = "C_PAGE")
    private String page; // 访问路径
    @Column(name = "C_PRIORITY")
    private Integer priority; // 优先级
    @Column(name = "C_DESCRIPTION")
    private String description; // 描述

    @ManyToMany(mappedBy = "menus")
    private Set<Role> roles = new HashSet<Role>(0);

    @OneToMany(mappedBy = "parentMenu", fetch=FetchType.EAGER)  //EAGER立即加载集合
    private Set<Menu> childrenMenus = new HashSet<Menu>();  //存放当前菜单下级菜单

    @ManyToOne
    @JoinColumn(name = "C_PID")
    private Menu parentMenu;  //当前菜单上级菜单;外键字段
    
    /**
     * combotree 展示文本内容
     */
    public String getText(){
        return name;
    }
    
    /**
      * @Description: 返回json数据中 包含children  children:[]
      * @return
      *      
     */
    public Set<Menu> getChildren(){
        return childrenMenus;
    }
    
    /**
     * 返回ztree数据,父节点数据的id
     * 
     */
    public Integer getpId(){
        if(parentMenu!=null){
            return parentMenu.getId();
        }
        return 0;
    }
    
......

 

在realm中动态查询用户的权限&角色

标签:pager   smi   md5   分享   dht   lvg   fbi   名称   ddb   

原文地址:http://www.cnblogs.com/javaxiaoxin/p/7436443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!