Commit 3649c331 authored by 杨伊博's avatar 杨伊博

ok

parent 5285dd6e
<?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>com.example</groupId>
<artifactId>springboot-springSecurity4</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<mybatis.version>3.4.0</mybatis.version>
<mybatis-spring.version>1.3.0</mybatis-spring.version>
</properties>
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.yy.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.run;
/**
* Created by yangyibo on 17/1/17.
*/
@ComponentScan(basePackages ="com.yy.example")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
package com.yy.example.bean;
public class Permission {
private Integer id;
private String name;
private String permissionUrl;
private String method;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPermissionUrl() {
return permissionUrl;
}
public void setPermissionUrl(String permissionUrl) {
this.permissionUrl = permissionUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Permission{" +
"id=" + id +
", name=" + name +
", permissionUrl=" + permissionUrl +
", method=" + method +
", description=" + description +
'}';
}
}
\ No newline at end of file
package com.yy.example.bean;
public class Role implements Comparable<Role>{
private Integer id;
private String name;
private Integer roleLevel;
private String description;
private String menuItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoleLevel() {
return roleLevel;
}
public void setRoleLevel(Integer roleLevel) {
this.roleLevel = roleLevel;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMenuItems() {
return menuItems;
}
public void setMenuItems(String menuItems) {
this.menuItems = menuItems;
}
@Override
public int compareTo(Role o) {
if(id == o.getId()){
return 0;
}else if(id > o.getId()){
return 1;
}else{
return -1;
}
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Role){
if(this.id == ((Role)obj).getId()){
return true;
}
}
return false;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name=" + name +
", roleLevel=" + roleLevel +
", description=" + description +
'}';
}
}
\ No newline at end of file
package com.yy.example.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
public class User implements UserDetails {
private Integer id;
private String cnname;
private String username;
@JsonIgnore
private String password;
private String rePassword;
private String historyPassword;
private String email;
@JsonIgnore
private String telephone;
private String mobilePhone;
private List<? extends GrantedAuthority> authorities;
private Role role;
private Integer roleId;
@Override
@JsonIgnore
public boolean isAccountNonExpired() {
return true;
}
@Override
@JsonIgnore
public boolean isAccountNonLocked() {
return true;
}
@Override
@JsonIgnore
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@JsonIgnore
public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username;
}
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCnname() {
return cnname;
}
public void setCnname(String cnname) {
this.cnname = cnname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getRePassword() {
return rePassword;
}
public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getHistoryPassword() {
return historyPassword;
}
public void setHistoryPassword(String historyPassword) {
this.historyPassword = historyPassword;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
'}';
}
}
\ No newline at end of file
package com.yy.example.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import java.beans.PropertyVetoException;
@Configuration
public class DataSourceConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
package com.yy.example.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("**.dao");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
package com.yy.example.config;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(
ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setLogImpl(org.apache.ibatis.logging.log4j.Log4jImpl.class);//use log4j log
sessionFactory.setConfiguration(configuration);
sessionFactory.setMapperLocations(applicationContext.getResources("classpath:com/yy/example/mapper/*.xml"));
//
// Properties prop = new Properties();
// prop.setProperty("supportMethodsArguments","true");
// prop.setProperty("rowBoundsWithCount", "true");
// prop.setProperty("params","pageNum=pageNum;pageSize=pageSize;");
// PageInterceptor pi = new PageInterceptor();
// pi.setProperties(prop);
// sessionFactory.setPlugins(new Interceptor[]{pi});
return sessionFactory;
}
}
package com.yy.example.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisScannerConfig {
@Bean
public MapperScannerConfigurer MapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.us.example.dao");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
package com.yy.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
@Configuration
@ComponentScan
public class TransactionConfig implements TransactionManagementConfigurer{
@Autowired
private DataSource dataSource;
@Bean(name = "transactionManager")
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
\ No newline at end of file
package com.yy.example.config;
import com.yy.example.security.UrlUserService;
import com.yy.example.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* <Description> <br>
*
* @author henley<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2017年1月13日 <br>
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UrlUserService urlUserService;
@Autowired
SessionRegistry sessionRegistry;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/logout").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry)
.and()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(MD5Util.encode((String) rawPassword));
}
});
}
@Bean
public SessionRegistry getSessionRegistry(){
SessionRegistry sessionRegistry=new SessionRegistryImpl();
return sessionRegistry;
}
}
\ No newline at end of file
package com.yy.example.controller;
import com.yy.example.bean.User;
import com.yy.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LoginController {
@Autowired
UserService userService;
@RequestMapping(value = "/login")
@ResponseBody
public Object login(@AuthenticationPrincipal User loginedUser, @RequestParam(name = "logout", required = false) String logout) {
if (logout != null) {
return null;
}
if (loginedUser != null) {
return userService.getById(loginedUser.getId());
}
return null;
}
}
package com.yy.example.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RequestMapping(value = "/users")
@RestController
public class UserController {
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Object list(HttpServletRequest request) {
return "Get all User";
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Object detail(@PathVariable Integer id) {
return "Get a user";
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Object create(HttpServletRequest request) {
return "POST a user";
}
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public Object update(HttpServletRequest request) {
return "PUT a user";
}
}
\ No newline at end of file
package com.yy.example.dao;
import com.yy.example.bean.Permission;
import java.util.List;
import java.util.Map;
public interface PermissionDao {
List<Permission> getByMap(Map<String, Object> map);
Permission getById(Integer id);
Integer create(Permission permission);
int update(Permission permission);
List<Permission> getByUserId(Integer userId);
}
\ No newline at end of file
package com.yy.example.dao;
import com.yy.example.bean.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List<User> getByMap(Map<String, Object> map);
List<User> getByRoleId(Map<String, Object> map);
User getById(Integer id);
Integer create(User user);
int update(User user);
User getByUserName(String userName);
}
\ No newline at end of file
package com.yy.example.security;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
/**
* Created by yangyibo on 17/1/19.
*/
@Service
public class UrlAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
String url, method;
if ("anonymousUser".equals(authentication.getPrincipal())
|| matchers("/images/**", request)
|| matchers("/js/**", request)
|| matchers("/css/**", request)
|| matchers("/fonts/**", request)
|| matchers("/", request)
|| matchers("/index.html", request)
|| matchers("/favicon.ico", request)
|| matchers("/login", request)) {
return;
} else {
for (GrantedAuthority ga : authentication.getAuthorities()) {
if (ga instanceof UrlGrantedAuthority) {
UrlGrantedAuthority urlGrantedAuthority = (UrlGrantedAuthority) ga;
url = urlGrantedAuthority.getPermissionUrl();
method = urlGrantedAuthority.getMethod();
if (matchers(url, request)) {
if (method.equals(request.getMethod()) || "ALL".equals(method)) {
return;
}
}
}
}
}
throw new AccessDeniedException("no right");
}
@Override
public boolean supports(ConfigAttribute attribute) {
return true;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
private boolean matchers(String url, HttpServletRequest request) {
AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
if (matcher.matches(request)) {
return true;
}
return false;
}
}
package com.yy.example.security;
import org.springframework.security.access.ConfigAttribute;
import javax.servlet.http.HttpServletRequest;
/**
* Created by yangyibo on 17/2/15.
*/
public class UrlConfigAttribute implements ConfigAttribute {
private final HttpServletRequest httpServletRequest;
public UrlConfigAttribute(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
@Override
public String getAttribute() {
return null;
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
}
\ No newline at end of file
package com.yy.example.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import javax.servlet.*;
import java.io.IOException;
/**
* Created by yangyibo on 17/2/7.
*/
@Service
public class UrlFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
@Autowired
private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Autowired
public void setUrlAccessDecisionManager(UrlAccessDecisionManager urlAccessDecisionManager) {
super.setAccessDecisionManager(urlAccessDecisionManager);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用UrlMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用UrlAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
}
package com.yy.example.security;
import org.springframework.security.core.GrantedAuthority;
/**
* Created by yangyibo on 17/2/15.
*/
public class UrlGrantedAuthority implements GrantedAuthority {
private String permissionUrl;
private String method;
public String getPermissionUrl() {
return permissionUrl;
}
public void setPermissionUrl(String permissionUrl) {
this.permissionUrl = permissionUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public UrlGrantedAuthority (String permissionUrl, String method) {
this.permissionUrl = permissionUrl;
this.method = method;
}
@Override
public String getAuthority() {
return this.permissionUrl + ";"+this.method;
}
}
package com.yy.example.security;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Created by yangyibo on 17/1/19.
*/
@Service
public class UrlMetadataSourceService implements
FilterInvocationSecurityMetadataSource {
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
final HttpServletRequest request = ((FilterInvocation) object).getRequest();
Set<ConfigAttribute> allAttributes = new HashSet<>();
ConfigAttribute configAttribute = new UrlConfigAttribute(request);
allAttributes.add(configAttribute);
return allAttributes;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
package com.yy.example.security;
import com.yy.example.bean.Permission;
import com.yy.example.bean.User;
import com.yy.example.dao.PermissionDao;
import com.yy.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yangyibo on 17/2/7.
*/
@Service
public class UrlUserService implements UserDetailsService {
@Autowired
UserDao userDao;
@Autowired
PermissionDao permissionDao;
@Override
public UserDetails loadUserByUsername(String userName) { //重写loadUserByUsername 方法获得 userdetails 类型用户
User user = userDao.getByUserName(userName);
if (user != null) {
List<Permission> permissions = permissionDao.getByUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Permission permission : permissions) {
if (permission != null && permission.getName()!=null) {
GrantedAuthority grantedAuthority = new UrlGrantedAuthority(permission.getPermissionUrl(),permission.getMethod());
grantedAuthorities.add(grantedAuthority);
}
}
user.setGrantedAuthorities(grantedAuthorities);
return user;
} else {
throw new UsernameNotFoundException("admin: " + userName + " do not exist!");
}
}
}
\ No newline at end of file
package com.yy.example.service;
import com.yy.example.bean.User;
import com.yy.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private SessionRegistry sessionRegistry;
@Autowired
private UserDao userDao;
public User getById(Integer id) {
User user = userDao.getById(id);
return user;
}
}
\ No newline at end of file
package com.yy.example.utils;
/**
* Created by yangyibo on 17/2/7.
*/
import java.security.MessageDigest;
/**
* MD5加密工具
*
*/
public class MD5Util {
private static final String SALT = "yy";
private static final String WECAHT_SALT="yy_aa";
public static String encode(String password) {
password = password + SALT;
return processEncode(password);
}
/**
* 与微信模块约定的加密模块
* */
public static String wechatEncode(String password){
password = password + WECAHT_SALT;
return processEncode(password);
}
public static boolean wehcatValidation(String str, String token){
boolean flag = false;
if(wechatEncode(str).equals(token)){
flag = true;
}
return flag;
}
public static String processEncode(String password) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("abel"));
System.out.println(MD5Util.encode("admin"));
}
}
\ No newline at end of file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/epp_manager?useSSL=false&useUnicode=true&characterEncoding=UTF-8
#jdbc.url=jdbc:mysql://47.94.17.188:3306/epp_manager?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=admin
server.port=8088
logging.level.org.springframework.security= INFO
spring.thymeleaf.cache=false
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yy.example.dao.PermissionDao">
<resultMap id="permissionMap" type="com.yy.example.bean.Permission">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="permissionUrl" column="permission_url"/>
<result property="method" column="method"/>
<result property="description" column="description"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="permissionUrl != null and permissionUrl != ''">
and permission_url = #{permissionUrl}
</if>
<if test="method != null and method != ''">
and method = #{method}
</if>
<if test="description != null and description != ''">
and description = #{description}
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="permissionMap">
SELECT * FROM permission
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="permissionMap">
SELECT * FROM permission WHERE id =#{id}
</select>
<select id="getList" resultMap="permissionMap">
SELECT * from permission
</select>
<select id="getByUserId" parameterType="int" resultMap="permissionMap">
select p.*
from user u
LEFT JOIN user_role ur on u.id= ur.User_id
LEFT JOIN role r on ur.role_id=r.id
LEFT JOIN role_permission rp on rp.role_id=r.id
LEFT JOIN permission p on p.id =rp.permission_id
where u.id=#{userId}
</select>
<insert id="create" parameterType="com.yy.example.bean.Permission">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO permission(
id,
name,
permission_url,
method,
description
)VALUES(
#{id},
#{name},
#{permissionUrl},
#{method},
#{description}
)
</insert>
<update id="update" parameterType="com.yy.example.bean.Permission">
UPDATE permission SET
name = #{name},
permission_url = #{permissionUrl},
method = #{method},
description = #{description}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM permission WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yy.example.dao.UserDao">
<resultMap id="userMap" type="com.yy.example.bean.User">
<id property="id" column="id"/>
<result property="cnname" column="cnname"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="telephone" column="telephone"/>
<result property="mobilePhone" column="mobile_phone"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="cnname != null and cnname != ''">
and cnname = #{cnname}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
<if test="telephone != null and telephone != ''">
and telephone = #{telephone}
</if>
<if test="mobilePhone != null and mobilePhone != ''">
and mobile_phone = #{mobilePhone}
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="userMap">
SELECT u.* FROM user u
<include refid="queryCondition" />
ORDER by id DESC
</select>
<select id="getById" parameterType="int" resultMap="userMap">
SELECT * FROM user WHERE id =#{id}
</select>
<select id="getByUserName" parameterType="String" resultMap="userMap">
select u.* from user u
where username= #{username}
</select>
<insert id="create" parameterType="com.yy.example.bean.User">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user(
id,
cnname,
username,
password,
email,
telephone,
mobile_phone,
wechat_id,
skill,
department_id,
login_count
)VALUES(
#{id},
#{cnname},
#{username},
#{password},
#{email},
#{telephone},
#{mobilePhone},
#{wechatId},
#{skill},
#{departmentId},
#{loginCount}
)
</insert>
<update id="update" parameterType="com.yy.example.bean.User">
UPDATE user
<set>
<if test = "cnname != null and cnname != ''">
cnname = #{cnname},
</if>
<if test = "password != null and password != ''">
password = #{password},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
<if test="telephone != null and telephone != ''">
telephone = #{telephone},
</if>
<if test=" mobilePhone!= null and mobilePhone != ''">
mobile_phone = #{mobilePhone},
</if>
</set>
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment