2021/12/27 Journal Development springboot + vue + mybatis Cotton Sugar English Project Day06

Rear part

Completed the system user add delete change check function

controller

//Get all users by querying criteria
    @RequestMapping("/getAllAdminUser")
    public ResultObj getAllAdminUser(@RequestParam(required=false,defaultValue="",name = "username") String username,
                                           @RequestParam(required=false,defaultValue="",name ="nickname") String nickname,
                                           @RequestParam(required=false,defaultValue="",name ="role_id")String role_id,
                                           @RequestParam(required=false,defaultValue="5",name ="limit")String pageSize,
                                           @RequestParam(required=false,defaultValue="1",name ="page")String pageNum){
        Integer roleId;
        if(StringUtils.hasLength(role_id)){
            roleId = Integer.parseInt(role_id);
        }
        else{
            roleId = null;
        }
        return adminUserService.getAllAdminUser(username, nickname, roleId,Integer.parseInt(pageSize), Integer.parseInt(pageNum));
    }

    //change
    @RequestMapping("/updateAdminUser")
    public ResultObj updateAdminUser(@RequestBody AdminUser user){
        return adminUserService.updateAdminUser(user);
    }

    //Delete
    @RequestMapping("/deleteAdminUserByIds")
    public ResultObj deleteAdminUserByIds(@RequestBody ArrayList<Integer> ids){
        return adminUserService.deleteAdminUserByIds(ids);
    }

    //increase
    @RequestMapping("/addAdminUser")
    public ResultObj addAdminUser(@RequestBody AdminUser user){
        return adminUserService.addAdminUser(user);
    }

serviceimpl

