Java源码示例:com.ruoyi.framework.util.ShiroUtils

示例1
protected void handleDataScope(final JoinPoint joinPoint)
{
    // 获得注解
    DataScope controllerDataScope = getAnnotationLog(joinPoint);
    if (controllerDataScope == null)
    {
        return;
    }
    // 获取当前的用户
    SysUser currentUser = ShiroUtils.getSysUser();
    if (currentUser != null)
    {
        // 如果是超级管理员,则不过滤数据
        if (!currentUser.isAdmin())
        {
            dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
                    controllerDataScope.userAlias());
        }
    }
}
 
示例2
@RequiresPermissions("monitor:online:forceLogout")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@PostMapping("/forceLogout")
@ResponseBody
public AjaxResult forceLogout(String sessionId)
{
    SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
    if (sessionId.equals(ShiroUtils.getSessionId()))
    {
        return error("当前登陆用户无法强退");
    }
    if (online == null)
    {
        return error("用户已下线");
    }
    OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
    if (onlineSession == null)
    {
        return error("用户已下线");
    }
    onlineSession.setStatus(OnlineStatus.off_line);
    onlineSessionDAO.update(onlineSession);
    online.setStatus(OnlineStatus.off_line);
    userOnlineService.saveOnline(online);
    return success();
}
 
示例3
/**
 * 删除菜单
 */
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@RequiresPermissions("system:menu:remove")
@GetMapping("/remove/{menuId}")
@ResponseBody
public AjaxResult remove(@PathVariable("menuId") Long menuId)
{
    if (menuService.selectCountMenuByParentId(menuId) > 0)
    {
        return AjaxResult.warn("存在子菜单,不允许删除");
    }
    if (menuService.selectCountRoleMenuByMenuId(menuId) > 0)
    {
        return AjaxResult.warn("菜单已分配,不允许删除");
    }
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(menuService.deleteMenuById(menuId));
}
 
示例4
/**
 * 新增保存角色
 */
@RequiresPermissions("system:role:add")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@Validated SysRole role)
{
    if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
    {
        return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
    }
    else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
    {
        return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
    }
    role.setCreateBy(ShiroUtils.getLoginName());
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(roleService.insertRole(role));

}
 
示例5
/**
 * 保存
 */
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:dept:edit")
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(@Validated SysDept dept)
{
    if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
    {
        return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
    }
    else if (dept.getParentId().equals(dept.getDeptId()))
    {
        return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
    }
    dept.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(deptService.updateDept(dept));
}
 
示例6
/**
 * 新增保存用户
 */
@RequiresPermissions("system:user:add")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@Validated SysUser user)
{
    if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
    {
        return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在");
    }
    else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
    {
        return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在");
    }
    else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
    {
        return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在");
    }
    user.setSalt(ShiroUtils.randomSalt());
    user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
    user.setCreateBy(ShiroUtils.getLoginName());
    return toAjax(userService.insertUser(user));
}
 
示例7
/**
 * 修改保存用户
 */
@RequiresPermissions("system:user:edit")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(@Validated SysUser user)
{
    if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId()))
    {
        return error("不允许修改超级管理员用户");
    }
    else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
    {
        return error("修改用户'" + user.getLoginName() + "'失败,手机号码已存在");
    }
    else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
    {
        return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在");
    }
    user.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(userService.updateUser(user));
}
 
示例8
private String logout(String sessionId) {
    SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
    if (sessionId.equals(ShiroUtils.getSessionId())) {
        return "当前登陆用户无法强退";
    }
    if (online == null) {
        return "用户已下线";
    }
    OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
    if (onlineSession == null) {
        return "用户已下线";
    }
    onlineSession.setStatus(OnlineStatus.OFF_LINE);
    online.setStatus(OnlineStatus.OFF_LINE);
    userOnlineService.saveOnline(online);
    return null;
}
 
示例9
@Log(title = "重置密码", businessType = BusinessType.UPDATE)
@PostMapping("/resetPwd")
@ResponseBody
public AjaxResult resetPwd(String oldPassword, String newPassword)
{
    SysUser user = ShiroUtils.getSysUser();
    if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword))
    {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
        if (userService.resetUserPwd(user) > 0)
        {
            ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            return success();
        }
        return error();
    }
    else
    {
        return error("修改密码失败,旧密码错误");
    }
}
 
示例10
/**
 * 修改用户
 */
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PostMapping("/update")
@ResponseBody
public AjaxResult update(SysUser user)
{
    SysUser currentUser = ShiroUtils.getSysUser();
    currentUser.setUserName(user.getUserName());
    currentUser.setEmail(user.getEmail());
    currentUser.setPhonenumber(user.getPhonenumber());
    currentUser.setSex(user.getSex());
    if (userService.updateUserInfo(currentUser) > 0)
    {
        ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId()));
        return success();
    }
    return error();
}
 
