美文网首页
权限(SSH项目-bos系统实战)

权限(SSH项目-bos系统实战)

作者: gaookey | 来源:发表于2020-06-08 16:58 被阅读0次

Apache Shiro入门

1591606534766.jpg

建表 sql 语句

/\*==============================================================\*/
/\* DBMS name:      MySQL 5.0                                    */
/\* Created on:     2018/5/13 21:47:37                           */
/*==============================================================*/


drop table if exists auth_function;

drop table if exists auth_role;

drop table if exists role_function;

/\*drop table if exists t_user;\*/

drop table if exists user_role;

/\*==============================================================\*/
/\* Table: auth_function                                         */
/*==============================================================*/
create table auth_function
(
   id                   varchar(32) not null,
   name                 varchar(255),
   code                 varchar(255),
   description          varchar(255),
   page                 varchar(255),
   generatemenu         varchar(255),
   zindex               int,
   pid                  varchar(32),
   primary key (id),
   key AK\_Key\_2 (name)
);

/\*==============================================================\*/
/\* Table: auth_role                                             */
/*==============================================================*/
create table auth_role
(
   id                   varchar(32) not null,
   name                 varchar(255),
   code                 varchar(255),
   description          varchar(255),
   primary key (id),
   key AK\_Key\_2 (name)
);

/\*==============================================================\*/
/\* Table: role_function                                         */
/*==============================================================*/
create table role_function
(
   role_id              varchar(32) not null,
   function_id          varchar(32) not null,
   primary key (role\_id, function\_id)
);

/\*==============================================================\*/
/\* Table: t_user                                                */
/*==============================================================
create table t_user
(
   id                   varchar(32) not null,
   username             varchar(20),
   password             varchar(32),
   salary               double,
   birthday             date,
   gender               varchar(10),
   station              varchar(40),
   telephone            varchar(11),
   remark               varchar(255),
   primary key (id)
);\*/

/\*==============================================================\*/
/\* Table: user_role                                             */
/*==============================================================*/
create table user_role
(
   user_id              varchar(32) not null,
   role_id              varchar(32) not null,
   primary key (user\_id, role\_id)
);

alter table auth\_function add constraint FK\_Reference_1 foreign key (pid)
      references auth_function (id) on delete restrict on update restrict;

alter table role\_function add constraint FK\_Reference\_2 foreign key (function\_id)
      references auth_function (id) on delete restrict on update restrict;

alter table role\_function add constraint FK\_Reference\_3 foreign key (role\_id)
      references auth_role (id) on delete restrict on update restrict;

alter table user\_role add constraint FK\_Reference\_4 foreign key (user\_id)
      references t_user (id) on delete restrict on update restrict;

alter table user\_role add constraint FK\_Reference\_5 foreign key (role\_id)
      references auth_role (id) on delete restrict on update restrict;

auth_function

package com.gwl.bos.model;

import java.util.HashSet;
import java.util.Set;

public class Function {
    private String id;
    private String name;
    private String code;
    private String description;
    private String page;
    private String generatemenu;
    private Integer zindex;

    private String pId;
    private Function function;
    private Set<Function> functions = new HashSet<>(0);
    private Set<Role> roles = new HashSet(0);

    public String getpId() {
        if (function != null) {
            return function.getId();
        }
        return "0";
    }

    public void setpId(String pId) {
        this.pId = pId;
    }

    public Function getFunction() {
        return function;
    }

    public void setFunction(Function function) {
        this.function = function;
    }

    public Set<Function> getFunctions() {
        return functions;
    }

