springBoot中shiro与Redis整合的配置文件
整合依赖:
<!--shiro与redis整合-->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.0.0</version>
</dependency>
配置文件:
spring:
redis:
host: 127.0.0.1
port: 6379
配置类:
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
//2.创建安全管理器
@Bean
public SecurityManager getSecurityManager(CustomRealm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
//将自定义的会话管理器注册到安全管理器中
securityManager.setSessionManager(sessionManager());
//将自定义的redis缓存管理器注册到安全管理器中
securityManager.setCacheManager(cacheManager());
return securityManager;
}
/**
* 1.redis的控制器,操作redis
*/
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
return redisManager;
}
/**
* 2.sessionDao
*/
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO sessionDAO = new RedisSessionDAO();
sessionDAO.setRedisManager(redisManager());
return sessionDAO;
}
/**
* 3.会话管理器
*/
public DefaultWebSessionManager sessionManager() {
CustomSessionManager sessionManager = new CustomSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* 4.缓存管理器
*/
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
全部配置:
package cn.itcast.shiro;
import cn.itcast.shiro.realm.CustomRealm;
import cn.itcast.shiro.session.CustomSessionManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfiguration {
//1.创建realm
@Bean
public CustomRealm getRealm() {
return new CustomRealm();
}
//2.创建安全管理器
@Bean
public SecurityManager getSecurityManager(CustomRealm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
//将自定义的会话管理器注册到安全管理器中
securityManager.setSessionManager(sessionManager());
//将自定义的redis缓存管理器注册到安全管理器中
securityManager.setCacheManager(cacheManager());
return securityManager;
}
//3.配置shiro的过滤器工厂
/**
* 再web程序中,shiro进行权限控制全部是通过一组过滤器集合进行控制
*
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
//1.创建过滤器工厂
ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
//2.设置安全管理器
filterFactory.setSecurityManager(securityManager);
//3.通用配置(跳转登录页面,为授权跳转的页面)
filterFactory.setLoginUrl("/autherror?code=1");//跳转url地址
filterFactory.setUnauthorizedUrl("/autherror?code=2");//未授权的url
//4.设置过滤器集合
/**
* 设置所有的过滤器:有顺序map
* key = 拦截的url地址
* value = 过滤器类型
*
*/
Map<String,String> filterMap = new LinkedHashMap<>();
//filterMap.put("/user/home","anon");//当前请求地址可以匿名访问
//具有某中权限才能访问
//使用过滤器的形式配置请求地址的依赖权限
//filterMap.put("/user/home","perms[user-home]"); //不具备指定的权限,跳转到setUnauthorizedUrl地址
//使用过滤器的形式配置请求地址的依赖角色
//filterMap.put("/user/home","roles[系统管理员]");
filterMap.put("/user/**","authc");//当前请求地址必须认证之后可以访问
filterFactory.setFilterChainDefinitionMap(filterMap);
return filterFactory;
}
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
/**
* 1.redis的控制器,操作redis
*/
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
return redisManager;
}
/**
* 2.sessionDao
*/
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO sessionDAO = new RedisSessionDAO();
sessionDAO.setRedisManager(redisManager());
return sessionDAO;
}
/**
* 3.会话管理器
*/
public DefaultWebSessionManager sessionManager() {
CustomSessionManager sessionManager = new CustomSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* 4.缓存管理器
*/
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
//开启对shior注解的支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
注意:使用shiro与Redis的插件包,实体类必须实现一个接口AuthCachePrincipal才能将数据存入Redis中,重写的方法回null就可以了;
完整实体类:
package cn.itcast.shiro.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.crazycake.shiro.AuthCachePrincipal;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* 用户实体类
*/
@Entity
@Table(name = "pe_user")
@Getter
@Setter
/**
* AuthCachePrincipal:
* redis和shiro插件包提供的接口
*/
public class User implements Serializable ,AuthCachePrincipal {
private static final long serialVersionUID = 4297464181093070302L;
/**
* ID
*/
@Id
private String id;
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="pe_user_role",joinColumns={@JoinColumn(name="user_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="role_id",referencedColumnName="id")}
)
private Set<Role> roles = new HashSet<Role>();//用户与角色 多对多
@Override
public String getAuthCacheKey() {
return null;
}
}
项目地址:
链接:https://pan.baidu.com/s/1gqssnCWLofXFxshutBj3BA
提取码:o87i
==========================================================================================
pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itcast</groupId>
<artifactId>shiro_springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<fastjson.version>1.2.47</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--shiro和spring整合-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro核心包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro与redis整合-->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<!--编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<!--单元测试插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置:
server:
port: 8081
spring:
application:
name: ihrm-company #指定服务名
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/shiro_db?useUnicode=true&characterEncoding=utf8
username: root
password: 111111
jpa:
database: MySQL
show-sql: true
open-in-view: true
redis:
host: 127.0.0.1
port: 6379
代码:
自定义的公共异常处理器
package cn.itcast.shiro;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义的公共异常处理器
* 1.声明异常处理器
* 2.对异常统一处理
*/
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(value = AuthorizationException.class)
@ResponseBody
public String error(HttpServletRequest request, HttpServletResponse response,AuthorizationException e) {
return "未授权";
}
}
启动器:
package cn.itcast.shiro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication(scanBasePackages = "cn.itcast")
@EntityScan("cn.itcast.shiro.domain")
public class ShiroApplication {
public static void main(String[] args) {
SpringApplication.run(ShiroApplication.class, args);
}
@Bean
public OpenEntityManagerInViewFilter openEntityManagerInViewFilter() {
return new OpenEntityManagerInViewFilter();
}
}
shiro配置类
package cn.itcast.shiro;
import cn.itcast.shiro.realm.CustomRealm;
import cn.itcast.shiro.session.CustomSessionManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfiguration {
//1.创建realm
@Bean
public CustomRealm getRealm() {
return new CustomRealm();
}
//2.创建安全管理器
@Bean
public SecurityManager getSecurityManager(CustomRealm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
//将自定义的会话管理器注册到安全管理器中
securityManager.setSessionManager(sessionManager());
//将自定义的redis缓存管理器注册到安全管理器中
securityManager.setCacheManager(cacheManager());
return securityManager;
}
//3.配置shiro的过滤器工厂
/**
* 再web程序中,shiro进行权限控制全部是通过一组过滤器集合进行控制
*
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
//1.创建过滤器工厂
ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
//2.设置安全管理器
filterFactory.setSecurityManager(securityManager);
//3.通用配置(跳转登录页面,为授权跳转的页面)
filterFactory.setLoginUrl("/autherror?code=1");//跳转url地址
filterFactory.setUnauthorizedUrl("/autherror?code=2");//未授权的url
//4.设置过滤器集合
/**
* 设置所有的过滤器:有顺序map
* key = 拦截的url地址
* value = 过滤器类型
*
*/
Map<String,String> filterMap = new LinkedHashMap<>();
//filterMap.put("/user/home","anon");//当前请求地址可以匿名访问
//具有某中权限才能访问
//使用过滤器的形式配置请求地址的依赖权限
//filterMap.put("/user/home","perms[user-home]"); //不具备指定的权限,跳转到setUnauthorizedUrl地址
//使用过滤器的形式配置请求地址的依赖角色
//filterMap.put("/user/home","roles[系统管理员]");
filterMap.put("/user/**","authc");//当前请求地址必须认证之后可以访问
filterFactory.setFilterChainDefinitionMap(filterMap);
return filterFactory;
}
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
/**
* 1.redis的控制器,操作redis
*/
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
return redisManager;
}
/**
* 2.sessionDao
*/
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO sessionDAO = new RedisSessionDAO();
sessionDAO.setRedisManager(redisManager());
return sessionDAO;
}
/**
* 3.会话管理器
*/
public DefaultWebSessionManager sessionManager() {
CustomSessionManager sessionManager = new CustomSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* 4.缓存管理器
*/
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
//开启对shior注解的支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
realm:
package cn.itcast.shiro.realm;
import cn.itcast.shiro.domain.Permission;
import cn.itcast.shiro.domain.Role;
import cn.itcast.shiro.domain.User;
import cn.itcast.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;
/**
* 自定义的realm
*/
public class CustomRealm extends AuthorizingRealm {
public void setName(String name) {
super.setName("customRealm");
}
@Autowired
private UserService userService;
/**
* 授权方法
* 操作的时候,判断用户是否具有响应的权限
* 先认证 -- 安全数据
* 再授权 -- 根据安全数据获取用户具有的所有操作权限
*
*
*/
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//1.获取已认证的用户数据
User user = (User) principalCollection.getPrimaryPrincipal();//得到唯一的安全数据
//2.根据用户数据获取用户的权限信息(所有角色,所有权限)
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> roles = new HashSet<>();//所有角色
Set<String> perms = new HashSet<>();//所有权限
for (Role role : user.getRoles()) {
roles.add(role.getName());
for (Permission perm : role.getPermissions()) {
perms.add(perm.getCode());
}
}
info.setStringPermissions(perms);
info.setRoles(roles);
return info;
}
/**
* 认证方法
* 参数:传递的用户名密码
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.获取登录的用户名密码(token)
UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
String username = upToken.getUsername();
String password = new String( upToken.getPassword());
//2.根据用户名查询数据库
User user = userService.findByName(username);
//3.判断用户是否存在或者密码是否一致
if(user != null && user.getPassword().equals(password)) {
//4.如果一致返回安全数据
//构造方法:安全数据,密码,realm域名
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
return info;
}
//5.不一致,返回null(抛出异常)
return null;
}
public static void main(String[] args) {
System.out.println(new Md5Hash("123456","wangwu",3).toString());
}
}
自定义的sessionManager:
package cn.itcast.shiro.session;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
/**
* 自定义的sessionManager
*/
public class CustomSessionManager extends DefaultWebSessionManager {
/**
* 头信息中具有sessionid
* 请求头:Authorization: sessionid
*
* 指定sessionId的获取方式
*/
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
//获取请求头Authorization中的数据
String id = WebUtils.toHttp(request).getHeader("Authorization");
if(StringUtils.isEmpty(id)) {
//如果没有携带,生成新的sessionId
return super.getSessionId(request,response);
}else{
//返回sessionId;
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return id;
}
}
}
UserController:
package cn.itcast.shiro.controller;
import cn.itcast.shiro.domain.User;
import cn.itcast.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
@RestController
public class UserController {
@Autowired
private UserService userService;
//个人主页
//使用shiro注解鉴权
//@RequiresPermissions() -- 访问此方法必须具备的权限
//@RequiresRoles() -- 访问此方法必须具备的角色
/**
* 1.过滤器:如果权限信息不匹配setUnauthorizedUrl地址
* 2.注解:如果权限信息不匹配,抛出异常
*/
@RequiresPermissions("user-home")
@RequestMapping(value = "/user/home")
public String home() {
return "访问个人主页成功";
}
//添加
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String add() {
return "添加用户成功";
}
//查询
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String find() {
return "查询用户成功";
}
//更新
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String update(String id) {
return "更新用户成功";
}
//删除
@RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
public String delete() {
return "删除用户成功";
}
/**
* 1.传统登录
* 前端发送登录请求 => 接口部分获取用户名密码 => 程序员在接口部分手动控制
* 2.shiro登录
* 前端发送登录请求 => 接口部分获取用户名密码 => 通过subject.login => realm域的认证方法
*
*/
//用户登录
@RequestMapping(value="/login")
public String login(String username,String password) {
//构造登录令牌
try {
/**
* 密码加密:
* shiro提供的md5加密
* Md5Hash:
* 参数一:加密的内容
* 111111 --- abcd
* 参数二:盐(加密的混淆字符串)(用户登录的用户名)
* 111111+混淆字符串
* 参数三:加密次数
*
*/
password = new Md5Hash(password,username,3).toString();
UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
//1.获取subject
Subject subject = SecurityUtils.getSubject();
//获取session
String sid = (String) subject.getSession().getId();
//2.调用subject进行登录
subject.login(upToken);
return "登录成功";
}catch (Exception e) {
return "用户名或密码错误";
}
}
}
实体类:
package cn.itcast.shiro.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.crazycake.shiro.AuthCachePrincipal;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* 用户实体类
*/
@Entity
@Table(name = "pe_user")
@Getter
@Setter
/**
* AuthCachePrincipal:
* redis和shiro插件包提供的接口
*/
public class User implements Serializable ,AuthCachePrincipal {
private static final long serialVersionUID = 4297464181093070302L;
/**
* ID
*/
@Id
private String id;
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="pe_user_role",joinColumns={@JoinColumn(name="user_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="role_id",referencedColumnName="id")}
)
private Set<Role> roles = new HashSet<Role>();//用户与角色 多对多
@Override
public String getAuthCacheKey() {
return null;
}
}
package cn.itcast.shiro.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "pe_role")
@Getter
@Setter
public class Role implements Serializable {
private static final long serialVersionUID = 594829320797158219L;
@Id
private String id;
private String name;
private String description;
//角色与用户 多对多
@ManyToMany(mappedBy="roles")
private Set<User> users = new HashSet<User>(0);
//角色与权限 多对多
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="pe_role_permission",
joinColumns={@JoinColumn(name="role_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="permission_id",referencedColumnName="id")})
private Set<Permission> permissions = new HashSet<Permission>(0);
}
package cn.itcast.shiro.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "pe_permission")
@Getter
@Setter
@NoArgsConstructor
public class Permission implements Serializable {
private static final long serialVersionUID = -4990810027542971546L;
/**
* 主键
*/
@Id
private String id;
private String name;
private String code;
private String description;
}
======================================ssm================================================
ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
spring-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<description>Shiro 配置</description>
<import resource="spring-redis.xml"></import>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/returnloginPage" />
<property name="unauthorizedUrl" value="/returnloginPage" />
<property name="filterChainDefinitions">
<value>
/* = anon
/view/assets/** = anon
/view/jsp/**=authc
</value>
</property>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!--自定义Realm 继承自AuthorizingRealm -->
<bean id="monitorRealm" class="com.tcwl.vsmp.shiro.MyShiroRealm">
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--设置自定义realm -->
<property name="realm" ref="monitorRealm" />
<!--
<property name="cacheManager" ref="shiroEhcacheManager" />-->
<property name="cacheManager" ref="shiroCacheManager" />
<property name="sessionManager" ref="sessionManager"></property>
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor" />
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!--classpath是缓存属性的配置文件 -->
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" />
</bean>
<!-- 2018-07-23 实现shiro-redis -->
<!-- Redis-based cache configuration -->
<bean id="shiroCacheManager" class="org.crazycake.shiro.RedisCacheManager">
<property name="redisManager" ref="redisManager" />
<property name="expire" value="1800"/>
<property name="keyPrefix" value="shiro:cache:" />
</bean>
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="sessionDAO" ref="redisSessionDAO" />
<property name="sessionIdCookie" ref="shareSession" />
</bean>
<!-- sessionIdCookie的实现,用于重写覆盖容器默认的JSESSIONID -->
<bean id="shareSession" class="org.apache.shiro.web.servlet.SimpleCookie">
<!-- cookie的name,对应的默认是 JSESSIONID -->
<constructor-arg name="name" value="SHAREJSESSIONID" />
<!-- jsessionId的path为 / 用于多个系统共享jsessionId -->
<property name="path" value="/" />
<property name="httpOnly" value="true"/>
</bean>
</beans>
com.tcwl.vsmp.shiro.ShiroUtils
package com.tcwl.vsmp.shiro;
import com.tcwl.vsmp.customer.dao.CustomerDao;
import com.tcwl.vsmp.customer.po.Customer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author johnny
* @create 2018-08-08 上午10:18
**/
@Component
public class ShiroUtils implements ApplicationContextAware
{
@Autowired
private static CustomerDao customerDao;
public static void updateShiroSubject()
{
Subject subject = SecurityUtils.getSubject();
Object currentUser = subject.getPrincipal();
String code;
if (currentUser instanceof Customer)
{
Customer redisUser = (Customer) currentUser;
code = redisUser.getCustomer_code();
Customer basesUser = customerDao.queryCustomerByCustomerCode(code);
// 修改属性 哈哈
PrincipalCollection principalCollection = subject.getPrincipals();
String realmName = principalCollection.getRealmNames().iterator()
.next();
PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(
basesUser, realmName);
subject.runAs(newPrincipalCollection);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException
{
customerDao = (CustomerDao) applicationContext.getBean("customerDao");
}
}
com.tcwl.vsmp.shiro.MyShiroRealm
/******************************************************************
*
* 无锡坦程第三方增值业务平台
*
* Package: com.tcwl.vsmp.shiro
*
* Filename: MyShiroRealm.java
*
* Description: shiro
*
* Copyright: Copyright (c) 2012 Wu Xi Tan Cheng IOT Technology Co.,Ltd
*
* Company: 无锡坦程物联网科技有限公司
*
* @author: ChenLei
*
* @version: 1.0.0
*
* @since: 1.6.0
*
* Create at: 2016-1-18 下午1:29:19
*
* Revision:
*
* 2016-1-18 下午1:29:19 - first revision
*
*****************************************************************/
package com.tcwl.vsmp.shiro;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.tcwl.vsmp.common.BaseService;
import com.tcwl.vsmp.common.memcached.MemcachedInvoke;
import com.tcwl.vsmp.customer.dao.CustomerDao;
import com.tcwl.vsmp.customer.po.Customer;
import com.tcwl.vsmp.sysuser.dao.SysUserDao;
import com.tcwl.vsmp.sysuser.po.SysUser;
import com.tcwl.vsmp.sysuser.service.impl.SysUserServiceImpl;
import com.tcwl.vsmp.utils.PhoneFormatCheckUtils;
/**
*
* shiro权限
* @author ChenLei 2016-1-18 下午1:29:19
* @version 1.0.0
*/
@Repository("monitorRealm")
public class MyShiroRealm extends AuthorizingRealm
{
/**
* 客户模块DAO
*/
@Autowired
private CustomerDao customerDao;
/**
* 系统用户Dao
*/
@Autowired
private SysUserDao sysUserDao;
/**
* @Description 认证回调函数, 登录时调用.
* @param authcToken 对象
* @return 结果
* @throws AuthenticationException
*/
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException
{
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
String password = String.valueOf(token.getPassword());
// 判断是不是手机号
boolean isPhone = PhoneFormatCheckUtils
.isPhoneLegal(token.getUsername().trim());
// 查询客户信息
Customer customer = null;
if (isPhone)
{
// 找到对应的客户
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("count", 0);
map1.put("pagenumber", 10);
map1.put("phone", token.getUsername().trim());
map1.put("login_pwd", password);
List<Customer> cList = customerDao.queryCustomerByMap(map1);
if (null != cList && cList.size() > 0)
{
customer = cList.get(0);
}
}
else
{
customer = customerDao.queryByLoginCode(token.getUsername(),
password);
}
SysUser user = null;
if (null == customer)
{
user = sysUserDao.queryByLoginCode(token.getUsername(), password);
}
if (null != customer)
{
Session session = SecurityUtils.getSubject().getSession();
System.out.println("APP客户认证成功... ");
session.setTimeout(-1000L);
// System.out.println(session.getId());
return new SimpleAuthenticationInfo(customer,
customer.getLogin_pwd(), getName());
}
else if (null != user)
{
Session session = SecurityUtils.getSubject().getSession();
System.out.println("后台用户认证成功... ");
SysUserServiceImpl.getMap().put(user.getLogin_code(), password);
System.out.println(
SysUserServiceImpl.getMap().get(user.getLogin_code()));
// System.out.println(session.getId());
return new SimpleAuthenticationInfo(user, user.getLogin_pwd(),
getName());
}
else
{
System.out.println("认证失败...");
return null;
}
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals)
{
SysUser sysUser = (SysUser) (principals.fromRealm(getName()).iterator()
.next());
String logincode = sysUser.getLogin_code();
// String logincode = (principals.fromRealm(getName()).iterator().next()
// .toString());
// SysUser sysUser = null;
if (null == (BaseService.getMemClientInstant()
.get(("UserMenus" + logincode))))
{
MemcachedInvoke.getMemClient().set(("UserMenus" + logincode),
sysUserDao.queryByLoginCode(logincode, ""));
}
sysUser = (SysUser) MemcachedInvoke.getMemClient()
.get("UserMenus" + logincode);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// String roleName = sysUser.getRole().getRole_name();
// String menus_Id = sysUser.getRole().getMenu_id();
// info.addRole(roleName);
List<String> permissions = new ArrayList<String>();
String[] strArray = null;
strArray = (sysUser.getMenu_id()).split(",");
permissions = Arrays.asList(strArray);
info.addStringPermissions(permissions);
return info;
}
/**
* 更新用户授权信息缓存.
* @param principal 名字
*/
public void clearCachedAuthorizationInfo(String principal)
{
SimplePrincipalCollection principals = new SimplePrincipalCollection(
principal, getName());
clearCachedAuthorizationInfo(principals);
}
/**
* 清除所有用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo()
{
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null)
{
for (Object key : cache.keys())
{
cache.remove(key);
}
}
}
/**
* 得到当前登录用户(需要转换)
*
* @return 结果
*/
public static Object getLoginUser()
{
return SecurityUtils.getSubject().getPrincipal();
}
}
实体类:
/******************************************************************
*
* 无锡坦程第三方增值业务平台
*
* Package: com.tcwl.vsmp.sysuser.po
*
* Filename: SysUser.java
*
* Description: 后台用户PO
*
* Copyright: Copyright (c) 2012 Wu Xi Tan Cheng IOT Technology Co.,Ltd
*
* Company: 无锡坦程物联网科技有限公司
*
* @author: ChenLei
*
* @version: 1.0.0
*
* @since: 1.6.0
*
* Create at: 2016-1-18 下午5:15:47
*
* Revision:
*
* 2016-1-18 下午5:15:47 - first revision
*
*****************************************************************/
package com.tcwl.vsmp.sysuser.po;
import java.io.Serializable;
import com.tcwl.vsmp.role.po.SysRole;
import org.crazycake.shiro.AuthCachePrincipal;
/**
*
*
* @author ChenLei 2016-1-18 下午5:15:47
* @version 1.0.0
*/
public class SysUser implements Serializable , AuthCachePrincipal
{
/**
* @Field @serialVersionUID : TODO(这里用一句话描述这个类的作用)
*/
private static final long serialVersionUID = 1L;
/**
* id
*/
private int sys_uid;
/**
* 登录帐号
*/
private String login_code;
/**
* 登录密码
*/
private String login_pwd;
/**
* 名字
*/
private String true_name;
/**
* 手机
*/
private String mobile;
/**
* 地址
*/
private String address;
/**
* 状态
*/
private String status;
/**
* 添加时间
*/
private String create_time;
/**
* 所属角色
*/
private int role_id;
/**
* 部门名称
*/
private String dept_name;
/**
*
*/
private SysRole role = new SysRole();
/**
* 菜单id
*/
private String menu_id;
public String getMenu_id()
{
return menu_id;
}
public void setMenu_id(String menu_id)
{
this.menu_id = menu_id;
}
public SysRole getRole()
{
return role;
}
public void setRole(SysRole role)
{
this.role = role;
}
public String getDept_name()
{
return dept_name;
}
public void setDept_name(String dept_name)
{
this.dept_name = dept_name;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
public int getRole_id()
{
return role_id;
}
public void setRole_id(int role_id)
{
this.role_id = role_id;
}
/**
*
* @return 结果
*/
public String getCreate_time()
{
if (create_time != null)
{
return (create_time).substring(0, create_time.length() - 2);
}
return "";
}
public void setCreate_time(String create_time)
{
this.create_time = create_time;
}
public int getSys_uid()
{
return sys_uid;
}
public void setSys_uid(int sys_uid)
{
this.sys_uid = sys_uid;
}
public String getLogin_code()
{
return login_code;
}
public void setLogin_code(String login_code)
{
this.login_code = login_code;
}
public String getLogin_pwd()
{
return login_pwd;
}
public void setLogin_pwd(String login_pwd)
{
this.login_pwd = login_pwd;
}
public String getTrue_name()
{
return true_name;
}
public void setTrue_name(String true_name)
{
this.true_name = true_name;
}
public String getMobile()
{
return mobile == null ? "" : mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
public String getAddress()
{
return address == null ? "" : address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
@Override
public String getAuthCacheKey() {
return getLogin_code();
}
}
控制器:
/******************************************************************
*
* 无锡坦程第三方增值业务平台
*
* Package: com.tcwl.vsmp.sysuser.controller
*
* Filename: UserController.java
*
* Description: TODO(用一句话描述该文件做什么)
*
* Copyright: Copyright (c) 2012 Wu Xi Tan Cheng IOT Technology Co.,Ltd
*
* Company: 无锡坦程物联网科技有限公司
*
* @author: Administrator
*
* @version: 1.0.0
*
* @since: 1.6.0
*
* Create at: 2016-1-21 上午10:30:43
*
* Revision:
*
* 2016-1-21 上午10:30:43 - first revision
*
*****************************************************************/
package com.tcwl.vsmp.sysuser.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tcwl.vsmp.common.BaseController;
import com.tcwl.vsmp.common.ExceptionInfo;
import com.tcwl.vsmp.common.OilConstant;
import com.tcwl.vsmp.oil.service.OilCardOperationService;
import com.tcwl.vsmp.passcard.service.PassCardService;
import com.tcwl.vsmp.role.po.SysRole;
import com.tcwl.vsmp.role.service.RoleService;
import com.tcwl.vsmp.sysuser.po.SysUser;
import com.tcwl.vsmp.sysuser.service.SysUserService;
import com.tcwl.vsmp.utils.BatchNumber;
import com.tcwl.vsmp.utils.DateUtils;
import com.tcwl.vsmp.utils.PageBean;
/**
*
* 后台用户Controller
* @author ChenLei 2016-1-21 上午10:30:43
* @version 1.0.0
*/
@Controller
public class UserController
{
/**
* 系统用户service
*/
@Autowired
private SysUserService userService;
/**
* 角色service
*/
@Autowired
private RoleService roleService;
/**
* 油卡Service
*/
@Autowired
private OilCardOperationService olicardService;
/**
* 通行卡service
*/
@Autowired
private PassCardService passCardService;
/**
*
* @param session session
* @param request 请求
* @return 结果
*/
@RequestMapping("/returnloginPage")
public String returnloginPage(HttpSession session,
HttpServletRequest request)
{
return "login";
}
/**
*
* @param login_code 登录帐号
* @param login_pwd 登录密码
* @param request 请求
* @return 结果
*/
@RequestMapping("/sysUser/adminLogin")
public @ResponseBody Map<String, String> adminLogin(
@RequestParam("login_code") String login_code,
@RequestParam("login_pwd") String login_pwd,
HttpServletRequest request)
{
Map<String, String> map = userService.adminLogin(login_code, login_pwd);
HttpSession session = request.getSession(true);
session.setAttribute("loginUser",
userService.findUsernameBycode(login_code));
session.setAttribute("uid",userService.findUserIdByCode(login_code));
session.setAttribute("msgTimes", olicardService.queryMsg(login_code));
// 借款阀值
session.setAttribute("loanThreshold",
BatchNumber.getValue(OilConstant.LOAN_THRESHOLD));
return map;
}
/**
*
* @param index 分页
* @param size 分页
* @param deptId 部门id
* @param logincode 登录帐号
* @param username 用户名
* @param is_join 是否合并
* @param request 请求
* @return 结果
*/
@RequestMapping("/sysUser/queryAll")
public @ResponseBody PageBean<SysUser> queryAll(
@RequestParam("index") int index, @RequestParam("size") int size,
@RequestParam("deptId") int deptId,
@RequestParam("logincode") String logincode,
@RequestParam("username") String username,
@RequestParam("is_join") int is_join, HttpServletRequest request)
{
String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
PageBean<SysUser> user = null;
try
{
user = userService.queryAll(index, size, deptId, logincode,
username, is_join);
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "查询用户", 1, 1,
"");
}
catch (Exception e)
{
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "查询用户", 0, 1,
"");
}
return user;
}
/**
*
* @param uid id
* @param request 返回
* @return 结果
*/
@RequestMapping("/user/findUser")
public String findById(@RequestParam("uid") int uid,
HttpServletRequest request)
{
try
{
SysUser user = userService.findById(uid);
List<SysRole> roles = roleService.findAll();
request.setAttribute("user", user);
request.setAttribute("userRoles", roles);
}
catch (Exception e)
{
return "/jsp/error";
}
return "/jsp/user/userupdate";
}
/**
*
* @param uid id
* @param request 返回
* @return 结果
*/
@RequestMapping("/user/changePwd")
public String changePwd(@RequestParam("uid") int uid,
HttpServletRequest request)
{
try
{
SysUser user = userService.findById(uid);
List<SysRole> roles = roleService.findAll();
request.setAttribute("user", user);
request.setAttribute("userRoles", roles);
}
catch (Exception e)
{
return "/jsp/error";
}
return "/jsp/user/changePwd";
}
/**
*
* @param code 帐号
* @param request 请求
* @return 结果
*/
@RequestMapping("/user/findUserByCode")
public @ResponseBody int findUserByCode(@RequestParam("code") String code,
HttpServletRequest request)
{
int count = 0;
try
{
if (userService.findUserByCode(code) != 0)
{
count++;
}
}
catch (Exception e)
{
return count;
}
return count;
}
/**
*
* @param u 系统用户
* @param request 请求
* @return 返回
*/
@RequestMapping(value = "/user/updateUser", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody SysUser u,
HttpServletRequest request)
{
String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
try
{
userService.updateUser(u);
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "修改用户", 1, 1,
"");
}
catch (Exception e)
{
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "修改用户", 0, 1,
"");
return "error";
}
return "success";
}
/**
*
* @param u 系统用户
* @param request 请求
* @return 结果
*/
@RequestMapping(value = "/user/insertUser", produces =
{ "application/json;charset=UTF-8" })
public @ResponseBody String insertDept(@RequestBody SysUser u,
HttpServletRequest request)
{
String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
try
{
userService.insertUser(u);
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "添加用户", 1, 1,
"");
}
catch (Exception e)
{
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "添加用户", 0, 1,
"");
return ExceptionInfo.OPERATION_FAILURE;
}
return ExceptionInfo.OPERATION_SUCCESS;
}
/**
*
* @param id id
* @param request 请求
* @return 结果
*/
@RequestMapping(value = "/user/delUser", produces =
{ "application/json;charset=UTF-8" })
public @ResponseBody String delDept(@RequestParam("id") int id,
HttpServletRequest request)
{
String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
int res = 0;
try
{
res = userService.delUser(id);
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "删除用户", 1, 1,
"");
}
catch (Exception e)
{
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "删除用户", 0, 1,
"");
return ExceptionInfo.OPERATION_FAILURE;
}
return res == 1 ? ExceptionInfo.OPERATION_SUCCESS
: ExceptionInfo.DEPT_USERIN;
}
/**
*
* @param request 请求
* @return 返回
*/
@RequestMapping("/loginOut")
public String loginOut(HttpServletRequest request)
{
if (SecurityUtils.getSubject().getPrincipals() != null)
{
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "用户管理", "用户登出", 1, 1,
"");
}
return userService.loginOut(request);
}
/**
*
* @param logincode 登录帐号
* @param menuId 菜单id
* @return 结果
*/
@RequestMapping(value = "/user/checkMenuIdBycode")
public @ResponseBody boolean checkMenuIdBycode(
@RequestParam("logincode") String logincode,
@RequestParam("menuId") int menuId)
{
return userService.checkMenuIdBycode(logincode, menuId);
}
/**
* 查询该用户下的新用户申请次数
* @param menuId 菜单id
* @return 结果
*/
@RequestMapping(value = "/user/checkMenuId")
public @ResponseBody String checkMenuIdBycode(
@RequestParam("menuId") String menuId)
{
PrincipalCollection s = SecurityUtils.getSubject().getPrincipals();
if (null == s)
{
return "0_0";
}
String logincode = SecurityUtils.getSubject().getPrincipals()
.toString();
String[] menuIdArr = menuId.split("_");
boolean ischeck = userService.checkMenuIdBycode(logincode,
Integer.parseInt(menuIdArr[0]));
// 油卡申请的数量
int oilCardApplyNum = 0;
if (ischeck)
{
oilCardApplyNum = olicardService.queryMsg(logincode);
}
ischeck = userService.checkMenuIdBycode(logincode,
Integer.parseInt(menuIdArr[1]));
// 通行卡申请的数量
int passCardApplyNum = 0;
if (ischeck)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", OilConstant.DEAL_STATUS_WAIT); // 查找待处理状态
passCardApplyNum = passCardService.findPassCardApplySize(map);
}
return oilCardApplyNum + "_" + passCardApplyNum;
}
/**
*
* @return 结果
*/
@RequestMapping(value = "/returnNoLogin")
public @ResponseBody String returnNoLogin()
{
return "请登录";
}
public SysUserService getUserService()
{
return userService;
}
public void setUserService(SysUserService userService)
{
this.userService = userService;
}
}