示例11
/**
 * 修改保存岗位
 */
@RequiresPermissions("system:post:edit")
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(@Validated SysPost post)
{
    if (UserConstants.POST_NAME_NOT_UNIQUE.equals(postService.checkPostNameUnique(post)))
    {
        return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
    }
    else if (UserConstants.POST_CODE_NOT_UNIQUE.equals(postService.checkPostCodeUnique(post)))
    {
        return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
    }
    post.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(postService.updatePost(post));
}
 
示例12
protected void handleDataScope(final JoinPoint joinPoint)
{
    // 获得注解
    DataScope controllerDataScope = getAnnotationLog(joinPoint);
    if (controllerDataScope == null)
    {
        return;
    }
    // 获取当前的用户
    SysUser currentUser = ShiroUtils.getSysUser();
    if (currentUser != null)
    {
        // 如果是超级管理员,则不过滤数据
        if (!currentUser.isAdmin())
        {
            dataScopeFilter(joinPoint, currentUser, controllerDataScope.tableAlias());
        }
    }
}
 
示例13
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response){
    try {
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        SysUser user = ShiroUtils.getSysUser();
        if (ObjectUtil.isNotNull(user)) {
            String loginName = user.getLoginName();
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
            // 清理缓存
            cache.remove(loginName);
        }
        // 退出登录
        subject.logout();
        issueRedirect(request, response, redirectUrl);
    } catch (Exception e) {
        log.error("Encountered session exception during logout.  This can generally safely be ignored." , e);
    }
    return false;
}
 
示例14
/**
 * 删除菜单
 */
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@RequiresPermissions("system:menu:remove")
@PostMapping("/remove/{menuId}")
@ResponseBody
public AjaxResult remove(@PathVariable("menuId") Long menuId)
{
    if (menuService.selectCountMenuByParentId(menuId) > 0)
    {
        return error(1, "存在子菜单,不允许删除");
    }
    if (menuService.selectCountRoleMenuByMenuId(menuId) > 0)
    {
        return error(1, "菜单已分配,不允许删除");
    }
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(menuService.deleteMenuById(menuId));
}
 
示例15
/**
 * 新增保存用户
 */
@RequiresPermissions("system:user:add")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@Transactional(rollbackFor = Exception.class)
@ResponseBody
public AjaxResult addSave(SysUser user)
{
    if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId()))
    {
        return error("不允许修改超级管理员用户");
    }
    user.setSalt(ShiroUtils.randomSalt());
    user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
    user.setCreateBy(ShiroUtils.getLoginName());
    return toAjax(userService.insertUser(user));
}
 
示例16
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception
{
    try
    {
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        try
        {
            SysUser user = ShiroUtils.getSysUser();
            if (StringUtils.isNotNull(user))
            {
                String loginName = user.getLoginName();
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
                // 清理缓存
                cache.remove(loginName);
            }
            // 退出登录
            subject.logout();
        }
        catch (SessionException ise)
        {
            log.error("logout fail.", ise);
        }
        issueRedirect(request, response, redirectUrl);
    }
    catch (Exception e)
    {
        log.error("Encountered session exception during logout.  This can generally safely be ignored.", e);
    }
    return false;
}
 
示例17
/**
 * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception
{
    Subject subject = getSubject(request, response);
    if (subject == null || subject.getSession() == null)
    {
        return true;
    }
    Session session = onlineSessionDAO.readSession(subject.getSession().getId());
    if (session != null && session instanceof OnlineSession)
    {
        OnlineSession onlineSession = (OnlineSession) session;
        request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
        // 把user对象设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest == true)
        {
            SysUser user = ShiroUtils.getSysUser();
            if (user != null)
            {
                onlineSession.setUserId(user.getUserId());
                onlineSession.setLoginName(user.getLoginName());
	onlineSession.setAvatar(user.getAvatar());
                onlineSession.setDeptName(user.getDept().getDeptName());
                onlineSession.markAttributeChanged();
            }
        }

        if (onlineSession.getStatus() == OnlineStatus.off_line)
        {
            return false;
        }
    }
    return true;
}
 
示例18
/**
 * 新增保存角色
 */
@RequiresPermissions("system:role:add")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@Transactional(rollbackFor = Exception.class)
@ResponseBody
public AjaxResult addSave(SysRole role) {
    role.setCreateBy(ShiroUtils.getLoginName());
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(roleService.insertRole(role));

}
 
