NutzBook - 为Shiro做准备

NutzBook - 为Shiro做准备

Tags: Nutz

摘要

NutzBook - 为Shiro做准备

新增Permission类

package net.javablog.bean;

import org.nutz.dao.entity.annotation.*;

@Table("t_permission")
public class Permission extends BasePojo {

    @Id
    protected long id;
    @Name
    protected String name;
    @Column("al")
    protected String alias;
    @Column("dt")
    @ColDefine(type = ColType.VARCHAR, width = 500)
    private String description;


    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getDescription() {
        return description;
    }

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

新增Role类

package net.javablog.bean;

import org.nutz.dao.entity.annotation.*;

import java.util.List;

@Table("t_role")
public class Role extends BasePojo {

    @Id
    protected long id;
    @Name
    protected String name;
    @Column("al")
    protected String alias;
    @Column("dt")
    @ColDefine(type = ColType.VARCHAR, width = 500)
    private String description;
    @ManyMany(from = "role_id", relation = "t_role_permission", target = Permission.class, to = "permission_id")
    protected List<Permission> permissions;

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getDescription() {
        return description;
    }

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

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

修改User类

package net.javablog.bean;

import org.nutz.dao.entity.annotation.*;

import java.util.Date;
import java.util.List;

@Table("t_user")
public class User extends BasePojo {

    @Id
    protected int id;
    @Name
    @Column
    protected String name;
    @Column("passwd")
    @ColDefine(width = 128)
    protected String password;
    @Column
    protected String salt;
    @Column
    private boolean locked;
    @ManyMany(from = "u_id", relation = "t_user_role", target = Role.class, to = "role_id")
    protected List<Role> roles;
    @ManyMany(from = "u_id", relation = "t_user_permission", target = Permission.class, to = "permission_id")
    protected List<Permission> permissions;
    @One(target = UserProfile.class, field = "id", key = "userId")
    protected UserProfile profile;


    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

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

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

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public UserProfile getProfile() {
        return profile;
    }

    public void setProfile(UserProfile profile) {
        this.profile = profile;
    }
}

javabean关系

到目前为止总共7张表

t_permission 权限表
t_role 角色表
t_role_permission 角色和权限的关系表(多对多)
t_user 用户表
t_user_permission 用户和权限的关系表(多对多)
t_user_profile 用户和用户资料的关系表 (一对一)
t_user_role 用户和角色的关系表 (多对多)

新增UserService

package net.javablog.service;

import net.javablog.bean.User;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;
import org.nutz.service.IdNameEntityService;

import java.util.Date;

@IocBean(fields = "dao")
public class UserService extends IdNameEntityService<User> {

    public User add(String name, String password) {
        User user = new User();
        user.setName(name.trim());
        user.setSalt(R.UU16());
        user.setPassword(new Sha256Hash(password, user.getSalt()).toHex());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        return dao().insert(user);
    }

    public int fetch(String username, String password) {
        User user = fetch(username);
        if (user == null) {
            return -1;
        }
        String _pass = new Sha256Hash(password, user.getSalt()).toHex();
        if (_pass.equalsIgnoreCase(user.getPassword())) {
            return user.getId();
        }
        return -1;
    }

    public void updatePassword(int userId, String password) {
        User user = fetch(userId);
        if (user == null) {
            return;
        }
        user.setSalt(R.UU16());
        user.setPassword(new Sha256Hash(password, user.getSalt()).toHex());
        user.setUpdateTime(new Date());
        dao().update(user, "^(password|salt|updateTime)$");
    }


}

修改MainSetup

        // 初始化默认根用户
        if (dao.count(User.class) == 0) {
            UserService us = ioc.get(UserService.class);
            us.add("admin", "123456");
        }

使用UserService添加管理员用户

修改UserModule

打开UserModule, 先加一个属性UserService
@Inject protected UserService userService;

因为密码加密了,所以登陆方法要改一下

    @At
    @Filters // 覆盖UserModule类的@Filter设置,因为登陆可不能要求是个已经登陆的Session
    @POST
    public Object login(@Param("username")String username, 
            @Param("password")String password, 
            @Param("captcha")String captcha,
            @Attr(scope=Scope.SESSION, value="nutz_captcha")String _captcha,
            HttpSession session) {
        NutMap re = new NutMap();
        if (!Toolkit.checkCaptcha(_captcha, captcha)) {
            return re.setv("ok", false).setv("msg", "验证码错误");
        }
        int userId = userService.fetch(username, password);
        if (userId < 0) {
            return re.setv("ok", false).setv("msg", "用户名或密码错误");
        } else {
            session.setAttribute("me", userId);
            return re.setv("ok", true);
        }
    }

同样的还要修改add方法及update方法

    @At
    public Object update(@Param("password")String password, @Attr("me")int me) {
        if (Strings.isBlank(password) || password.length() < 6)
            return new NutMap().setv("ok", false).setv("msg", "密码不符合要求");
        userService.updatePassword(me, password);
        return new NutMap().setv("ok", true);
    }

重建表结构

因为User表修改了, 所以,打开mysql控制台,执行下面的语句
drop table nutzbook.t_user;

如果使用了1.b.53或以上的版本,可以在MainSetup中自动修改
Daos.migration(dao, User.class, true, false); 会保留原来的字段的数据

修改MainModule

打开MainModule, 添加一个注解
@SessionBy(ShiroSessionProvider.class)
含义是,使用Shiro的Session替换NutFilter作用域内的Session

页面测试

访问 http://127.0.0.1:8080/ admin登陆
添加一个新用户,然后尝试登陆,修改密码,再尝试登陆。