@Override
    public ResultObj getAllAdminUser(String username, String nickname, Integer role_id, Integer pageSize, Integer pageNum) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<AdminUser> adminUsers = adminUserDao.getAllAdminUser(username, nickname, role_id);
            PageInfo<AdminUser> pageInfo = new PageInfo<>(adminUsers);
            return new ResultObj(Constant.OK, Constant.QUERY_SUCCESS, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj(Constant.ERROR, Constant.QUERY_ERROR, null);
        }
    }

    @Override
    public ResultObj updateAdminUser(AdminUser user) {
        try {
            boolean flag = adminUserDao.updateAdminUser(user);
            if (flag) {
                return new ResultObj(Constant.OK, Constant.UPDATE_SUCCESS, null);
            } else {
                return new ResultObj(Constant.ERROR, Constant.UPDATE_ERROR, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj(Constant.ERROR, Constant.UPDATE_ERROR, null);
        }
    }

    @Override
    @Transactional
    public ResultObj deleteAdminUserByIds(List<Integer> ids) {
        try {
            boolean flag = adminUserDao.deleteAdminUserByIds(ids);
            if (flag) {
                return new ResultObj(Constant.OK, Constant.DELETE_SUCCESS, null);
            } else {
                return new ResultObj(Constant.ERROR, Constant.DELETE_ERROR, null);
            }
        } catch (Exception e) {
            return new ResultObj(Constant.ERROR, Constant.DELETE_ERROR, null);
        }
    }

    @Override
    public ResultObj addAdminUser(AdminUser user) {
        String salt = PasswordUtils.getSalt();
        String password = PasswordUtils.encode(user.getPassword(),salt);
        user.setSalt(salt);
        user.setPassword(password);
        try {
            boolean flag = adminUserDao.addAdminUser(user);
            if(flag){
                return new ResultObj(Constant.OK, Constant.ADD_SUCCESS,null);
            }
            else{
                return new ResultObj(Constant.ERROR, Constant.ADD_ERROR,null);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return new ResultObj(Constant.ERROR, Constant.ADD_ERROR, null);
        }
    }

mapper

<!--check-->
    <select id="getAllAdminUser"  resultMap="baseResultMap">
        SELECT id,username,nickname,role_id,available
        FROM admin_user
        <where>
            <if test="username != null and ! &quot;&quot;.equals(username)">
                <bind name="myUsername" value="'%' + username + '%'"/>
                username like #{myUsername}
            </if>
            <if test="nickname != null and ! &quot;&quot;.equals(nickname)">
                <bind name="myNickname" value="'%' + nickname + '%'"/>
                nickname like #{myNickname}
            </if>
            <if test="role_id != null">
                role_id = #{role_id}
            </if>
        </where>
    </select>
    <!--change-->
    <update id="updateAdminUser" parameterType="AdminUser">
        UPDATE admin_user
        <set>
            <if test="adminUser.username != null and ! &quot;&quot;.equals(adminUser.username)">
                username = #{adminUser.username},
            </if>
            <if test="adminUser.nickname != null and ! &quot;&quot;.equals(adminUser.nickname)">
                nickname = #{adminUser.nickname},
            </if>
            <if test="adminUser.roleId != null">
                role_id = #{adminUser.roleId},
            </if>
        </set>
        WHERE
        id = #{adminUser.id};
    </update>

    <!--Delete-->
    <delete id="deleteAdminUserByIds">
        DELETE FROM admin_user
        WHERE id in
        <foreach collection="ids" item = "id" index = "no" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <!--increase-->
    <insert id="addAdminUser" parameterType="AdminUser">
        INSERT INTO admin_user (username,nickname,password,role_id,createtime,salt)
        VALUES (#{user.username},#{user.nickname},#{user.password},#{user.roleId},NOW(),#{user.salt})
    </insert>

Completed resetting password function

/reset password
    @RequestMapping("/restPassword")
    public ResultObj restPassword(Integer id){
        log.info(String.valueOf(id));
        return adminUserService.restPassword(id);
    }
//reset password
    @Override
    public ResultObj restPassword(Integer id) {
        String salt = PasswordUtils.getSalt();
        String password = PasswordUtils.encode("123456", salt);
        try {
            boolean flag = adminUserDao.restPassword(id, password, salt);
            if (flag) {
                return new ResultObj(Constant.OK, Constant.RESET_SUCCESS, null);
            } else {
                return new ResultObj(Constant.ERROR, Constant.RESET_ERROR, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj(Constant.ERROR, Constant.RESET_ERROR, null);
        }
    }

Front end

Complete the child component's call to the parent component's event

Add events to child components in parent components that you want to trigger

Add trigger functions to subcomponents

// Trigger parent component event button
        //Data data,
        //fun parent component function name
        btnClick(fun,data) {
            console.log(fun);
            // this.$emit("click_" + (idx + 1), e);
            this.$emit(fun,data);
        },

This enables the child component to invoke the parent component

Finished updating front-end data, resetting password, deleting function

methods: {
        //Reset Search Bar
        reset() {
            let _this = this;
            _this.queryAdminUserForm.username = "";
            _this.queryAdminUserForm.nickname = "";
            _this.queryAdminUserForm.roleId = "";
            _this.$refs.table.getTableData();
        },
        // Send Conditional Search Request
        search() {
            this.$refs.table.getTableData();
        },

        // Single Data Update
        updateAdminUser(data) {
            let _this = this;
            if (data.id == 1) {
                _this.$message.error("You cannot edit this user with your permissions");
                return;
            }
            _this.updateAdminUserFormVisible = true;
            _this.updateForm.id = data.id;
            _this.updateForm.nickname = data.nickname;
            _this.updateForm.roleId = data.roleId;
        },
        //Send Edit Request
        toUpdateAdminUser(data) {
            let _this = this;
            adminUserApi
                .updateAdminUser(data)
                .then((res) => {
                    let result = res.data;
                    if (result.code == 200) {
                        _this.$message(result.msg);
                        this.$refs.table.getTableData();
                    } else {
                        _this.$message.error(result.msg);
                    }
                })
                .catch((error) => {
                    _this.$message.error("Server error, please try again later");
                });
            _this.updateAdminUserFormVisible = false;
        },
        //reset password
        resetPassword(data) {
            let _this = this;
            if (data.id == 1) {
                _this.$message.error("Your permissions cannot reset this user");
                return;
            }
            _this
                .$confirm("Do you want to reset the user's password to 123 456", "warning", {
                    confirmButtonText: "Determine",
                    cancelButtonText: "cancel",
                    type: "warning",
                })
                .then(() => {
                    //todelete
                    console.log("To reset");
                    _this.toResetPassword(data.id);
                })
                .catch(() => {});
        },
        toResetPassword(id) {
            let data = {
                id
            }
            adminUserApi
                .restPassword(data)
                .then((res) => {
                    let result = res.data;
                    if (result.code == 200) {
                        this.$message(result.msg);
                        this.$refs.table.getTableData();
                    } else {
                        this.$message.error(result.msg);
                    }
                })
                .catch((error) => {
                    this.$message.error("Server error, please try again later");
                });
        },
        //delete user
        deleteAdminUser(data) {
            let _this = this;
            if (data.id == 1) {
                _this.$message.error("Your permissions cannot delete this user");
                return;
            }
            _this
                .$confirm("Do you want to permanently delete this system user", "warning", {
                    confirmButtonText: "Determine",
                    cancelButtonText: "cancel",
                    type: "warning",
                })
                .then(() => {
                    //todelete
                    _this.toDelete(data.id);
                })
                .catch(() => {});
        },
        toDelete(id) {
            let ids = [id];
            adminUserApi
                .deleteAdminUserByIds(ids)
                .then((res) => {
                    let result = res.data;
                    if (result.code == 200) {
                        this.$message(result.msg);
                        this.$refs.table.getTableData();
                    } else {
                        this.$message.error(result.msg);
                    }
                })
                .catch((error) => {
                    this.$message.error("Server error, please try again later");
                });
        },
    },

Design sketch


Going to shiro again

Start by understanding the logic of shiro login authentication
https://blog.csdn.net/caoyang0105/article/details/82769293

Rewritten login logic
The login logic at this stage is
The backend intercepts all interface requests except for the login interface

protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("JwtFilter-->>>isAccessAllowed-Method:init()");
        //Whether you are trying to log in or return to true if you are trying to log in
        if (isLoginAttempt(request, response)) {
            return true;
        }

        //If the login api is not accessed, token should normally be present in HEADER
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(Constant.HEADER_TOKEN_KEY);
        if(StringUtils.hasLength(token)){
            //If so, enter the executeLogin method to execute the logon and check that token is correct
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                throw new AuthenticationException(e.getMessage());
            }
        }
        else{
            //No token illegal access request
            throw new AuthenticationException("Illegal access");
        }
    }

If it's not a login interface, get token in the browser response header
Access without token is illegal without login

If there is a token in the header, take it to LeeRealm for login authentication

LeeRealm

Here's a LeeMatcher to verify, because shiro will go back to LeesShiro to find a Matcher to verify the password, and then because there's no password in the data that's stored, overwrite a Matcher to let him verify that token is legal instead of verifying the password


And configure this Matcher in shiroconfig

It's too late now. Think about what you're going to write tomorrow. I'm afraid I'll forget it tomorrow

Tomorrow I will put the login logic in the controller in Realm, completely controlled by shiro, but I still feel unrealistic because I don't need Shiro to help me control my password. I just need him to help me control whether token is valid or not, and if it expires, I can control the user's login status, so I'll postpone for a moment and write it tomorrow.

Keywords: Java Spring Boot Vue.js

Added by roach on Tue, 04 Jan 2022 03:07:08 +0200