示例19
/**
 * 修改保存参数配置
 */
@RequiresPermissions("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysConfig config) {
    config.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(configService.updateConfig(config));
}
 
示例20
/**
 * 授权
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0)
{
    SysUser user = ShiroUtils.getSysUser();
    // 角色列表
    Set<String> roles = new HashSet<String>();
    // 功能列表
    Set<String> menus = new HashSet<String>();
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    // 管理员拥有所有权限
    if (user.isAdmin())
    {
        info.addRole("admin");
        info.addStringPermission("*:*:*");
    }
    else
    {
        roles = roleService.selectRoleKeys(user.getUserId());
        menus = menuService.selectPermsByUserId(user.getUserId());
        // 角色加入AuthorizationInfo认证对象
        info.setRoles(roles);
        // 权限加入AuthorizationInfo认证对象
        info.setStringPermissions(menus);
    }
    return info;
}
 
示例21
@RequiresPermissions("monitor:online:batchForceLogout")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@PostMapping("/batchForceLogout")
@ResponseBody
public AjaxResult batchForceLogout(@RequestParam("ids[]") String[] ids)
{
    for (String sessionId : ids)
    {
        SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
        if (online == null)
        {
            return error("用户已下线");
        }
        OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
        if (onlineSession == null)
        {
            return error("用户已下线");
        }
        if (sessionId.equals(ShiroUtils.getSessionId()))
        {
            return error("当前登陆用户无法强退");
        }
        onlineSession.setStatus(OnlineStatus.off_line);
        onlineSessionDAO.update(onlineSession);
        online.setStatus(OnlineStatus.off_line);
        userOnlineService.saveOnline(online);
    }
    return success();
}
 
示例22
/**
 * 修改保存菜单
 */
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:menu:edit")
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysMenu menu) {
    menu.setUpdateBy(ShiroUtils.getLoginName());
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(menuService.updateMenu(menu));
}
 
示例23
/**
 * 修改保存菜单
 */
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:menu:edit")
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(@Validated SysMenu menu)
{
    if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
    {
        return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
    }
    menu.setUpdateBy(ShiroUtils.getLoginName());
    ShiroUtils.clearCachedAuthorizationInfo();
    return toAjax(menuService.updateMenu(menu));
}
 
示例24
/**
 * 加载角色菜单列表树
 */
@GetMapping("/roleMenuTreeData")
@ResponseBody
public List<Ztree> roleMenuTreeData(SysRole role)
{
    Long userId = ShiroUtils.getUserId();
    List<Ztree> ztrees = menuService.roleMenuTreeData(role, userId);
    return ztrees;
}
 
示例25
/**
 * 加载所有菜单列表树
 */
@GetMapping("/menuTreeData")
@ResponseBody
public List<Ztree> menuTreeData()
{
    Long userId = ShiroUtils.getUserId();
    List<Ztree> ztrees = menuService.menuTreeData(userId);
    return ztrees;
}
 
示例26
/**
 * 保存
 */
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:dept:edit")
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysDept dept) {
    dept.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(deptService.updateDept(dept));
}
 
示例27
/**
 * 保存角色分配数据权限
 */
@RequiresPermissions("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PostMapping("/authDataScope")
@ResponseBody
public AjaxResult authDataScopeSave(SysRole role)
{
    role.setUpdateBy(ShiroUtils.getLoginName());
    if (roleService.authDataScope(role) > 0)
    {
        ShiroUtils.setSysUser(userService.selectUserById(ShiroUtils.getSysUser().getUserId()));
        return success();
    }
    return error();
}
 
示例28
/**
 * 新增保存调度
 */
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@RequiresPermissions("monitor:job:add")
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(SysJob job) throws SchedulerException, TaskException{
    job.setCreateBy(ShiroUtils.getLoginName());
    return toAjax(jobService.insertJobCron(job));
}
 
示例29
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    if (handler instanceof HandlerMethod) {
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Class<?> clazz = handlerMethod.getBeanType();
        final Method method = handlerMethod.getMethod();

        if (clazz.isAnnotationPresent(LoginAuth.class) || method.isAnnotationPresent(LoginAuth.class)) {
            SysUser loginUser = ShiroUtils.getSysUser();
            return ObjectUtil.isNotNull(loginUser);
        }
    }
    return true;
}
 
示例30
/**
 * 修改保存公告
 */
@RequiresPermissions("system:notice:edit")
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysNotice notice)
{
    notice.setUpdateBy(ShiroUtils.getLoginName());
    return toAjax(noticeService.updateNotice(notice));
}