    public void setFunctions(Set<Function> functions) {
        this.functions = functions;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public String getGeneratemenu() {
        return generatemenu;
    }

    public void setGeneratemenu(String generatemenu) {
        this.generatemenu = generatemenu;
    }

    public Integer getZindex() {
        return zindex;
    }

    public void setZindex(Integer zindex) {
        this.zindex = zindex;
    }
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.gwl.bos.model.Function" table="auth_function" schema="bos">
        <id name="id" column="id">
            <generator class="uuid"></generator>
        </id>
        <property name="name" column="name"/>
        <property name="code" column="code"/>
        <property name="description" column="description"/>
        <property name="page" column="page"/>
        <property name="generatemenu" column="generatemenu"/>
        <property name="zindex" column="zindex"/>

        <many-to-one name="function" class="com.gwl.bos.model.Function" fetch="select">
            <column name="pid" length="32"/>
        </many-to-one>

        <set name="roles" inverse="true" table="role_function">
            <key>
                <column name="function_id" length="32" not-null="true"/>
            </key>
            <many-to-many entity-name="com.gwl.bos.model.Role">
                <column name="role_id" length="32" not-null="true"/>
            </many-to-many>
        </set>
        <set name="functions" inverse="true">
            <key>
                <column name="pid" length="32"/>
            </key>
            <one-to-many class="com.gwl.bos.model.Function"/>
        </set>

    </class>
</hibernate-mapping>

auth_role

package com.gwl.bos.model;

import java.util.HashSet;
import java.util.Set;

public class Role {
    private String id;
    private String name;
    private String code;
    private String description;

    private Set<User> users = new HashSet(0);
    private Set<Function> functions = new HashSet(0);

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    public Set<Function> getFunctions() {
        return functions;
    }

    public void setFunctions(Set<Function> functions) {
        this.functions = functions;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.gwl.bos.model.Role" table="auth_role" schema="bos">
        <id name="id" column="id">
            <generator class="uuid"></generator>
        </id>
        <property name="name" column="name"/>
        <property name="code" column="code"/>
        <property name="description" column="description"/>

        <set name="users" inverse="true" table="user_role">
            <key>
                <column name="role_id" length="32" not-null="true"/>
            </key>
            <many-to-many entity-name="com.gwl.bos.model.User">
                <column name="user_id" length="32" not-null="true"/>
            </many-to-many>
        </set>
        <set name="functions" table="role_function">
            <key>
                <column name="role_id" length="32" not-null="true"/>
            </key>
            <many-to-many entity-name="com.gwl.bos.model.Function">
                <column name="function_id" length="32" not-null="true"/>
            </many-to-many>
        </set>

    </class>
</hibernate-mapping>

t_user

package com.gwl.bos.model;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class User {
    private String id;
    private String username;
    private String password;
    private Double salary;
    private Date birthday;
    private String gender;
    private String station;
    private String telephone;
    private String remark;

    private Set<Role> roles = new HashSet<Role>();

    public String getBirthdayStr() {
        if (birthday == null) {
            return "";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(birthday);
        return format;
    }

    public String getRolesStr() {
        String str = "";
        for (Role role : roles) {
            str += role.getName() + "、";
        }
        return str;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public User() {
    }

    public User(String username) {
        this.username = username;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getStation() {
        return station;
    }

    public void setStation(String station) {
        this.station = station;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.gwl.bos.model.User" table="t_user">
        <id name="id" column="id">
            <generator class="uuid"></generator>
        </id>
        <property name="username" column="username"/>
        <property name="password" column="password"/>
        <property name="salary" column="salary"/>
        <property name="birthday" column="birthday"/>
        <property name="gender" column="gender"/>
        <property name="station" column="station"/>
        <property name="telephone" column="telephone"/>
        <property name="remark" column="remark"/>

        <!--配置用户与角色的多对多-->
        <set name="roles" lazy="false" table="user_role">
            <key>
                <column name="user_id" length="32" not-null="true"/>
            </key>
            <many-to-many entity-name="com.gwl.bos.model.Role">
                <column name="role_id" length="32" not-null="true"/>
            </many-to-many>
        </set>

    </class>
</hibernate-mapping>

通过用户id查找权限

sql语句

#通过用户id查找权限 (第一种方式)(SELECT DISTINCT:仅选取唯一不同的值)
SELECT af.id, af.name, af.page, af.code
FROM auth_function af
LEFT OUTER JOIN role_function rf
ON rf.function_id = af.id
LEFT OUTER JOIN auth_role ar
ON rf.role_id = ar.id
LEFT OUTER JOIN user_role ur
ON ar.id = ur.role_id
WHERE ur.user_id = '4028e4216bf8cebb016bf8cf71980000';

#通过用户id查找权限 (第二种方式)
SELECT af.id, af.name, af.page, af.code
FROM
auth\_function af, role\_function rf, auth\_role ar, user\_role ur
WHERE
rf.function_id = af.id AND 
rf.role_id = ar.id AND
ar.id = ur.role_id AND
ur.user_id = '4028e4216bf8cebb016bf8cf71980000';

java

package com.gwl.bos.dao.impl;

import com.gwl.bos.dao.FunctionDao;
import com.gwl.bos.dao.base.BaseDaoImpl;
import com.gwl.bos.model.Function;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class FunctionDaoImpl extends BaseDaoImpl<Function> implements FunctionDao {

    @Override
    public List<Function> findFunctionsByUserId(String userId) {

        String sql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles r LEFT OUTER JOIN r.users u WHERE u.id = :userId";
        SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(sql);
        query.setParameter("userId", userId);
        List<Function> functions = query.list();
        return functions;

        /*
        List<Function> functions = new ArrayList<>();

        Set<Role> roles = (Set<Role>) hibernateTemplate.get(User.class, userId).getRoles();

        for (Role r : roles) {
            Set<Function> f = (Set<Function>) r.getFunctions();
            for (Function fun : f) {
                functions.add(fun);
            }
        }
        return functions;
        */
        
        /*
        String sql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles r LEFT OUTER JOIN r.users u WHERE u.id = ?0";
        return (List<Function>) hibernateTemplate.find(sql, userId);
        */
    }

    @Override
    public List<Function> findMenuByUserId(String userId) {

        String sql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles r LEFT OUTER JOIN r.users u WHERE u.id = :userId AND f.generatemenu = '1' order by f.zindex desc";
        SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(sql);
        query.setParameter("userId", userId);
        List<Function> functions = query.list();
        return functions;

        /*
        String sql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles r LEFT OUTER JOIN r.users u WHERE u.id = ?0 AND f.generatemenu = '1' order by f.zindex desc";
        return (List<Function>) hibernateTemplate.find(sql, userId);
        */
    }

    @Override
    public List<Function> findAllMenu() {

        String sql = "SELECT DISTINCT f FROM Function f WHERE f.generatemenu = '1' order by f.zindex desc";
        SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(sql);
        List<Function> functions = query.list();
        return functions;

        /*
        String sql = "SELECT DISTINCT f FROM Function f WHERE f.generatemenu = '1' order by f.zindex desc";
        return (List<Function>) hibernateTemplate.find(sql);
        */
    }
}

Realm

package com.gwl.bos.web.realm;

import com.gwl.bos.dao.FunctionDao;
import com.gwl.bos.dao.UserDao;
import com.gwl.bos.model.Function;
import com.gwl.bos.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class BosRealm extends AuthorizingRealm {

    @Autowired
    private FunctionDao functionDao;

    /**
     * 权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User loginUser = (User) principalCollection.getPrimaryPrincipal();

        List<Function> functions = null;

        if (loginUser.getUsername().equals("admin")) {
            //获取全部权限
            functions = functionDao.get();
        } else {
            functionDao.findFunctionsByUserId(loginUser.getId());
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        for (Function function : functions) {
            info.addStringPermission(function.getCode());
        }
        return info;
    }

    @Autowired
    private UserDao userDao;

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userDao.findByUsername(token.getUsername());

        if (user != null) {

            /**
             * Object principal  数据库查询的对象
             * Object credentials  查询出来的密码,自动验证
             * String realmName  当前类名
             */
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this
                    .getClass().getSimpleName());

            return info;
        }

        return null;
    }
}

相关文章

网友评论

      本文标题:权限(SSH项目-bos系统实战)

      本文链接:https://www.haomeiwen.com/subject/njwrtktx.html