├── src ├── main │ ├── java │ │ └── com │ │ │ └── luotuo │ │ │ ├── service │ │ │ ├── BaseResourceService.java │ │ │ ├── TestResourceService.java │ │ │ ├── UserWechatService.java │ │ │ ├── RolePrivilegeService.java │ │ │ ├── NativeSqlServiceImpl.java │ │ │ ├── UserRoleService.java │ │ │ ├── URIResourceService.java │ │ │ ├── UserResourcesService.java │ │ │ ├── UserPrivilegeService.java │ │ │ └── DepartmentService.java │ │ │ ├── MyExceptions │ │ │ ├── NullException.java │ │ │ └── AlreadyExistException.java │ │ │ ├── entity │ │ │ ├── TestResource.java │ │ │ ├── PlatformAndMenu.java │ │ │ └── BaseResource.java │ │ │ ├── wechat │ │ │ ├── bean │ │ │ │ ├── MediaGetResult.java │ │ │ │ ├── Jscode2sessionResult.java │ │ │ │ ├── SnsToken.java │ │ │ │ └── BaseResult.java │ │ │ ├── LocalResponseHandler.java │ │ │ ├── utils │ │ │ │ ├── JsonUtil.java │ │ │ │ ├── StringUtils.java │ │ │ │ ├── SignatureUtil.java │ │ │ │ ├── MapUtil.java │ │ │ │ ├── StreamUtils.java │ │ │ │ ├── XMLConverUtil.java │ │ │ │ └── JsUtil.java │ │ │ ├── sns │ │ │ │ └── BaseAPI.java │ │ │ ├── JsonResponseHandler.java │ │ │ ├── ResultErrorHandler.java │ │ │ ├── XmlResponseHandler.java │ │ │ ├── API.java │ │ │ ├── BytesOrJsonResponseHandler.java │ │ │ └── HttpClientFactory.java │ │ │ ├── repository │ │ │ └── TestResourceRepository.java │ │ │ ├── user │ │ │ ├── entity │ │ │ │ ├── Department.java │ │ │ │ ├── URIResource.java │ │ │ │ ├── Role.java │ │ │ │ ├── UserRole.java │ │ │ │ ├── DepartmentResponse.java │ │ │ │ ├── UserPrivilege.java │ │ │ │ ├── RolePrivilege.java │ │ │ │ ├── UserResponse.java │ │ │ │ ├── Resource.java │ │ │ │ ├── User.java │ │ │ │ ├── UserResources.java │ │ │ │ ├── UserWechat.java │ │ │ │ ├── PrivilegeConfig.java │ │ │ │ ├── PageResponse.java │ │ │ │ └── PrivilegeConfig1.java │ │ │ └── repository │ │ │ │ ├── URIResourceRepository.java │ │ │ │ ├── UserWechatRepository.java │ │ │ │ ├── ResourceRepository.java │ │ │ │ ├── RoleRepository.java │ │ │ │ ├── UserResourcesRepository.java │ │ │ │ ├── DepartmentRepository.java │ │ │ │ ├── UserRoleRepository.java │ │ │ │ ├── RolePrivilegeRepository.java │ │ │ │ ├── PrivilegeConfigRepository.java │ │ │ │ ├── UserPrivilegeRepository.java │ │ │ │ └── UserRepository.java │ │ │ ├── controller │ │ │ ├── UserResourcesController.java │ │ │ ├── RolePrivilegeController.java │ │ │ ├── LoginController.java │ │ │ ├── ResourceController.java │ │ │ └── BaseController.java │ │ │ ├── config │ │ │ ├── MyResourceServerTokenServices.java │ │ │ ├── Global.java │ │ │ ├── CorsFilter.java │ │ │ ├── MyPasswordEncoder.java │ │ │ ├── UserDsConfig.java │ │ │ ├── AuditDsConfig.java │ │ │ ├── MyAuthenticationSuccessHandler.java │ │ │ ├── MyOAuth2ClientAuthenticationProcessingFilter.java │ │ │ └── MySimpleUrlAuthenticationFailureHandler.java │ │ │ ├── security │ │ │ ├── RESTAuthenticationEntryPoint.java │ │ │ ├── RESTAuthenticationSuccessHandler.java │ │ │ └── RESTAuthenticationFailureHandler.java │ │ │ ├── global │ │ │ ├── EncryptionAlgs.java │ │ │ ├── Node.java │ │ │ ├── Constant.java │ │ │ └── result │ │ │ │ └── Response.java │ │ │ ├── custom │ │ │ ├── AuthorityInfo.java │ │ │ ├── MyFilterSecurityInterceptor.java │ │ │ ├── MyInvocationSecurityMetadataSourceService.java │ │ │ ├── UserInfo.java │ │ │ ├── CustomUserDetailsService.java │ │ │ └── MyAccessDecisionManager.java │ │ │ ├── utils │ │ │ ├── SystemConfig.java │ │ │ ├── JsonUtils.java │ │ │ ├── Format.java │ │ │ ├── SpecificationFactory.java │ │ │ ├── StringUtils.java │ │ │ ├── DateUtils.java │ │ │ └── HttpUtils.java │ │ │ ├── Application.java │ │ │ └── runner │ │ │ └── MyStartUpRunner1.java │ ├── resources │ │ ├── application.properties │ │ ├── application-weixin.properties │ │ └── logback.xml │ └── webapp │ │ └── WEB-INF │ │ └── jsp │ │ └── index.jsp └── test │ └── java │ └── com │ └── luotuo │ └── ApplicationTests.java ├── README.md └── .gitignore /src/main/java/com/luotuo/service/BaseResourceService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | 4 | public interface BaseResourceService { 5 | Object findAll() throws Exception; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=weixin 2 | ## mvn clean package -Dmaven.test.skip=true 3 | 4 | # mvn clean package spring-boot:repackage -Dmaven.test.skip=true 5 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/MyExceptions/NullException.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.MyExceptions; 2 | 3 | /** 4 | * Created by luotuo on 17-7-6. 5 | */ 6 | public class NullException extends Exception { 7 | public NullException(String msg) { 8 | super(msg); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/MyExceptions/AlreadyExistException.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.MyExceptions; 2 | 3 | /** 4 | * Created by luotuo on 17-7-6. 5 | */ 6 | public class AlreadyExistException extends Exception { 7 | public AlreadyExistException(String msg) { 8 | super(msg); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/entity/TestResource.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.Table; 7 | 8 | @Entity 9 | @Data 10 | @Table(name = "test_resource") 11 | public class TestResource extends BaseResource { 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/bean/MediaGetResult.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.bean; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class MediaGetResult extends BaseResult { 7 | private String filename; 8 | private String contentType; 9 | private byte[] bytes; 10 | private String video_url; //如果返回的是视频消息素材 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/bean/Jscode2sessionResult.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.bean; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by luotuo on 17-9-22. 7 | */ 8 | @Data 9 | public class Jscode2sessionResult extends BaseResult { 10 | private String openid; 11 | private String session_key; 12 | private Integer expires_in; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/repository/TestResourceRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.repository; 2 | 3 | import com.luotuo.entity.TestResource; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | 8 | @Repository 9 | public interface TestResourceRepository extends JpaRepository { 10 | } 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-security-wechat 2 | 3 | ### 目的 4 | * 此项目将springboot(1.5.3)与spring-security进行了集成 5 | * 此项目将微信登录集成到了spring-security中,使项目能够支持微信登录 6 | * 此项目配置了两个数据源,分别在AuditDsConfig.java和UserDsConfig.java中 7 | * 希望朋友们能够通过这个项目了解security配置(com.luotuo.custom以及com.luotuo.security包中的文件),并对security和Oauth2.0实现微信登录集成有所了解 8 | * 欢迎大家star和fork,并提交pr 9 | 10 | 11 | ### 感谢 12 | 感谢开源,感谢github! 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/LocalResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | public abstract class LocalResponseHandler{ 4 | 5 | protected String uriId; 6 | 7 | protected long startTime = System.currentTimeMillis(); 8 | 9 | public String getUriId() { 10 | return uriId; 11 | } 12 | 13 | public void setUriId(String uriId) { 14 | this.uriId = uriId; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/entity/PlatformAndMenu.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.entity; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by luotuo on 17-7-18. 7 | */ 8 | @Data 9 | public class PlatformAndMenu { 10 | /** 11 | * id 12 | */ 13 | private long id; 14 | /** 15 | * 平台 16 | */ 17 | private String platform; 18 | /** 19 | * 菜单 20 | */ 21 | private String menu; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/JsonUtil.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | 5 | public class JsonUtil { 6 | 7 | private JsonUtil(){} 8 | 9 | public static T parseObject(String json,Class clazz){ 10 | return JSON.parseObject(json, clazz); 11 | } 12 | 13 | public static String toJSONString(Object object){ 14 | return JSON.toJSONString(object); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/luotuo/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.luotuo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/bean/SnsToken.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.bean; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by luotuo on 17-9-22. 7 | */ 8 | @Data 9 | public class SnsToken extends BaseResult { 10 | private String access_token; 11 | private Integer expires_in; 12 | private String refresh_token; 13 | private String openid; 14 | private String scope; 15 | private String unionid; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/Department.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | 7 | /** 8 | * Created by luotuo on 17-6-29. 9 | */ 10 | @Entity 11 | @Table(name = "department") 12 | @Data 13 | public class Department { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private long id; 17 | private long pid; 18 | private String name; 19 | private int level; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/bean/BaseResult.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.bean; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * 微信请求状态数据 7 | * 8 | * @author LiYi 9 | */ 10 | @Data 11 | public class BaseResult { 12 | private static final String SUCCESS_CODE = "0"; 13 | private String errcode; 14 | private String errmsg; 15 | 16 | public boolean isSuccess() { 17 | return errcode == null || errcode.isEmpty() || errcode.equals(SUCCESS_CODE); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | public class StringUtils { 4 | 5 | public static String arrayToDelimitedString(Object[] arr, String delim) { 6 | if (arr == null || arr.length == 0) { 7 | return ""; 8 | } 9 | StringBuilder sb = new StringBuilder(); 10 | for (int i = 0; i < arr.length; i++) { 11 | if (i > 0) { 12 | sb.append(delim); 13 | } 14 | sb.append(arr[i]); 15 | } 16 | return sb.toString(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/controller/UserResourcesController.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.controller; 2 | 3 | import com.luotuo.service.UserResourcesService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | @Controller 9 | @RequestMapping("/userResources") 10 | public class UserResourcesController extends BaseController{ 11 | @Autowired 12 | private UserResourcesService userResourcesService; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/TestResourceService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.repository.TestResourceRepository; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public class TestResourceService implements BaseResourceService { 9 | @Autowired 10 | private TestResourceRepository testResourceRepository; 11 | @Override 12 | public Object findAll() throws Exception { 13 | return testResourceRepository.findAll(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/controller/RolePrivilegeController.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.controller; 2 | 3 | import com.luotuo.service.RolePrivilegeService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | /** 9 | * Created by luotuo on 17-7-13. 10 | */ 11 | @Controller 12 | @RequestMapping("/rolePrivilege") 13 | public class RolePrivilegeController extends BaseController { 14 | 15 | @Autowired 16 | private RolePrivilegeService rolePrivilegeService; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/URIResourceRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.URIResource; 4 | 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import javax.persistence.Table; 10 | 11 | /** 12 | * Created by luotuo on 17-6-29. 13 | */ 14 | @Repository 15 | @Table(name = "uri_resource") 16 | @Qualifier("uriResourceRepository") 17 | public interface URIResourceRepository extends JpaRepository { 18 | } 19 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8" %> 3 | 4 | 5 | 6 | 7 | GOD 8 | 9 | 10 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/UserWechatRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.User; 4 | import com.luotuo.user.entity.UserWechat; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | 8 | import javax.persistence.Table; 9 | 10 | /** 11 | * Created by luotuo on 17-9-22. 12 | */ 13 | @Table(name = "user_wechat") 14 | public interface UserWechatRepository extends JpaRepository { 15 | @Query(value = "select bean from UserWechat bean where openid = ?1") 16 | UserWechat getByOpenId(String openId); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/URIResource.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | 5 | /** 6 | * Created by luotuo on 17-6-29. 7 | */ 8 | @Entity 9 | @Table(name = "uri_resource") 10 | public class URIResource { 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.IDENTITY) 13 | private Long id; 14 | 15 | private String uri; 16 | 17 | public Long getId() { 18 | return id; 19 | } 20 | 21 | public void setId(Long id) { 22 | this.id = id; 23 | } 24 | 25 | public String getUri() { 26 | return uri; 27 | } 28 | 29 | public void setUri(String uri) { 30 | this.uri = uri; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/ResourceRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.Resource; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.stereotype.Repository; 9 | 10 | @Repository 11 | public interface ResourceRepository extends JpaRepository,JpaSpecificationExecutor { 12 | 13 | @Query(value = "select bean from Resource bean where bean.resourceId = ?1") 14 | Resource findByResourceId(String resourceId); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/MyResourceServerTokenServices.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 5 | import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; 6 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 7 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 8 | 9 | /** 10 | * Created by luotuo on 17-9-28. 11 | */ 12 | public interface MyResourceServerTokenServices extends ResourceServerTokenServices { 13 | OAuth2Authentication loadAuthentication(String var1, String var2) throws AuthenticationException, InvalidTokenException; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/security/RESTAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.security; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | @Component 13 | public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint { 14 | 15 | @Override 16 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) 17 | throws IOException, ServletException { 18 | 19 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/UserWechatService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.UserWechat; 4 | import com.luotuo.user.repository.UserWechatRepository; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import javax.annotation.Resource; 9 | 10 | /** 11 | * Created by luotuo on 17-9-22. 12 | */ 13 | @Service 14 | @Transactional("secondTransactionManager") 15 | public class UserWechatService { 16 | @Resource 17 | private UserWechatRepository userWechatRepository; 18 | 19 | public UserWechat save(UserWechat userWechat) { 20 | return userWechatRepository.save(userWechat); 21 | } 22 | 23 | public UserWechat getByOpenId(String openId) { 24 | return userWechatRepository.getByOpenId(openId); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/global/EncryptionAlgs.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.global; 2 | 3 | import java.math.BigInteger; 4 | import java.security.MessageDigest; 5 | 6 | /** 7 | * Created by luotuo on 17-7-18. 8 | */ 9 | public class EncryptionAlgs { 10 | public static String getMD5(String str) { 11 | try { 12 | // 生成一个MD5加密计算摘要 13 | MessageDigest md = MessageDigest.getInstance("MD5"); 14 | // 计算md5函数 15 | md.update(str.getBytes("UTF-8")); 16 | // digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 17 | // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 18 | return new BigInteger(1, md.digest()).toString(16); 19 | } catch (Exception e) { 20 | System.out.println(e.toString()); 21 | return ""; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | log/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ 26 | 27 | # ---> Java 28 | *.class 29 | 30 | # Mobile Tools for Java (J2ME) 31 | .mtj.tmp/ 32 | 33 | # Package Files # 34 | *.jar 35 | *.war 36 | *.ear 37 | 38 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 39 | hs_err_pid* 40 | 41 | # ---> Maven 42 | target/ 43 | pom.xml.tag 44 | pom.xml.releaseBackup 45 | pom.xml.versionsBackup 46 | pom.xml.next 47 | release.properties 48 | dependency-reduced-pom.xml 49 | buildNumber.properties 50 | .mvn/timing.properties 51 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/security/RESTAuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.security; 2 | import org.springframework.security.core.Authentication; 3 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 4 | import org.springframework.stereotype.Component; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | 11 | @Component 12 | public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 13 | 14 | @Override 15 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 16 | Authentication authentication) throws IOException, ServletException { 17 | 18 | clearAuthenticationAttributes(request); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/entity/BaseResource.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | 7 | /** 8 | * 资源基类,如果想让系统某个entity成为资源,必须具有下列属性 9 | */ 10 | 11 | @Data 12 | @MappedSuperclass 13 | public class BaseResource { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | protected Long id; 17 | /** 18 | * 编号 19 | */ 20 | protected String code; 21 | /** 22 | * 名称 23 | */ 24 | protected String name; 25 | /** 26 | * 类型 27 | */ 28 | @Column(columnDefinition = "char(50) not null default ''") 29 | protected String type; 30 | /** 31 | * 资源是否被添加进资源列表 32 | */ 33 | @Column(name = "is_used") 34 | protected int isUsed; 35 | /** 36 | * 资源唯一id,由资源类型+资源原始id经过md5得到 37 | */ 38 | @Column(name = "resource_id") 39 | protected String resourceId; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/security/RESTAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.security; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | @Component 13 | public class RESTAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 14 | 15 | @Override 16 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 17 | AuthenticationException exception) throws IOException, ServletException { 18 | 19 | super.onAuthenticationFailure(request, response, exception); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | /** 7 | * Created by luotuo on 17-6-30. 8 | */ 9 | @Entity 10 | @Table(name = "roles") 11 | public class Role implements Serializable { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private long id; 15 | 16 | private String code; 17 | private String name; 18 | 19 | public long getId() { 20 | return id; 21 | } 22 | 23 | public void setId(long id) { 24 | this.id = id; 25 | } 26 | 27 | public String getCode() { 28 | return code; 29 | } 30 | 31 | public void setCode(String code) { 32 | this.code = code; 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public void setName(String name) { 40 | this.name = name; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.Role; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.data.repository.query.Param; 9 | import org.springframework.stereotype.Repository; 10 | 11 | import javax.persistence.Table; 12 | 13 | /** 14 | * Created by luotuo on 17-7-4. 15 | */ 16 | @Repository 17 | @Table(name = "roles") 18 | @Qualifier("rolesRepository") 19 | public interface RoleRepository extends JpaRepository { 20 | Role findByCode(String code); 21 | Role findById(long id); 22 | @Modifying 23 | @Query(value="delete from Role bean where code = :code", nativeQuery = false) 24 | void deleteByCode(@Param("code") String code); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/global/Node.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.global; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by luotuo on 17-7-4. 8 | */ 9 | public class Node { 10 | private Long id; 11 | private Long pid; 12 | Object value; 13 | private List children; 14 | 15 | public Long getId() { 16 | return id; 17 | } 18 | 19 | public void setId(Long id) { 20 | this.id = id; 21 | } 22 | 23 | public Long getPid() { 24 | return pid; 25 | } 26 | 27 | public void setPid(Long pid) { 28 | this.pid = pid; 29 | } 30 | 31 | public Object getValue() { 32 | return value; 33 | } 34 | 35 | public void setValue(Object value) { 36 | this.value = value; 37 | } 38 | 39 | public List getChildren() { 40 | return children; 41 | } 42 | 43 | public void setChildren(List children) { 44 | this.children = children; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/sns/BaseAPI.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.sns; 2 | 3 | import org.apache.http.Header; 4 | import org.apache.http.HttpHeaders; 5 | import org.apache.http.entity.ContentType; 6 | import org.apache.http.message.BasicHeader; 7 | 8 | public abstract class BaseAPI { 9 | protected static final String BASE_URI = "https://api.weixin.qq.com"; 10 | protected static final String MEDIA_URI = "http://file.api.weixin.qq.com"; 11 | protected static final String MP_URI = "https://mp.weixin.qq.com"; 12 | protected static final String MCH_URI = "https://api.mch.weixin.qq.com"; 13 | protected static final String OPEN_URI = "https://open.weixin.qq.com"; 14 | 15 | protected static Header jsonHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE,ContentType.APPLICATION_JSON.toString()); 16 | protected static Header xmlHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE,ContentType.APPLICATION_XML.toString()); 17 | 18 | protected static final String PARAM_ACCESS_TOKEN = "access_token"; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/Global.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | /** 6 | * Created by liuma on 2017/6/5. 7 | */ 8 | public class Global { 9 | public static final int DEFAULT_PAGE_SIZE=20;//分页使用,每页条数 10 | public static final int DEFAULT_PAGE_NUM=0;//分页使用,第几页 11 | 12 | 13 | public static final String wechatAppId = "yourwechatappid"; 14 | public static final String wechatSecretKey = "yourwechatsecret"; 15 | 16 | public static String getIpAddr(HttpServletRequest request) { 17 | String ip = request.getHeader("x-forwarded-for"); 18 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 19 | ip = request.getHeader("Proxy-Client-IP"); 20 | } 21 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 22 | ip = request.getHeader("WL-Proxy-Client-IP"); 23 | } 24 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 25 | ip = request.getRemoteAddr(); 26 | } 27 | return ip; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/UserResourcesRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.UserResources; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.util.List; 11 | 12 | @Repository 13 | public interface UserResourcesRepository extends JpaRepository,JpaSpecificationExecutor { 14 | @Modifying 15 | @Query(value = "delete from UserResources bean where bean.resourceId = ?1") 16 | void deleteByResourceId(String resourceId); 17 | 18 | @Modifying 19 | @Query(value = "delete from UserResources bean where bean.userId in ?1") 20 | void deleteByUserIds(List userIds); 21 | 22 | @Modifying 23 | @Query(value = "delete from UserResources bean where bean.resourceId in ?1") 24 | void deleteByResourceIds(List resourceIds); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/DepartmentRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.Department; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import javax.persistence.Table; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by luotuo on 17-7-3. 14 | */ 15 | @Repository 16 | @Table(name = "department") 17 | @Qualifier("privilegeConfigRepository") 18 | public interface DepartmentRepository extends JpaRepository { 19 | 20 | Department findById(long id); 21 | 22 | @Query(value="select bean from Department bean where level = ?1", nativeQuery = false) 23 | List findByLevel(int level); 24 | 25 | @Query(value="select bean from Department bean where pid = ?1", nativeQuery = false) 26 | List findByPid(long pid); 27 | 28 | @Query(value = "select bean from Department bean where name = ?1") 29 | List getByName(String name); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | /** 7 | * Created by luotuo on 17-7-13. 8 | */ 9 | @Entity 10 | @Table(name = "user_role") 11 | public class UserRole implements Serializable { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private long id; 15 | private long user_id; 16 | private long role_id; 17 | private String role_name; 18 | 19 | public long getId() { 20 | return id; 21 | } 22 | 23 | public void setId(long id) { 24 | this.id = id; 25 | } 26 | 27 | public long getUser_id() { 28 | return user_id; 29 | } 30 | 31 | public void setUser_id(long user_id) { 32 | this.user_id = user_id; 33 | } 34 | 35 | public long getRole_id() { 36 | return role_id; 37 | } 38 | 39 | public void setRole_id(long role_id) { 40 | this.role_id = role_id; 41 | } 42 | 43 | public String getRole_name() { 44 | return role_name; 45 | } 46 | 47 | public void setRole_name(String role_name) { 48 | this.role_name = role_name; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/UserRoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.UserRole; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import javax.persistence.Table; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by luotuo on 17-7-13. 14 | */ 15 | @Repository 16 | @Table(name = "user_role") 17 | public interface UserRoleRepository extends JpaRepository { 18 | 19 | @Modifying 20 | @Query(value="delete from UserRole bean where user_id = ?1") 21 | void deleteByUser_id(Long userId); 22 | 23 | @Query(value = "select bean from UserRole bean where user_id=?1") 24 | List findByUser_id(long userId); 25 | 26 | @Query(value = "select bean from UserRole bean where role_name=?1") 27 | List findByName(String name); 28 | 29 | @Query(value = "select bean from UserRole bean where role_id=?1") 30 | List findByRole_id(Long id); 31 | 32 | @Query(value = "select bean from UserRole bean where role_id in ?1") 33 | List findByRoleIds(List roleIds); 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/AuthorityInfo.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | 4 | import org.springframework.security.core.GrantedAuthority; 5 | 6 | /** 7 | * Created by luotuo on 17-6-26. 8 | */ 9 | public class AuthorityInfo implements GrantedAuthority { 10 | private static final long serialVersionUID = -175781100474818800L; 11 | 12 | public String getUrl() { 13 | return url; 14 | } 15 | 16 | public void setUrl(String url) { 17 | this.url = url; 18 | } 19 | 20 | /** 21 | * 权限URL 22 | */ 23 | private String url; 24 | 25 | public String getMethod() { 26 | return method; 27 | } 28 | 29 | public void setMethod(String method) { 30 | this.method = method; 31 | } 32 | 33 | private String method; 34 | 35 | public AuthorityInfo(String url, String method) { 36 | this.url = url; 37 | this.method = method; 38 | } 39 | 40 | public AuthorityInfo(String url) { 41 | this.url = url; 42 | this.method = ""; 43 | } 44 | 45 | @Override 46 | public String getAuthority() { 47 | return this.url + ";" + this.method; 48 | } 49 | 50 | public void setAuthority(String url, String method) { 51 | this.url = url; 52 | this.method = method; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/RolePrivilegeRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.RolePrivilege; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import javax.persistence.Table; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by luotuo on 17-7-13. 14 | */ 15 | @Repository 16 | @Table(name = "role_privilege") 17 | public interface RolePrivilegeRepository extends JpaRepository { 18 | @Query(value = "select bean from RolePrivilege bean where role_id=?1") 19 | List findByRole_id(Long roleId); 20 | 21 | @Modifying 22 | @Query(value = "delete from RolePrivilege bean where role_id = ?1 and privilege_id = ?2") 23 | void deletePrivilegeByRoleId(Long roleId, Long privilegeId); 24 | 25 | @Modifying 26 | @Query(value = "delete from RolePrivilege bean where role_id = ?1 and privilege_id in ?2") 27 | void deletePrivilegesByRoleId(Long roleId, List privilegeIds); 28 | 29 | @Query(value = "select bean from RolePrivilege bean where role_id in ?1") 30 | List findByRoleIds(List roleIds); 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/global/Constant.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.global; 2 | 3 | /** 4 | * Created by luotuo on 17-6-7. 5 | */ 6 | public class Constant { 7 | public enum ResourceType { 8 | PROJECT("project"), 9 | TASK("task"), 10 | REPORT("report"); 11 | 12 | public String getTypeName() { 13 | return typeName; 14 | } 15 | 16 | private String typeName; 17 | ResourceType(String typeName) { 18 | this.typeName = typeName; 19 | } 20 | } 21 | 22 | public enum ControllerType { 23 | GET("get"), 24 | EDIT("edit"), 25 | DELETE("delete"), 26 | ADD("add"); 27 | 28 | public String getTypeName() { 29 | return typeName; 30 | } 31 | 32 | private String typeName; 33 | ControllerType(String typeName) { this.typeName = typeName; } 34 | } 35 | 36 | public enum UserRoleType { 37 | AUDITMAN("audit_man"), 38 | AUDITLEADER("audit_leader"), 39 | PROJECTMANAGER("project_manager"), 40 | BUSINESSMANAGER("business_manager"), 41 | REVIEWER("reviewer"); 42 | public String getTypeName() { 43 | return typeName; 44 | } 45 | 46 | private String typeName; 47 | UserRoleType(String typeName) { this.typeName = typeName; } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/global/result/Response.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.global.result; 2 | 3 | 4 | /** 5 | * Created by luotuo on 17-6-1. 6 | */ 7 | public class Response { 8 | public static final int SUCCEED=1; 9 | public static final int ERROR=0; 10 | public static final int RESOURCELOCKED=0;//资源占用 11 | 12 | private int success; 13 | private String message; 14 | private Object result; 15 | 16 | public Response(int success, String message, Object obj) { 17 | this.success = success; 18 | this.message = message; 19 | this.result = obj; 20 | } 21 | 22 | public Response(){} 23 | 24 | public int getSuccess() { 25 | return success; 26 | } 27 | 28 | public void setSuccess(int success) { 29 | this.success = success; 30 | } 31 | 32 | public String getMessage() { 33 | return message; 34 | } 35 | 36 | public void setMessage(String message) { 37 | this.message = message; 38 | } 39 | 40 | public Object getResult() { 41 | return result; 42 | } 43 | 44 | public void setResult(Object result) { 45 | this.result = result; 46 | } 47 | 48 | public void buildResponse(int success, String message, Object obj) { 49 | this.success = success; 50 | this.message = message; 51 | this.result = obj; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/DepartmentResponse.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | /** 4 | * Created by luotuo on 17-7-25. 5 | */ 6 | public class DepartmentResponse { 7 | private long id; 8 | private long pid; 9 | private String name; 10 | private int level; 11 | private String pName; 12 | 13 | public long getId() { 14 | return id; 15 | } 16 | 17 | public void setId(long id) { 18 | this.id = id; 19 | } 20 | 21 | public long getPid() { 22 | return pid; 23 | } 24 | 25 | public void setPid(long pid) { 26 | this.pid = pid; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public int getLevel() { 38 | return level; 39 | } 40 | 41 | public void setLevel(int level) { 42 | this.level = level; 43 | } 44 | 45 | public String getpName() { 46 | return pName; 47 | } 48 | 49 | public void setpName(String pName) { 50 | this.pName = pName; 51 | } 52 | 53 | public void set(Department d, String pName) { 54 | this.id = d.getId(); 55 | this.name = d.getName(); 56 | this.pid = d.getPid(); 57 | this.level = d.getLevel(); 58 | this.pName = pName; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/UserPrivilege.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | /** 7 | * Created by luotuo on 17-6-30. 8 | */ 9 | @Entity 10 | @Table(name = "user_privilege") 11 | public class UserPrivilege implements Serializable { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private Long id; 15 | 16 | //@OneToOne(cascade = CascadeType.ALL) 17 | //@JoinColumn(name = "user_id") 18 | private Long user_id; 19 | 20 | //@OneToOne(cascade = CascadeType.ALL) 21 | //@JoinColumn(name = "privilege_config_id") 22 | private Long privilege_id; 23 | 24 | private String privilege_name; 25 | 26 | 27 | public String getPrivilege_name() { 28 | return privilege_name; 29 | } 30 | 31 | public void setPrivilege_name(String privilege_name) { 32 | this.privilege_name = privilege_name; 33 | } 34 | 35 | public Long getId() { 36 | return id; 37 | } 38 | 39 | public void setId(Long id) { 40 | this.id = id; 41 | } 42 | 43 | public Long getUser_id() { 44 | return user_id; 45 | } 46 | 47 | public void setUser_id(Long user_id) { 48 | this.user_id = user_id; 49 | } 50 | 51 | public Long getPrivilege_id() { 52 | return privilege_id; 53 | } 54 | 55 | public void setPrivilege_id(Long privilege_id) { 56 | this.privilege_id = privilege_id; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/RolePrivilege.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | /** 7 | * Created by luotuo on 17-7-13. 8 | */ 9 | @Entity 10 | @Table(name = "role_privilege") 11 | public class RolePrivilege implements Serializable { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private long id; 15 | 16 | private long role_id; 17 | private String role_name; 18 | private long privilege_id; 19 | private String privilege_name; 20 | 21 | public long getId() { 22 | return id; 23 | } 24 | 25 | public void setId(long id) { 26 | this.id = id; 27 | } 28 | 29 | public long getRole_id() { 30 | return role_id; 31 | } 32 | 33 | public void setRole_id(long role_id) { 34 | this.role_id = role_id; 35 | } 36 | 37 | public String getRole_name() { 38 | return role_name; 39 | } 40 | 41 | public void setRole_name(String role_name) { 42 | this.role_name = role_name; 43 | } 44 | 45 | public long getPrivilege_id() { 46 | return privilege_id; 47 | } 48 | 49 | public void setPrivilege_id(long privilege_id) { 50 | this.privilege_id = privilege_id; 51 | } 52 | 53 | public String getPrivilege_name() { 54 | return privilege_name; 55 | } 56 | 57 | public void setPrivilege_name(String privilege_name) { 58 | this.privilege_name = privilege_name; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by luotuo on 17-7-21. 7 | */ 8 | @Data 9 | public class UserResponse { 10 | private long id; 11 | private String name; 12 | private String department; 13 | private String phone; 14 | private String email; 15 | private int state; 16 | private String state_str; 17 | private String icons; 18 | private String password; 19 | private String wechat; 20 | private String roles; 21 | private Object privileges; 22 | private String lastIp; 23 | private int hasLogin; 24 | private String wechatOpenId; 25 | private int bindWechat = 0; 26 | private String wechatHeadimgurl; 27 | private int hasJoin; 28 | 29 | public void setUserResponse(User user, String roles) { 30 | this.roles = roles; 31 | this.id = user.getId(); 32 | this.department = user.getDepartment(); 33 | this.email = user.getEmail(); 34 | this.icons = user.getIcons(); 35 | this.name = user.getName(); 36 | this.phone = user.getPhone(); 37 | this.password = user.getPassword(); 38 | this.state = user.getState(); 39 | this.state_str = user.getState_str(); 40 | this.wechat = user.getWechat(); 41 | this.lastIp = user.getLast_ip(); 42 | this.hasLogin = user.getHas_login(); 43 | this.wechatHeadimgurl = user.getWechat_headimgurl(); 44 | this.wechatOpenId = user.getWechat_open_id(); 45 | this.bindWechat = user.getBind_wechat(); 46 | this.hasJoin = user.getHas_join(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/RolePrivilegeService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.RolePrivilege; 4 | import com.luotuo.user.repository.RolePrivilegeRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by luotuo on 17-7-13. 13 | */ 14 | @Service 15 | @Transactional("secondTransactionManager") 16 | public class RolePrivilegeService { 17 | 18 | @Autowired 19 | private RolePrivilegeRepository rolePrivilegeRepository; 20 | 21 | public void deleteByRoleId(long roleId) { 22 | 23 | } 24 | 25 | public void deleteByPrivilegeId(long privilegeId) { 26 | 27 | } 28 | 29 | public Iterable save(Iterable privileges) { 30 | return rolePrivilegeRepository.save(privileges); 31 | } 32 | 33 | public List findByRoleId(long roleId) { 34 | return rolePrivilegeRepository.findByRole_id(roleId); 35 | } 36 | 37 | public List findByRoleIds(List roleIds) { 38 | return rolePrivilegeRepository.findByRoleIds(roleIds); 39 | } 40 | 41 | @Transactional 42 | public void deletePrivilegeByRoleId(long roleId, long privilegeId) { 43 | rolePrivilegeRepository.deletePrivilegeByRoleId(roleId, privilegeId); 44 | } 45 | 46 | @Transactional 47 | public void deletePrivilegesByRoleId(long roleId, List privilegsIds) { 48 | rolePrivilegeRepository.deletePrivilegesByRoleId(roleId, privilegsIds); 49 | } 50 | 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/PrivilegeConfigRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.PrivilegeConfig; 4 | 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import javax.persistence.Table; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by luotuo on 17-6-30. 15 | */ 16 | @Repository 17 | @Table(name = "privilege_config") 18 | @Qualifier("privilegeConfigRepository") 19 | public interface PrivilegeConfigRepository extends JpaRepository { 20 | PrivilegeConfig findById(long id); 21 | 22 | @Query(value="select bean from PrivilegeConfig bean where level = ?1", nativeQuery = false) 23 | List findByLevel(int level); 24 | @Query(value="select bean from PrivilegeConfig bean where pid = ?1", nativeQuery = false) 25 | List findByPid(long pid); 26 | 27 | @Query(value = "select id, platform, `name` from privilege_config where `type`='菜单' GROUP BY id, platform, `name`", nativeQuery = true) 28 | List findPlatformsAndMenus(); 29 | 30 | @Query(value = "select bean from PrivilegeConfig bean where id in ?1") 31 | List findByIds(List ids); 32 | 33 | @Query(value = "select bean from PrivilegeConfig bean where id in ?1 and level=?2") 34 | List findByIdsAndLevel(List ids, Integer level); 35 | 36 | @Query(value = "select bean from PrivilegeConfig bean where id in ?1 and pid = ?2") 37 | List findByIdsAndPid(List ids, Long pid); 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/Resource.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import com.luotuo.entity.BaseResource; 4 | import com.luotuo.global.EncryptionAlgs; 5 | import lombok.Data; 6 | import org.codehaus.jackson.map.Serializers; 7 | 8 | import javax.persistence.*; 9 | 10 | @Data 11 | @Entity 12 | @Table(name = "resource") 13 | public class Resource { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private long id; 17 | 18 | /** 19 | * 资源类型 20 | */ 21 | @Column(name = "resource_type", columnDefinition = "char(50) not null default ''") 22 | private String resourceType; 23 | /** 24 | * 资源唯一id,由资源类型+资源原始id经过md5得到 25 | */ 26 | @Column(name = "resource_id") 27 | private String resourceId; 28 | /** 29 | * 资源原始id 30 | */ 31 | @Column(name = "resource_origin_id", columnDefinition = "bigint not null default 0") 32 | private long resourceOriginId; 33 | /** 34 | * 资源名称 35 | */ 36 | @Column(name = "resource_name") 37 | private String resourceName; 38 | 39 | public Resource() {} 40 | 41 | public Resource(String type, long resourceOriginId, String name) { 42 | this.resourceOriginId = resourceOriginId; 43 | this.resourceType = type; 44 | this.resourceId = EncryptionAlgs.getMD5(type + resourceOriginId); 45 | this.resourceName = name; 46 | } 47 | 48 | public Resource(BaseResource baseResource) { 49 | this.resourceOriginId = baseResource.getId(); 50 | this.resourceName = baseResource.getName(); 51 | this.resourceType = baseResource.getType(); 52 | this.resourceId = EncryptionAlgs.getMD5(this.resourceType + this.resourceOriginId); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/CorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | /** 4 | * Created by luotuo on 17-6-19. 5 | */ 6 | import org.springframework.core.annotation.Order; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | 12 | import javax.servlet.*; 13 | import javax.servlet.annotation.WebFilter; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import java.io.IOException; 17 | 18 | @Order(1) 19 | @WebFilter(filterName = "corsFilter", urlPatterns = "/*") 20 | public class CorsFilter implements Filter { 21 | 22 | final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class); 23 | 24 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 25 | HttpServletResponse response = (HttpServletResponse) res; 26 | HttpServletRequest reqs = (HttpServletRequest)req; 27 | response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin")); 28 | response.setHeader("Access-Control-Allow-Credentials", "true"); 29 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 30 | response.setHeader("Access-Control-Max-Age", "3600"); 31 | response.setHeader("Access-Control-Allow-Headers", "X-Request-With, JWCQ, Origin,Content-Type"); 32 | response.setCharacterEncoding("UTF-8"); 33 | System.out.println("======CORS====="); 34 | chain.doFilter(req, res); 35 | } 36 | 37 | public void init(FilterConfig filterConfig) {} 38 | public void destroy() {} 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created by luotuo on 17-6-29. 10 | */ 11 | @Entity 12 | @Table(name = "user") 13 | @Data 14 | public class User implements Serializable { 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | private String name="测试账户"; 19 | private String department; 20 | private String phone; 21 | private String email; 22 | private int state; 23 | private String state_str; 24 | private String icons; 25 | private String password; 26 | private String wechat; 27 | private String last_ip; 28 | private int has_login = 0; 29 | private String resume;//用户简介 30 | private String title; //用户头衔 31 | private String city; //用户所在地 【新增】 32 | private long user_wechat_id; 33 | private String wechat_open_id; 34 | private int bind_wechat = 0; 35 | private String wechat_headimgurl; 36 | private int has_join = 1; 37 | 38 | public User() {} 39 | public User(UserWechat userWechat) { 40 | this.wechat_open_id = userWechat.getOpenid(); 41 | this.user_wechat_id = userWechat.getId(); 42 | this.password = "3audit-luotuo-1234567654321"; 43 | this.state = 1; 44 | this.state_str = "正常"; 45 | this.wechat_headimgurl = userWechat.getHeadimgurl(); 46 | this.bind_wechat = 1; 47 | } 48 | 49 | public void bindWechat(UserWechat userWechat) { 50 | this.user_wechat_id = userWechat.getId(); 51 | this.wechat_headimgurl = userWechat.getHeadimgurl(); 52 | this.wechat_open_id = userWechat.getOpenid(); 53 | this.bind_wechat = 1; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/JsonResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.http.HttpEntity; 6 | import org.apache.http.HttpResponse; 7 | import org.apache.http.client.ClientProtocolException; 8 | import org.apache.http.client.ResponseHandler; 9 | import org.apache.http.util.EntityUtils; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import com.luotuo.wechat.utils.JsonUtil; 14 | 15 | public class JsonResponseHandler{ 16 | 17 | private static Logger logger = LoggerFactory.getLogger(JsonResponseHandler.class); 18 | 19 | public static ResponseHandler createResponseHandler(final Class clazz){ 20 | return new JsonResponseHandlerImpl(null,clazz); 21 | } 22 | 23 | public static class JsonResponseHandlerImpl extends LocalResponseHandler implements ResponseHandler { 24 | 25 | private Class clazz; 26 | 27 | public JsonResponseHandlerImpl(String uriId, Class clazz) { 28 | this.uriId = uriId; 29 | this.clazz = clazz; 30 | } 31 | 32 | @Override 33 | public T handleResponse(HttpResponse response) 34 | throws ClientProtocolException, IOException { 35 | int status = response.getStatusLine().getStatusCode(); 36 | if (status >= 200 && status < 300) { 37 | HttpEntity entity = response.getEntity(); 38 | String str = EntityUtils.toString(entity,"utf-8"); 39 | logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}",super.uriId,System.currentTimeMillis()-super.startTime,str); 40 | return JsonUtil.parseObject(str, clazz); 41 | } else { 42 | throw new ClientProtocolException("Unexpected response status: " + status); 43 | } 44 | } 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/SystemConfig.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import org.springframework.core.io.ClassPathResource; 4 | import org.springframework.core.io.Resource; 5 | import org.springframework.core.io.support.PropertiesLoaderUtils; 6 | 7 | import java.io.IOException; 8 | import java.util.Properties; 9 | 10 | /** 11 | * Created by liuma on 2017/9/7. 12 | */ 13 | public class SystemConfig { 14 | private static Properties props; 15 | 16 | public SystemConfig() { 17 | 18 | try { 19 | Resource resource = new ClassPathResource("/application.properties"); 20 | props = PropertiesLoaderUtils.loadProperties(resource); 21 | String truePath="/application-"+props.getProperty("spring.profiles.active")+".properties"; 22 | resource = new ClassPathResource(truePath); 23 | props= PropertiesLoaderUtils.loadProperties(resource); 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | 29 | 30 | /** 31 | * 获取属性 32 | * 33 | * @param key 34 | * @return 35 | */ 36 | public static String getProperty(String key) { 37 | if (props == null) new SystemConfig(); 38 | return props == null ? null : props.getProperty(key); 39 | } 40 | 41 | /** 42 | * 获取属性 43 | * 44 | * @param key 属性key 45 | * @param defaultValue 属性value 46 | * @return 47 | */ 48 | public static String getProperty(String key, String defaultValue) { 49 | 50 | return props == null ? null : props.getProperty(key, defaultValue); 51 | 52 | } 53 | 54 | /** 55 | * 获取properyies属性 56 | * 57 | * @return 58 | */ 59 | public static Properties getProperties() { 60 | return props; 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.controller; 2 | 3 | import com.luotuo.user.entity.User; 4 | import com.luotuo.utils.SystemConfig; 5 | import org.codehaus.jackson.map.Serializers; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.ResponseBody; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | /** 14 | * Created by luotuo on 17-9-28. 15 | */ 16 | @Controller 17 | public class LoginController extends BaseController { 18 | /** 19 | * 如果使用HTML head中 20 | * 21 | * 增加ResponseBody注解 22 | */ 23 | // @RequestMapping(method= {RequestMethod.GET,RequestMethod.POST}, value = "/") 24 | // public String login(HttpServletRequest request) { 25 | // return "index"; 26 | // } 27 | 28 | /** 29 | * 微信登录成功后访问 30 | * @param request 31 | * @return 32 | */ 33 | @ResponseBody 34 | @RequestMapping(method= {RequestMethod.GET,RequestMethod.POST}, value = "/") 35 | public String login(HttpServletRequest request) { 36 | User user = getUser(); 37 | String responseStr = ""; 38 | String param = SystemConfig.getProperty("app.server.base.url") +"/view/login.html"; 39 | if (user != null) { 40 | param = SystemConfig.getProperty("callback.path.project"); 41 | } 42 | responseStr = String.format(responseStr, param); 43 | System.out.println("log ----: "+responseStr); 44 | return responseStr; 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/NativeSqlServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import javax.persistence.EntityManager; 6 | import javax.persistence.EntityManagerFactory; 7 | import javax.persistence.PersistenceUnit; 8 | import javax.persistence.Query; 9 | import java.util.List; 10 | 11 | /** 12 | * Created by luotuo on 17-6-7. 13 | */ 14 | @Service 15 | public class NativeSqlServiceImpl { 16 | @PersistenceUnit 17 | private EntityManagerFactory emf; 18 | 19 | /** 20 | * 查询多个属性 21 | * 返回List数组形式的List,数组中内容按照查询字段先后 22 | * @param sql 原生SQL语句 23 | * @return 24 | */ 25 | public List sqlArrayList(String sql){ 26 | EntityManager em=emf.createEntityManager(); 27 | Query query=em.createNativeQuery(sql); 28 | List list = query.getResultList(); 29 | em.close(); 30 | return list; 31 | } 32 | 33 | /** 34 | * 查询多个属性 35 | * 返回List对象形式的List,Object为Class格式对象 36 | * @param sql 原生SQL语句 37 | * @param obj Class格式对象 38 | * @return 39 | */ 40 | public List sqlObjectList(String sql, Object obj){ 41 | EntityManager em=emf.createEntityManager(); 42 | Query query=em.createNativeQuery(sql,obj.getClass()); 43 | List list = query.getResultList(); 44 | em.close(); 45 | return list; 46 | } 47 | 48 | /** 49 | * 查询单个属性 50 | * 返回List对象形式的List,Object为对象数据类型 51 | * @param sql 原生SQL语句 52 | * @return 53 | */ 54 | public List sqlSingleList(String sql){ 55 | EntityManager em=emf.createEntityManager(); 56 | Query query=em.createNativeQuery(sql); 57 | List list = query.getResultList(); 58 | em.close(); 59 | return list; 60 | } 61 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/UserRoleService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.UserRole; 4 | import com.luotuo.user.repository.UserRoleRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by luotuo on 17-7-13. 13 | */ 14 | @Service 15 | @Transactional("secondTransactionManager") 16 | public class UserRoleService { 17 | @Autowired 18 | private UserRoleRepository userRoleRepository; 19 | 20 | @Transactional 21 | public void deleteByUserId(long userId) { 22 | userRoleRepository.deleteByUser_id(userId); 23 | } 24 | 25 | public List save(Iterable userRoles) { 26 | return userRoleRepository.save(userRoles); 27 | } 28 | 29 | public UserRole save(UserRole userRole) { 30 | return userRoleRepository.save(userRole); 31 | } 32 | 33 | public List findByUserId(long userId) { 34 | return userRoleRepository.findByUser_id(userId); 35 | } 36 | 37 | public List findByName(String name) { return userRoleRepository.findByName(name); } 38 | 39 | public List findByRoleId(long id) { return userRoleRepository.findByRole_id(id); } 40 | 41 | public String getUserRoleNamesByUserId(long userId) { 42 | String res = ""; 43 | List userRoles = findByUserId(userId); 44 | if (userRoles.size() <= 0) 45 | return res; 46 | for (UserRole u : userRoles) { 47 | res += u.getRole_name() + ","; 48 | } 49 | res = res.substring(0, res.length() - 1); 50 | return res; 51 | } 52 | 53 | public List findByRoleIds(List roleIds) { 54 | return userRoleRepository.findByRoleIds(roleIds); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/controller/ResourceController.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.controller; 2 | 3 | import com.luotuo.global.result.Response; 4 | import com.luotuo.service.ResourceService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | @Controller 15 | @RequestMapping("/resource") 16 | public class ResourceController extends BaseController { 17 | @Autowired 18 | private ResourceService resourceService; 19 | 20 | /** 21 | * @name 查询资源 22 | * @param resourceType 资源类型 23 | * @param resourceName 资源名称 24 | * @param page 分页的页码 25 | * @param size 每页大小 26 | * @param request 27 | * @return 28 | */ 29 | @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/search") 30 | @ResponseBody 31 | public Response search(@RequestParam(value = "resourceType", required = false, defaultValue = "") String resourceType, 32 | @RequestParam(value = "resourceName", required = false, defaultValue = "") String resourceName, 33 | @RequestParam(value = "page", required = false, defaultValue = "0") String page, 34 | @RequestParam(value = "size", required = false, defaultValue = "20") String size, 35 | HttpServletRequest request) { 36 | Object res = null; 37 | try { 38 | res = resourceService.search(resourceType, resourceName, Integer.valueOf(page), Integer.valueOf(size)); 39 | } catch (Exception e) { 40 | return errorResponse("查询失败" + e.getMessage(), e.toString()); 41 | } 42 | return successResponse("查询成功", res); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/Application.java: -------------------------------------------------------------------------------- 1 | package com.luotuo; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 8 | 9 | import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; 10 | import org.springframework.boot.builder.SpringApplicationBuilder; 11 | import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; 12 | import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; 13 | import org.springframework.boot.web.servlet.ServletComponentScan; 14 | import org.springframework.boot.web.support.SpringBootServletInitializer; 15 | import org.springframework.context.annotation.ComponentScan; 16 | import org.springframework.context.annotation.Configuration; 17 | import org.springframework.scheduling.annotation.EnableScheduling; 18 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 19 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; 20 | import org.springframework.stereotype.Component; 21 | 22 | 23 | @SpringBootApplication 24 | @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 25 | @ComponentScan(basePackages={"com.luotuo"}) 26 | @ServletComponentScan 27 | @EnableOAuth2Client 28 | @EnableAuthorizationServer 29 | public class Application extends SpringBootServletInitializer { 30 | public static void main(String[] args) { 31 | SpringApplication.run(Application.class, args); 32 | } 33 | 34 | // @Bean 35 | // public EmbeddedServletContainerCustomizer containerCustomizer(){ 36 | // return new EmbeddedServletContainerCustomizer() { 37 | // @Override 38 | // public void customize(ConfigurableEmbeddedServletContainer container) { 39 | // container.setSessionTimeout(Global.sEXPIREDTIME);//单位为S 40 | // } 41 | // }; 42 | // } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/UserResources.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import com.luotuo.global.EncryptionAlgs; 4 | import lombok.Data; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Data 10 | @Table(name = "user_resources") 11 | public class UserResources { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private long id; 15 | 16 | /** 17 | * 用户id 18 | */ 19 | @Column(name = "user_id") 20 | private long userId; 21 | 22 | /** 23 | * 用户名 24 | */ 25 | @Column(name = "user_name") 26 | private String userName; 27 | /** 28 | * 资源唯一id,由资源类型+资源原始id经过md5得到 29 | */ 30 | @Column(name = "resource_id") 31 | private String resourceId; 32 | /** 33 | * 资源原始id 34 | */ 35 | @Column(name = "resource_origin_id", columnDefinition = "bigint not null default 0") 36 | private long resourceOriginId; 37 | /** 38 | * 资源类型 39 | */ 40 | @Column(name = "resource_type", columnDefinition = "char(50) not null default ''") 41 | private String resourceType; 42 | 43 | /** 44 | * 资源名称 45 | */ 46 | @Column(name = "resource_name") 47 | private String resourceName; 48 | 49 | public UserResources() {} 50 | 51 | public UserResources(User user, long resourceOriginId, String resourceType, String name) { 52 | this.userId = user.getId(); 53 | this.resourceOriginId = resourceOriginId; 54 | this.resourceType = resourceType; 55 | this.resourceName = name; 56 | this.resourceId = EncryptionAlgs.getMD5(resourceType + resourceOriginId); 57 | this.userName = user.getName(); 58 | } 59 | 60 | public UserResources(User user, Resource resource) { 61 | this.userId = user.getId(); 62 | this.userName = user.getName(); 63 | this.resourceId = resource.getResourceId(); 64 | this.resourceType = resource.getResourceType(); 65 | this.resourceOriginId = resource.getResourceOriginId(); 66 | this.resourceName = resource.getResourceName(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/UserPrivilegeRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.UserPrivilege; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import javax.persistence.Table; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by luotuo on 17-6-30. 15 | */ 16 | @Repository 17 | @Table(name = "user_privilege") 18 | public interface UserPrivilegeRepository extends JpaRepository { 19 | @Modifying 20 | @Query(value="delete from UserPrivilege bean where user_id = ?1", nativeQuery = false) 21 | void deleteByUser_id(Long userId); 22 | 23 | @Query(value = "select bean from UserPrivilege bean where user_id=?1") 24 | List findByUser_id(Long userId); 25 | 26 | @Modifying 27 | @Query(value="delete from UserPrivilege bean where user_id = ?1 and privilege_id = ?2", nativeQuery = false) 28 | void deletePrivilegeByUserId(Long userId, long privilegeId); 29 | 30 | @Modifying 31 | @Query(value = "delete from UserPrivilege bean where user_id = ?1 and privilege_id in ?2") 32 | void deletePrivilegesByUserId(Long userId, List privilegeIds); 33 | 34 | @Modifying 35 | @Query(value = "delete from UserPrivilege bean where privilege_id = ?1") 36 | void deleteByPrivilegeId(Long privilegeId); 37 | 38 | @Modifying 39 | @Query(value = "delete from UserPrivilege bean where privilege_id in ?1") 40 | void deleteByPrivilegeIds(List privilegeIds); 41 | 42 | @Modifying 43 | @Query(value = "delete from UserPrivilege bean where user_id in ?1 and privilege_id = ?2") 44 | void deleteByUserIdsAndPrivilegeId(List userIds, Long privilegeId); 45 | 46 | @Modifying 47 | @Query(value = "delete from UserPrivilege bean where user_id in ?1 and privilege_id in ?2") 48 | void deleteByUserIdsAndPrivilegeIds(List userIds, List privilegeIds); 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/UserWechat.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by luotuo on 17-9-21. 10 | */ 11 | @Entity 12 | @Table(name = "user_wechat") 13 | @Data 14 | public class UserWechat { 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | private Integer subscribe; //用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。 19 | private String openid; //用户的标识,对当前公众号唯一 20 | private String nickname; 21 | //private String nickname_emoji; //昵称 表情转义 22 | private String sex; //用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 23 | private String language; 24 | private String city; 25 | private String province; 26 | private String country; 27 | private String headimgurl; 28 | private Integer subscribe_time; 29 | private String[] privilege; //sns 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom) 30 | private String unionid; //多个公众号之间用户帐号互通UnionID机制 31 | private Integer groupid; 32 | private String remark; //公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注 33 | private Integer[] tagid_list; //用户被打上的标签ID列表 34 | public UserWechat() {} 35 | public UserWechat(Map attrs) { 36 | this.unionid = attrs.get("unionid") == null ? "" : (String) attrs.get("unionid"); 37 | this.city = attrs.get("city") == null ? "" : (String) attrs.get("city"); 38 | this.country = attrs.get("country") == null ? "" : (String) attrs.get("country"); 39 | this.headimgurl = attrs.get("headimgurl") == null ? "" : (String) attrs.get("headimgurl"); 40 | this.nickname = attrs.get("nickname") == null ? "" : (String) attrs.get("nickname"); 41 | this.openid = attrs.get("openid") == null ? "" : (String) attrs.get("openid"); 42 | this.province = attrs.get("province") == null ? "" : (String)attrs.get("province"); 43 | this.sex = attrs.get("sex") == null ? "" : attrs.get("sex").toString(); 44 | if (this.sex.equals("1")) this.sex = "男"; 45 | else if (this.sex.equals("2")) this.sex = "女"; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/runner/MyStartUpRunner1.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.runner; 2 | 3 | import com.luotuo.service.URIResourceService; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.method.HandlerMethod; 10 | import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; 11 | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 12 | 13 | import java.util.ArrayList; 14 | import java.util.Comparator; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | /** 19 | * Created by luotuo on 17-6-29. 20 | */ 21 | @Component 22 | public class MyStartUpRunner1 implements CommandLineRunner { 23 | 24 | @Autowired 25 | private URIResourceService uriResourceService; 26 | 27 | @Autowired 28 | ApplicationContext applicationContext; 29 | 30 | @Override 31 | public void run(String... args) throws Exception { 32 | System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行更新URI操作<<<<<<<<<<<<<"); 33 | UpdateURIResource(); 34 | } 35 | 36 | private void UpdateURIResource() { 37 | List uris = getAllRequestMappingInfo(); 38 | List allURIs = uriResourceService.getAll(); 39 | for (String uri: uris ) { 40 | if (!allURIs.contains(uri)) 41 | uriResourceService.save(uri); 42 | } 43 | } 44 | 45 | private List getAllRequestMappingInfo() { 46 | AbstractHandlerMethodMapping objHandlerMethodMapping = (AbstractHandlerMethodMapping)applicationContext.getBean("requestMappingHandlerMapping"); 47 | Map mapRet = objHandlerMethodMapping.getHandlerMethods(); 48 | List res = new ArrayList(); 49 | for (Map.Entry entry : mapRet.entrySet()) { 50 | String uri = entry.getKey().toString().replace("{", "").replace("[", "").replace("}","").replace("]",""); 51 | String []temp = uri.split(","); 52 | res.add(temp[0]); 53 | } 54 | return res; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/URIResourceService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.repository.URIResourceRepository; 4 | import com.luotuo.user.entity.URIResource; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.data.domain.PageRequest; 8 | import org.springframework.data.domain.Sort; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | import java.util.ArrayList; 13 | import java.util.Comparator; 14 | import java.util.List; 15 | 16 | /** 17 | * Created by luotuo on 17-6-29. 18 | */ 19 | 20 | @Service 21 | @Transactional("secondTransactionManager") 22 | public class URIResourceService { 23 | 24 | @Autowired 25 | private URIResourceRepository uriResourceRepository; 26 | 27 | public URIResource save(String uriStr) { 28 | URIResource uri = new URIResource(); 29 | Sort sort = new Sort(Sort.Direction.DESC, "id"); 30 | PageRequest pageRequest = new PageRequest(0, 1, sort); 31 | Iterable uriResource = uriResourceRepository.findAll(pageRequest); 32 | for (URIResource u: uriResource) { 33 | uri.setId(u.getId() + 1); 34 | } 35 | uri.setUri(uriStr); 36 | return uriResourceRepository.save(uri); 37 | } 38 | 39 | public List getAll() { 40 | List uriResources = uriResourceRepository.findAll(); 41 | List uriStrs = new ArrayList(); 42 | for (URIResource uri: uriResources) { 43 | uriStrs.add(uri.getUri()); 44 | } 45 | return uriStrs; 46 | } 47 | 48 | public List getAllForWeb() { 49 | List uriResources = uriResourceRepository.findAll(); 50 | List uriStrs = new ArrayList(); 51 | for (URIResource uri: uriResources) { 52 | if (uri.getUri().contains("/error")) 53 | continue; 54 | uriStrs.add(uri.getUri()); 55 | } 56 | uriStrs.sort(new Comparator() {//排序 57 | @Override 58 | public int compare(String o1, String o2) { 59 | return o1.compareTo(o2); 60 | } 61 | }); 62 | return uriStrs; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/ResultErrorHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | import com.luotuo.wechat.bean.BaseResult; 4 | import org.apache.http.HttpEntity; 5 | import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 6 | import org.apache.http.client.methods.HttpUriRequest; 7 | import org.apache.http.entity.ContentType; 8 | import org.apache.http.util.EntityUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import com.luotuo.wechat.bean.BaseResult; 13 | import com.luotuo.wechat.utils.JsonUtil; 14 | 15 | /** 16 | * 返回数据错误处理 17 | * 18 | * @since 2.8.3 19 | * @author SHYL 20 | * 21 | */ 22 | public abstract class ResultErrorHandler { 23 | 24 | private static Logger logger = LoggerFactory.getLogger(ResultErrorHandler.class); 25 | 26 | /** 27 | * 数据错误检查 28 | * @param result 返回数据 29 | * @return boolean 30 | */ 31 | private boolean isError(Object result) { 32 | if(result != null){ 33 | if(result instanceof BaseResult){ 34 | BaseResult baseResult = (BaseResult)result; 35 | return !baseResult.isSuccess(); 36 | } 37 | } 38 | return false; 39 | } 40 | 41 | protected void doHandle(String uriId,HttpUriRequest request,Object result){ 42 | if(this.isError(result)){ 43 | String content = null; 44 | if(request instanceof HttpEntityEnclosingRequestBase){ 45 | HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; 46 | HttpEntity entity = request_base.getEntity(); 47 | //MULTIPART_FORM_DATA 请求类型判断 48 | if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ 49 | try { 50 | content = EntityUtils.toString(entity); 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | } 55 | if(logger.isErrorEnabled()){ 56 | logger.error("URI[{}] {} Content:{} Result:{}", 57 | uriId, 58 | request.getURI(), 59 | content == null ? "multipart_form_data" : content, 60 | result == null? null : JsonUtil.toJSONString(result)); 61 | } 62 | } 63 | this.handle(uriId,request.getURI().toString(),content,result); 64 | } 65 | } 66 | 67 | /** 68 | * 数据错误处理 69 | * @param uriId uriId 70 | * @param uri uri 71 | * @param requestEntity 请求entity数据 72 | * @param result 返回的数据 73 | */ 74 | protected abstract void handle(String uriId,String uri,String requestEntity,Object result); 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/MyFilterSecurityInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.access.SecurityMetadataSource; 5 | import org.springframework.security.access.intercept.AbstractSecurityInterceptor; 6 | import org.springframework.security.access.intercept.InterceptorStatusToken; 7 | import org.springframework.security.web.FilterInvocation; 8 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.servlet.*; 12 | import java.io.IOException; 13 | 14 | /** 15 | * Created by luotuo on 17-7-3. 16 | */ 17 | @Service 18 | public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { 19 | @Autowired 20 | private FilterInvocationSecurityMetadataSource securityMetadataSource; 21 | 22 | @Autowired 23 | public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) { 24 | super.setAccessDecisionManager(myAccessDecisionManager); 25 | } 26 | 27 | @Override 28 | public void init(FilterConfig filterConfig) throws ServletException { 29 | 30 | } 31 | 32 | @Override 33 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 34 | FilterInvocation fi = new FilterInvocation(request, response, chain); 35 | invoke(fi); 36 | } 37 | 38 | public void invoke(FilterInvocation fi) throws IOException, ServletException { 39 | //fi里面有一个被拦截的url 40 | //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限 41 | //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够 42 | InterceptorStatusToken token = super.beforeInvocation(fi); 43 | try { 44 | //执行下一个拦截器 45 | fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); 46 | } finally { 47 | super.afterInvocation(token, null); 48 | } 49 | } 50 | 51 | @Override 52 | public void destroy() { 53 | 54 | } 55 | 56 | @Override 57 | public Class getSecureObjectClass() { 58 | return FilterInvocation.class; 59 | } 60 | 61 | @Override 62 | public SecurityMetadataSource obtainSecurityMetadataSource() { 63 | return this.securityMetadataSource; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/XmlResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | import java.io.IOException; 4 | import java.util.Map; 5 | 6 | import org.apache.http.Header; 7 | import org.apache.http.HttpEntity; 8 | import org.apache.http.HttpResponse; 9 | import org.apache.http.client.ClientProtocolException; 10 | import org.apache.http.client.ResponseHandler; 11 | import org.apache.http.util.EntityUtils; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | import com.luotuo.wechat.utils.SignatureUtil; 16 | import com.luotuo.wechat.utils.XMLConverUtil; 17 | 18 | public class XmlResponseHandler{ 19 | 20 | private static Logger logger = LoggerFactory.getLogger(XmlResponseHandler.class); 21 | 22 | public static ResponseHandler createResponseHandler(Class clazz){ 23 | return new XmlResponseHandlerImpl(null, clazz,null,null); 24 | } 25 | 26 | public static ResponseHandler createResponseHandler(Class clazz,String sign_type,String key){ 27 | return new XmlResponseHandlerImpl(null, clazz,sign_type,key); 28 | } 29 | 30 | public static class XmlResponseHandlerImpl extends LocalResponseHandler implements ResponseHandler { 31 | 32 | private Class clazz; 33 | 34 | private String sign_type; 35 | 36 | //签名校验key 37 | private String key; 38 | 39 | public XmlResponseHandlerImpl(String uriId, Class clazz,String sign_type,String key) { 40 | this.uriId = uriId; 41 | this.clazz = clazz; 42 | this.sign_type = sign_type; 43 | this.key = key; 44 | } 45 | 46 | @Override 47 | public T handleResponse(HttpResponse response) 48 | throws ClientProtocolException, IOException { 49 | int status = response.getStatusLine().getStatusCode(); 50 | if (status >= 200 && status < 300) { 51 | HttpEntity entity = response.getEntity(); 52 | String str = EntityUtils.toString(entity); 53 | Header contentType = response.getEntity().getContentType(); 54 | if(contentType!=null&&!contentType.toString().matches(".*[uU][tT][fF]-8$")){ 55 | str = new String(str.getBytes("iso-8859-1"),"utf-8"); 56 | } 57 | logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}",super.uriId,System.currentTimeMillis()-super.startTime,str); 58 | T t = XMLConverUtil.convertToObject(clazz,str); 59 | return t; 60 | } else { 61 | throw new ClientProtocolException("Unexpected response status: " + status); 62 | } 63 | 64 | } 65 | 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/MyPasswordEncoder.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import com.sun.istack.NotNull; 4 | import org.springframework.security.crypto.password.PasswordEncoder; 5 | 6 | import java.math.BigInteger; 7 | import java.security.MessageDigest; 8 | 9 | /** 10 | * Created by luotuo on 17-9-26. 11 | */ 12 | public class MyPasswordEncoder implements PasswordEncoder { 13 | @NotNull 14 | private final String encodingAlgorithm; 15 | 16 | public MyPasswordEncoder(final String encodingAlgorithm) { 17 | this.encodingAlgorithm = encodingAlgorithm; 18 | } 19 | 20 | public MyPasswordEncoder() {this("2");} 21 | 22 | public String encode(CharSequence rawPassword) { 23 | String password = rawPassword.toString(); 24 | if (encodingAlgorithm.equals("0")) { 25 | // MD5 26 | return md5Alg(password); 27 | } else if (encodingAlgorithm.equals("1")) { 28 | // MD5 with salt 29 | return md5WithSaltAlg(password); 30 | } else { 31 | // clear text 32 | return clearText(password); 33 | } 34 | } 35 | 36 | private String clearText(final String password) { 37 | return password; 38 | } 39 | 40 | private String md5Alg(final String password) { 41 | try { 42 | MessageDigest md = MessageDigest.getInstance("MD5"); 43 | // 计算md5函数 44 | md.update(password.getBytes("UTF-8")); 45 | // digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 46 | // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 47 | return new BigInteger(1, md.digest()).toString(16); 48 | } catch (Exception e) { 49 | return password; 50 | } 51 | } 52 | 53 | private String md5WithSaltAlg(final String password) { 54 | try { 55 | MessageDigest md = MessageDigest.getInstance("MD5"); 56 | // 计算md5函数 57 | md.update(password.getBytes("UTF-8")); 58 | // digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 59 | // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 60 | return new BigInteger(1, md.digest()).toString(16); 61 | } catch (Exception e) { 62 | return password; 63 | } 64 | } 65 | 66 | public boolean matches(CharSequence rawPassword, String encodedPassword) { 67 | if(encodedPassword != null && encodedPassword.length() != 0) { 68 | return encode(rawPassword).equals(encodedPassword); 69 | } else { 70 | return false; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/PrivilegeConfig.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import javax.persistence.*; 4 | 5 | /** 6 | * Created by luotuo on 17-6-30. 7 | */ 8 | @Entity 9 | @Table(name = "privilege_config") 10 | public class PrivilegeConfig { 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.IDENTITY) 13 | private long id; 14 | 15 | private long pid; 16 | private int level; 17 | private String level_str; 18 | private String name; 19 | private String type; 20 | private String value; 21 | private String url; 22 | private int state; 23 | private String state_str; 24 | private String platform; 25 | 26 | public String getPlatform() { 27 | return platform; 28 | } 29 | 30 | public void setPlatform(String platform) { 31 | this.platform = platform; 32 | } 33 | 34 | public long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(long id) { 39 | this.id = id; 40 | } 41 | 42 | public long getPid() { 43 | return pid; 44 | } 45 | 46 | public void setPid(long pid) { 47 | this.pid = pid; 48 | } 49 | 50 | public int getLevel() { 51 | return level; 52 | } 53 | 54 | public void setLevel(int level) { 55 | this.level = level; 56 | } 57 | 58 | public String getLevel_str() { 59 | return level_str; 60 | } 61 | 62 | public void setLevel_str(String level_str) { 63 | this.level_str = level_str; 64 | } 65 | 66 | public String getName() { 67 | return name; 68 | } 69 | 70 | public void setName(String name) { 71 | this.name = name; 72 | } 73 | 74 | public String getType() { 75 | return type; 76 | } 77 | 78 | public void setType(String type) { 79 | this.type = type; 80 | } 81 | 82 | public String getValue() { 83 | return value; 84 | } 85 | 86 | public void setValue(String value) { 87 | this.value = value; 88 | } 89 | 90 | public String getUrl() { 91 | return url; 92 | } 93 | 94 | public void setUrl(String url) { 95 | this.url = url; 96 | } 97 | 98 | public int getState() { 99 | return state; 100 | } 101 | 102 | public void setState(int state) { 103 | this.state = state; 104 | } 105 | 106 | public String getState_str() { 107 | return state_str; 108 | } 109 | 110 | public void setState_str(String state_str) { 111 | this.state_str = state_str; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/PageResponse.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | import org.springframework.data.domain.Page; 4 | 5 | /** 6 | * Created by luotuo on 17-7-24. 7 | */ 8 | public class PageResponse { 9 | private Object content; 10 | private Boolean last; 11 | private Integer totalPages; 12 | private Long totalElements; 13 | private Boolean first; 14 | private Object sort; 15 | private Integer numberOfElements; 16 | private Integer size; 17 | private Integer number; 18 | 19 | public Object getContent() { 20 | return content; 21 | } 22 | 23 | public void setContent(Object content) { 24 | this.content = content; 25 | } 26 | 27 | public Boolean getLast() { 28 | return last; 29 | } 30 | 31 | public void setLast(Boolean last) { 32 | this.last = last; 33 | } 34 | 35 | public Integer getTotalPages() { 36 | return totalPages; 37 | } 38 | 39 | public void setTotalPages(Integer totalPages) { 40 | this.totalPages = totalPages; 41 | } 42 | 43 | public Long getTotalElements() { 44 | return totalElements; 45 | } 46 | 47 | public void setTotalElements(Long totalElements) { 48 | this.totalElements = totalElements; 49 | } 50 | 51 | public Boolean getFirst() { 52 | return first; 53 | } 54 | 55 | public void setFirst(Boolean first) { 56 | this.first = first; 57 | } 58 | 59 | public Object getSort() { 60 | return sort; 61 | } 62 | 63 | public void setSort(Object sort) { 64 | this.sort = sort; 65 | } 66 | 67 | public Integer getNumberOfElements() { 68 | return numberOfElements; 69 | } 70 | 71 | public void setNumberOfElements(Integer numberOfElements) { 72 | this.numberOfElements = numberOfElements; 73 | } 74 | 75 | public Integer getSize() { 76 | return size; 77 | } 78 | 79 | public void setSize(Integer size) { 80 | this.size = size; 81 | } 82 | 83 | public Integer getNumber() { 84 | return number; 85 | } 86 | 87 | public void setNumber(Integer number) { 88 | this.number = number; 89 | } 90 | 91 | public void set(Page pages) { 92 | this.setFirst(pages.isFirst()); 93 | this.setLast(pages.isLast()); 94 | this.setNumber(pages.getNumber()); 95 | this.setNumberOfElements(pages.getNumberOfElements()); 96 | this.setSize(pages.getSize()); 97 | this.setSort(pages.getSort()); 98 | this.setTotalElements(pages.getTotalElements()); 99 | this.setTotalPages(pages.getTotalPages()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/UserResourcesService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.Resource; 4 | import com.luotuo.user.entity.User; 5 | import com.luotuo.user.entity.UserResources; 6 | import com.luotuo.user.repository.UserResourcesRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Service 15 | @Transactional("secondTransactionManager") 16 | public class UserResourcesService { 17 | @Autowired 18 | private UserResourcesRepository userResourcesRepository; 19 | 20 | /** 21 | * @name 给一个人添加一些资源 22 | * @param resources 23 | * @param user 24 | * @throws Exception 25 | */ 26 | public void addResourcesToUser(List resources, User user) throws Exception { 27 | if (resources.isEmpty()) 28 | throw new Exception("资源不能为空"); 29 | if (user == null) 30 | throw new Exception("用户不能为空"); 31 | List userResources = new ArrayList<>(); 32 | for (Resource r : resources) { 33 | UserResources userResources1 = new UserResources(user, r); 34 | userResources.add(userResources1); 35 | } 36 | userResourcesRepository.save(userResources); 37 | } 38 | 39 | /** 40 | * @name 给一个资源添加一些人 41 | * @param users 42 | * @param resource 43 | * @throws Exception 44 | */ 45 | public void addUsersToResource(List users, Resource resource) throws Exception { 46 | if (users.isEmpty()) 47 | throw new Exception("用户不能为空"); 48 | if (resource == null) 49 | throw new Exception("资源不能为空"); 50 | List userResources = new ArrayList<>(); 51 | for (User u : users) { 52 | UserResources userResources1 = new UserResources(u, resource); 53 | userResources.add(userResources1); 54 | } 55 | userResourcesRepository.save(userResources); 56 | } 57 | 58 | /** 59 | * @name 给一个用户增加一个资源/给一个资源增加一个用户 60 | * @param user 61 | * @param resource 62 | * @throws Exception 63 | */ 64 | public void addUserToResource(User user, Resource resource) throws Exception { 65 | if (user == null || resource == null) 66 | throw new Exception("用户和资源都不能为空"); 67 | UserResources userResources = new UserResources(user, resource); 68 | userResourcesRepository.save(userResources); 69 | } 70 | 71 | /** 72 | * @name 删除一个用户资源 73 | * @param userResourceId 74 | * @throws Exception 75 | */ 76 | public void deleteUserResource(Long userResourceId) throws Exception { 77 | userResourcesRepository.delete(userResourceId); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.repository; 2 | 3 | import com.luotuo.user.entity.User; 4 | 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.data.jpa.repository.JpaRepository; 9 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 10 | import org.springframework.data.jpa.repository.Modifying; 11 | import org.springframework.data.jpa.repository.Query; 12 | import org.springframework.stereotype.Repository; 13 | 14 | import javax.persistence.Table; 15 | import java.util.List; 16 | 17 | /** 18 | * Created by luotuo on 17-6-30. 19 | */ 20 | @Repository 21 | @Table(name = "user") 22 | @Qualifier("userRepository") 23 | public interface UserRepository extends JpaRepository,JpaSpecificationExecutor { 24 | User findById(Long id); 25 | @Query(value="select bean from User bean where email=?1") 26 | User getUserByLoginName(String name); 27 | @Query(value="select bean from User bean where phone=?1") 28 | User findUserByPhone(String code); 29 | 30 | @Modifying 31 | @Query(value="delete from User bean where code = ?1") 32 | void deleteByCode(String code); 33 | 34 | List findByName(String username); 35 | 36 | 37 | @Query(value = "select bean from User bean where state=?4 and name like %?1% and phone like %?2% and department like %?3%") 38 | Page search(String name, String phone, String department, Integer state, Pageable pageable); 39 | 40 | @Query(value = "select bean from User bean where name like %?1% and phone like %?2% and department like %?3%") 41 | Page searchNoState(String name, String phone, String department, Pageable pageable); 42 | 43 | @Query(value = "select bean from User bean where state=?4 and name like %?1% and phone like %?2% and department like %?3% and id in ?5") 44 | Page searchWithRole(String name, String phone, String department, Integer state, List ids, Pageable pageable); 45 | 46 | @Query(value = "select bean from User bean where name like %?1% and phone like %?2% and department like %?3% and id in ?4") 47 | Page searchNoStateWithRole(String name, String phone, String department, List ids, Pageable pageable); 48 | 49 | @Query(value = "select bean from User bean where id in ?1 and state = 1") 50 | List getUserInIds(List ids); 51 | 52 | @Query(value = "select bean from User bean where id in ?1") 53 | List getAllUserInIds(List ids);//停用的用户也要搜索 54 | 55 | @Query(value = "select bean from User bean where department = ?1 and state=1") 56 | List getUsersByDepartment(String department); 57 | 58 | @Query(value = "select bean from User bean where wechat_open_id = ?1") 59 | User getUserByOpenId(String openId); 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/SignatureUtil.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import java.util.Arrays; 4 | import java.util.Map; 5 | 6 | import javax.crypto.Mac; 7 | import javax.crypto.spec.SecretKeySpec; 8 | 9 | import org.apache.commons.codec.binary.Hex; 10 | import org.apache.commons.codec.digest.DigestUtils; 11 | 12 | public class SignatureUtil { 13 | 14 | /** 15 | * 生成sign HMAC-SHA256 或 MD5 签名 16 | * @param map map 17 | * @param paternerKey paternerKey 18 | * @return sign 19 | */ 20 | public static String generateSign(Map map,String paternerKey){ 21 | return generateSign(map, null, paternerKey); 22 | } 23 | 24 | /** 25 | * 生成sign HMAC-SHA256 或 MD5 签名 26 | * @param map map 27 | * @param sign_type HMAC-SHA256 或 MD5 28 | * @param paternerKey paternerKey 29 | * @return sign 30 | */ 31 | public static String generateSign(Map map,String sign_type,String paternerKey){ 32 | Map tmap = MapUtil.order(map); 33 | if(tmap.containsKey("sign")){ 34 | tmap.remove("sign"); 35 | } 36 | String str = MapUtil.mapJoin(tmap, false, false); 37 | if(sign_type == null){ 38 | sign_type = tmap.get("sign_type"); 39 | } 40 | if("HMAC-SHA256".equalsIgnoreCase(sign_type)){ 41 | try { 42 | Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); 43 | SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256"); 44 | sha256_HMAC.init(secret_key); 45 | return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase(); 46 | } catch (Exception e) { 47 | e.printStackTrace(); 48 | } 49 | return null; 50 | }else{//default MD5 51 | return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase(); 52 | } 53 | } 54 | 55 | /** 56 | * 生成事件消息接收签名 57 | * @param token token 58 | * @param timestamp timestamp 59 | * @param nonce nonce 60 | * @return str 61 | */ 62 | public static String generateEventMessageSignature(String token, String timestamp,String nonce) { 63 | String[] array = new String[]{token,timestamp,nonce}; 64 | Arrays.sort(array); 65 | String s = StringUtils.arrayToDelimitedString(array, ""); 66 | return DigestUtils.shaHex(s); 67 | } 68 | 69 | /** 70 | * mch 支付、代扣异步通知签名验证 71 | * @param map 参与签名的参数 72 | * @param key mch key 73 | * @return boolean 74 | */ 75 | public static boolean validateSign(Map map,String key){ 76 | return validateSign(map, null, key); 77 | } 78 | 79 | /** 80 | * mch 支付、代扣API调用签名验证 81 | * 82 | * @param map 参与签名的参数 83 | * @param sign_type HMAC-SHA256 或 MD5 84 | * @param key mch key 85 | * @return boolean 86 | */ 87 | public static boolean validateSign(Map map,String sign_type,String key){ 88 | if(map.get("sign") == null){ 89 | return false; 90 | } 91 | return map.get("sign").equals(generateSign(map,sign_type,key)); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/API.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | /** 4 | * API 设置 5 | * 6 | * 7 | * 2.8.6 8 | * 9 | * @author LiYi 10 | * 11 | */ 12 | public class API { 13 | 14 | private static final String KEY_JOIN = "#"; 15 | 16 | private static APIHandler apiHandler; 17 | 18 | /** 19 | * 判断参数表现形式 20 | * 21 | * @param keyParam 22 | * keyParam 23 | * @return boolean 24 | */ 25 | private static boolean isKeyParam(String keyParam) { 26 | // ACCESS_TOKEN_LENGTH 138 27 | // TICKET_LENGTH 86 28 | // KEY_MAX_LENGTH 18+1+18 29 | return keyParam != null && keyParam.length() < 50; 30 | } 31 | 32 | /** 33 | * keys 组合 34 | * 35 | * @param component_appid 36 | * component_appid 37 | * @param authorizer_appid 38 | * authorizer_appid 39 | * @return keyParam 40 | */ 41 | public static String keyParam(String component_appid, String authorizer_appid) { 42 | return String.format("%s%s%s", component_appid, KEY_JOIN, authorizer_appid); 43 | } 44 | 45 | /** 46 | * 获取access_token 47 | * 48 | * @param key 49 | * key 50 | * @return access_token 51 | */ 52 | public static String accessToken(String key) { 53 | if (isKeyParam(key)) { 54 | String[] keys = key.split(KEY_JOIN); 55 | if (keys.length == 2) { 56 | return apiHandler.accessToken(keys[0], keys[1]); 57 | } else if (keys.length == 1) { 58 | return apiHandler.accessToken(keys[0]); 59 | } 60 | } 61 | return key; 62 | } 63 | 64 | /** 65 | * 获取component_access_token 66 | * 67 | * @param key 68 | * key 69 | * @return component_access_token 70 | */ 71 | public static String componentAccessToken(String key) { 72 | if (isKeyParam(key)) { 73 | return apiHandler.componentAccessToken(key); 74 | } 75 | return key; 76 | } 77 | 78 | /** 79 | * 获取ticket 80 | * 81 | * @param key 82 | * key 83 | * @param type 84 | * 类型 jsapi,wx_card 85 | * @return ticket 86 | */ 87 | public static String ticket(String key, String type) { 88 | if (isKeyParam(key)) { 89 | String[] keys = key.split(KEY_JOIN); 90 | if (keys.length == 2) { 91 | return apiHandler.ticket(keys[0], keys[1], type); 92 | } else if (keys.length == 1) { 93 | return apiHandler.ticket(keys[0], type); 94 | } 95 | } 96 | return key; 97 | } 98 | 99 | public static APIHandler getApiHandler() { 100 | return apiHandler; 101 | } 102 | 103 | public static void setApiHandler(APIHandler apiHandler) { 104 | API.apiHandler = apiHandler; 105 | } 106 | 107 | public interface APIHandler { 108 | 109 | public String accessToken(String component_appid, String authorizer_appid); 110 | 111 | public String accessToken(String appid); 112 | 113 | public String componentAccessToken(String component_appid); 114 | 115 | public String ticket(String component_appid, String authorizer_appid, String type); 116 | 117 | public String ticket(String appid, String type); 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import com.fasterxml.jackson.core.JsonParseException; 4 | import com.fasterxml.jackson.core.type.TypeReference; 5 | import com.fasterxml.jackson.databind.JsonMappingException; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | 8 | import java.io.IOException; 9 | import java.util.*; 10 | 11 | /** 12 | * Created by liuma on 2017/8/8. 13 | */ 14 | public class JsonUtils { 15 | 16 | /* 将json字符串转换成List集合 */ 17 | public static List convertJson2List(String json) throws Exception { 18 | ObjectMapper objectMapper = new ObjectMapper(); 19 | List> list = null; 20 | try { 21 | list = objectMapper.readValue(json, List.class); 22 | } catch (JsonParseException e) { 23 | throw e; 24 | } catch (JsonMappingException e) { 25 | throw e; 26 | } catch (IOException e) { 27 | throw e; 28 | } 29 | return list; 30 | } 31 | public static Map convertJson2Map(String json) throws Exception { 32 | ObjectMapper objectMapper = new ObjectMapper(); 33 | Map map = null; 34 | try { 35 | map = objectMapper.readValue(json, Map.class); 36 | } catch (JsonParseException e) { 37 | throw e; 38 | } catch (JsonMappingException e) { 39 | throw e; 40 | } catch (IOException e) { 41 | throw e; 42 | } 43 | return map; 44 | } 45 | 46 | /* JavaBean(Entity/Model)转换成JSON */ 47 | public static String writeEntityJSON(Object obj) { 48 | ObjectMapper objectMapper = new ObjectMapper(); 49 | String res = null; 50 | try { 51 | res = objectMapper.writeValueAsString(obj); 52 | } catch (IOException e) { 53 | return "json字符串转换失败"; 54 | } 55 | return res; 56 | } 57 | 58 | public static Map convertEntity2Map(Object obj) throws IOException { 59 | ObjectMapper objectMapper = new ObjectMapper(); 60 | String json = null; 61 | Map map = null; 62 | try { 63 | json = objectMapper.writeValueAsString(obj); 64 | map = objectMapper.readValue(json, Map.class); 65 | } catch (IOException e) { 66 | throw e; 67 | } 68 | return map; 69 | } 70 | 71 | public static T jsonStr2Object(String content, Class cls) throws IOException { 72 | ObjectMapper objectMapper = new ObjectMapper(); 73 | T obj = objectMapper.readValue(content, cls); 74 | return obj; 75 | } 76 | 77 | 78 | /*将json字符串转换成List集合*/ 79 | public static List json2List(String json) throws Exception { 80 | if (json == null || json.equals("")) 81 | return null; 82 | ObjectMapper objectMapper = new ObjectMapper(); 83 | List list = objectMapper.readValue(json, new TypeReference>() { 84 | }); 85 | return list; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/UserPrivilegeService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.PrivilegeConfig; 4 | import com.luotuo.user.entity.UserPrivilege; 5 | import com.luotuo.user.repository.UserPrivilegeRepository; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * Created by luotuo on 17-6-30. 16 | */ 17 | @Service 18 | @Transactional("secondTransactionManager") 19 | public class UserPrivilegeService { 20 | @Autowired 21 | private UserPrivilegeRepository userPrivilegeRepository; 22 | 23 | @Transactional 24 | public void deleteByUserId(long userId) { 25 | userPrivilegeRepository.deleteByUser_id(userId); 26 | } 27 | 28 | public Iterable save(Iterable privileges) { 29 | return userPrivilegeRepository.save(privileges); 30 | } 31 | 32 | public List findByUserId(long userId) { 33 | return userPrivilegeRepository.findByUser_id(userId); 34 | } 35 | 36 | @Transactional 37 | public void deletePrivilegeByUserId(long userId, long privilegeId) { 38 | userPrivilegeRepository.deletePrivilegeByUserId(userId, privilegeId); 39 | } 40 | 41 | @Transactional 42 | public void deletePrivilegesByUserId(long userId, List privilegeIds) { 43 | userPrivilegeRepository.deletePrivilegesByUserId(userId, privilegeIds); 44 | } 45 | 46 | @Transactional 47 | public void deleteByPrivilegeId(long privilegeId) { 48 | userPrivilegeRepository.deleteByPrivilegeId(privilegeId); 49 | } 50 | 51 | @Transactional 52 | public void deleteByPrivilegeIds(List privilegeIds) { 53 | userPrivilegeRepository.deleteByPrivilegeIds(privilegeIds); 54 | } 55 | 56 | @Transactional 57 | public void deletePrivilegeByUserIdsAndPrivilegeId(List userIds, long privilegeId) { 58 | userPrivilegeRepository.deleteByUserIdsAndPrivilegeId(userIds, privilegeId); 59 | } 60 | 61 | @Transactional 62 | public void deletePrivilegeByUserIdsAndPrivilegeIds(List userIds, List privilegeIds) { 63 | userPrivilegeRepository.deleteByUserIdsAndPrivilegeIds(userIds, privilegeIds); 64 | } 65 | 66 | public void addPrivilegesForUsers(List userIds, List privileges) { 67 | List userPrivileges = new ArrayList<>(); 68 | for (Long u : userIds) { 69 | for (PrivilegeConfig p : privileges) { 70 | UserPrivilege userPrivilege = new UserPrivilege(); 71 | userPrivilege.setPrivilege_name(p.getName()); 72 | userPrivilege.setUser_id(u); 73 | userPrivilege.setPrivilege_id(p.getId()); 74 | userPrivileges.add(userPrivilege); 75 | } 76 | } 77 | if (!userPrivileges.isEmpty()) 78 | userPrivilegeRepository.save(userPrivileges); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.controller; 2 | import com.luotuo.config.Global; 3 | import com.luotuo.custom.UserInfo; 4 | import com.luotuo.global.result.Response; 5 | import com.luotuo.service.UserService; 6 | import com.luotuo.user.entity.User; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.data.domain.PageRequest; 11 | import org.springframework.data.domain.Sort; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.stereotype.Controller; 14 | import javax.servlet.http.HttpServletRequest; 15 | import org.springframework.web.bind.ServletRequestUtils; 16 | 17 | /** 18 | * Created by luotuo on 17-6-1. 19 | */ 20 | @Controller 21 | public class BaseController { 22 | //默认请求的分页信息,具体的值在Global中设置。缺省值是20项每页,第0页。 23 | Sort sort = new Sort(Sort.Direction.DESC, "id"); 24 | public PageRequest pageRequest = new PageRequest(Global.DEFAULT_PAGE_NUM, Global.DEFAULT_PAGE_SIZE, sort); 25 | //日志系统 26 | public final Logger mlogger = LoggerFactory.getLogger(this.getClass()); 27 | 28 | 29 | @Autowired 30 | UserService userService; 31 | 32 | 33 | public Long getUserId() { 34 | try { 35 | Object userInfo = SecurityContextHolder.getContext() 36 | .getAuthentication() 37 | .getPrincipal(); 38 | if (userInfo instanceof Long) 39 | return (Long)userInfo; 40 | return ((UserInfo)userInfo).getId(); 41 | } catch (Exception e) { 42 | return 0L; 43 | } 44 | } 45 | 46 | //返回请求中的参数值 47 | public String getParam(HttpServletRequest request, String name) { 48 | if (name == null || name == "") return null; 49 | String para = ServletRequestUtils.getStringParameter(request, name, null); 50 | return para; 51 | } 52 | 53 | //获取正确 54 | public Response successResponse(String message, Object result) { 55 | if (message == null) message = "处理成功"; 56 | Response response = new Response(); 57 | response.setSuccess(Response.SUCCEED); 58 | response.setMessage(message); 59 | if (result == null) 60 | result = 1; 61 | response.setResult(result); 62 | return response; 63 | } 64 | 65 | //出现错误 66 | public Response errorResponse(String message, Object result) { 67 | if (message == null) message = "处理失败"; 68 | Response response = new Response(); 69 | response.setSuccess(Response.ERROR); 70 | response.setMessage(message); 71 | if (result == null) 72 | result = 0; 73 | response.setResult(result); 74 | return response; 75 | } 76 | 77 | /** 78 | * 获取当前登录的用户信息 79 | */ 80 | public User getUser() { 81 | long userId = getUserId(); 82 | if (userId == 0) 83 | return null; 84 | User user = userService.getUserById(userId); 85 | return user; 86 | } 87 | } 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/Format.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import java.text.ParseException; 4 | import java.text.ParsePosition; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | 8 | /** 9 | * Created by liuma on 2017/7/6. 10 | */ 11 | public class Format { 12 | 13 | /** 14 | * @Function 对其函数,不够位数的在前面补0,保留num的长度位数字 15 | * @param code 16 | * @param num 对其长度 17 | * @return 18 | */ 19 | public static String formatCode(long code, int num) { 20 | String result = ""; 21 | // 保留num的位数 22 | // 0 代表前面补充0 23 | // num 代表长度为4 24 | // d 代表参数为正数型 25 | result = String.format("%0" + num + "d", code); 26 | return result; 27 | } 28 | 29 | public static String formatCode(int code, int num) { 30 | String result = ""; 31 | // 保留num的位数 32 | // 0 代表前面补充0 33 | // num 代表长度为4 34 | // d 代表参数为正数型 35 | result = String.format("%0" + num + "d", code); 36 | return result; 37 | } 38 | 39 | public static String formatDate(Date date){ 40 | SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟 41 | return sdf.format(date); 42 | } 43 | 44 | public static Date formatDateTime(String date) { 45 | SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟 46 | Date o=new Date(); 47 | try{ 48 | o=sdf.parse(date); 49 | }catch (ParseException e){ 50 | System.out.print("Date error"+e); 51 | } 52 | return o; 53 | } 54 | 55 | /** 56 | * 获取现在时间 57 | * 58 | * @return 返回时间类型 yyyy-MM-dd HH:mm:ss 59 | */ 60 | public static Date getNowDate() { 61 | Date currentTime = new Date(); 62 | SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 63 | String dateString = formatter.format(currentTime); 64 | ParsePosition pos = new ParsePosition(0); 65 | Date currentTime_2 = formatter.parse(dateString, pos); 66 | return currentTime_2; 67 | } 68 | 69 | public static String getNowDateString() { 70 | Date currentTime = new Date(); 71 | SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 72 | String dateString = formatter.format(currentTime); 73 | return dateString; 74 | } 75 | 76 | public static Date formatDate(String date) { 77 | if(StringUtils.isBlank(date))return null; 78 | SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟 79 | Date o=new Date(); 80 | try{ 81 | o=sdf.parse(date); 82 | }catch (ParseException e){ 83 | System.out.print("Date not yyyy-MM-dd format"+e); 84 | sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟 85 | try{ 86 | o=sdf.parse(date); 87 | }catch (Exception ee){ 88 | System.out.print("Date not yyyy-MM-dd HH:mm:ss format"+e); 89 | return null; 90 | } 91 | } 92 | return o; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/user/entity/PrivilegeConfig1.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.user.entity; 2 | 3 | /** 4 | * Created by luotuo on 17-7-24. 5 | */ 6 | public class PrivilegeConfig1 { 7 | private long id; 8 | private long pid; 9 | private int level; 10 | private String level_str; 11 | private String name; 12 | private String type; 13 | private String value; 14 | private String url; 15 | private int state; 16 | private String state_str; 17 | private String platform; 18 | 19 | private Boolean checked; 20 | public Boolean getChecked() { 21 | return checked; 22 | } 23 | 24 | public void setChecked(Boolean checked) { 25 | this.checked = checked; 26 | } 27 | 28 | public String getPlatform() { 29 | return platform; 30 | } 31 | 32 | public void setPlatform(String platform) { 33 | this.platform = platform; 34 | } 35 | 36 | public long getId() { 37 | return id; 38 | } 39 | 40 | public void setId(long id) { 41 | this.id = id; 42 | } 43 | 44 | public long getPid() { 45 | return pid; 46 | } 47 | 48 | public void setPid(long pid) { 49 | this.pid = pid; 50 | } 51 | 52 | public int getLevel() { 53 | return level; 54 | } 55 | 56 | public void setLevel(int level) { 57 | this.level = level; 58 | } 59 | 60 | public String getLevel_str() { 61 | return level_str; 62 | } 63 | 64 | public void setLevel_str(String level_str) { 65 | this.level_str = level_str; 66 | } 67 | 68 | public String getName() { 69 | return name; 70 | } 71 | 72 | public void setName(String name) { 73 | this.name = name; 74 | } 75 | 76 | public String getType() { 77 | return type; 78 | } 79 | 80 | public void setType(String type) { 81 | this.type = type; 82 | } 83 | 84 | public String getValue() { 85 | return value; 86 | } 87 | 88 | public void setValue(String value) { 89 | this.value = value; 90 | } 91 | 92 | public String getUrl() { 93 | return url; 94 | } 95 | 96 | public void setUrl(String url) { 97 | this.url = url; 98 | } 99 | 100 | public int getState() { 101 | return state; 102 | } 103 | 104 | public void setState(int state) { 105 | this.state = state; 106 | } 107 | 108 | public String getState_str() { 109 | return state_str; 110 | } 111 | 112 | public void setState_str(String state_str) { 113 | this.state_str = state_str; 114 | } 115 | 116 | public void set(PrivilegeConfig p, Boolean checked) { 117 | this.id = p.getId(); 118 | this.pid = p.getPid(); 119 | this.level = p.getLevel(); 120 | this.level_str = p.getLevel_str(); 121 | this.name = p.getName(); 122 | this.type = p.getType(); 123 | this.value = p.getValue(); 124 | this.url = p.getUrl(); 125 | this.state = p.getState(); 126 | this.state_str = p.getState_str(); 127 | this.platform = p.getPlatform(); 128 | this.checked = checked; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/UserDsConfig.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import org.springframework.beans.factory.annotation.Qualifier; 4 | import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 10 | import org.springframework.jdbc.core.JdbcTemplate; 11 | import org.springframework.orm.jpa.JpaTransactionManager; 12 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 13 | import org.springframework.transaction.PlatformTransactionManager; 14 | import org.springframework.transaction.annotation.EnableTransactionManagement; 15 | import org.springframework.transaction.support.TransactionTemplate; 16 | 17 | import javax.sql.DataSource; 18 | 19 | /** 20 | * Created by luotuo on 17-6-30. 21 | */ 22 | @Configuration 23 | @EnableTransactionManagement 24 | @EnableJpaRepositories(basePackages = "com.luotuo.user.repository", entityManagerFactoryRef = "secondEntityManagerFactory",transactionManagerRef = "secondTransactionManager") 25 | public class UserDsConfig { 26 | 27 | @Bean 28 | @ConfigurationProperties("second.datasource") 29 | public DataSourceProperties secondDataSourceProperties() { 30 | return new DataSourceProperties(); 31 | } 32 | 33 | @Bean 34 | @ConfigurationProperties("second.datasource") 35 | public DataSource secondDataSource() { 36 | return secondDataSourceProperties().initializeDataSourceBuilder().build(); 37 | } 38 | 39 | /** 40 | * 实体管理对象 41 | * @param builder 由spring注入这个对象,首先根据type注入(多个就取声明@Primary的对象),否则根据name注入 42 | * @return 43 | */ 44 | @Bean(name = "secondEntityManagerFactory") 45 | public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory( 46 | EntityManagerFactoryBuilder builder) { 47 | return builder 48 | .dataSource(secondDataSource()) 49 | .packages("com.luotuo.user.entity") 50 | .persistenceUnit("secondDs") 51 | .build(); 52 | } 53 | 54 | /** 55 | * 事物管理对象 56 | * @param secondEntityManagerFactory 实体管理工厂对象(按照名称注入) 57 | * @return 平台事物管理器 58 | */ 59 | @Bean(name = "secondTransactionManager") 60 | public PlatformTransactionManager transactionManager(@Qualifier("secondEntityManagerFactory")LocalContainerEntityManagerFactoryBean secondEntityManagerFactory){ 61 | JpaTransactionManager transactionManager = new JpaTransactionManager(); 62 | transactionManager.setEntityManagerFactory(secondEntityManagerFactory.getObject()); 63 | return transactionManager; 64 | } 65 | 66 | @Bean(name="jdbcTemplate2") 67 | public JdbcTemplate jdbcTemplate(){ 68 | return new JdbcTemplate(secondDataSource()); 69 | } 70 | 71 | @Bean(name = "transactionTemplate2") 72 | public TransactionTemplate transactionTemplate(@Qualifier("secondTransactionManager")PlatformTransactionManager transactionManager){ 73 | return new TransactionTemplate(transactionManager); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/AuditDsConfig.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Primary; 9 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 10 | import org.springframework.jdbc.core.JdbcTemplate; 11 | import org.springframework.orm.jpa.JpaTransactionManager; 12 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 13 | import org.springframework.transaction.PlatformTransactionManager; 14 | import org.springframework.transaction.annotation.EnableTransactionManagement; 15 | import org.springframework.transaction.support.TransactionTemplate; 16 | 17 | import javax.persistence.EntityManagerFactory; 18 | import javax.sql.DataSource; 19 | 20 | /** 21 | * Created by luotuo on 17-6-30. 22 | */ 23 | @Configuration 24 | @EnableTransactionManagement 25 | @EnableJpaRepositories(basePackages = "com.luotuo.repository",entityManagerFactoryRef = "firstEntityManagerFactory",transactionManagerRef="firstTransactionManager") 26 | public class AuditDsConfig { 27 | 28 | /** 29 | * 数据源配置对象 30 | * Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入 31 | * @return 32 | */ 33 | @Bean 34 | @Primary 35 | @ConfigurationProperties("first.datasource") 36 | public DataSourceProperties firstDataSourceProperties() { 37 | return new DataSourceProperties(); 38 | } 39 | 40 | /** 41 | * 数据源对象 42 | * @return 43 | */ 44 | @Bean 45 | @Primary 46 | @ConfigurationProperties("first.datasource") 47 | public DataSource firstDataSource() { 48 | return firstDataSourceProperties().initializeDataSourceBuilder().build(); 49 | } 50 | 51 | /** 52 | * 实体管理对象 53 | * @param builder 由spring注入这个对象,首先根据type注入(多个就取声明@Primary的对象),否则根据name注入 54 | * @return 55 | */ 56 | @Bean 57 | @Primary 58 | public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory( 59 | EntityManagerFactoryBuilder builder) { 60 | return builder 61 | .dataSource(firstDataSource()) 62 | .packages("com.luotuo.entity") 63 | .persistenceUnit("firstDs") 64 | .build(); 65 | } 66 | 67 | /** 68 | * 事务管理对象 69 | * @return 70 | */ 71 | @Bean(name = "firstTransactionManager") 72 | @Primary 73 | public PlatformTransactionManager transactionManager(EntityManagerFactory emf){ 74 | JpaTransactionManager transactionManager = new JpaTransactionManager(); 75 | transactionManager.setEntityManagerFactory(emf); 76 | return transactionManager; 77 | } 78 | 79 | @Bean 80 | @Primary 81 | public JdbcTemplate jdbcTemplate(){ 82 | return new JdbcTemplate(firstDataSource()); 83 | } 84 | 85 | @Bean 86 | @Primary 87 | public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){ 88 | return new TransactionTemplate(platformTransactionManager); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/MyInvocationSecurityMetadataSourceService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | import com.luotuo.user.entity.PrivilegeConfig; 4 | import com.luotuo.service.PrivilegeConfigService; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.access.ConfigAttribute; 8 | import org.springframework.security.access.SecurityConfig; 9 | import org.springframework.security.web.FilterInvocation; 10 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 11 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 12 | import org.springframework.stereotype.Service; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import java.util.*; 16 | 17 | /** 18 | * Created by luotuo on 17-7-3. 19 | */ 20 | @Service 21 | public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource { 22 | 23 | @Autowired 24 | private PrivilegeConfigService privilegeConfigService; 25 | 26 | private HashMap> map = null; 27 | 28 | /** 29 | * 加载权限表中所有权限 30 | */ 31 | public void loadResourceDefine() { 32 | map = new HashMap<>(); 33 | Collection array; 34 | ConfigAttribute cfg; 35 | List permissions = privilegeConfigService.findAll(); 36 | for (PrivilegeConfig permission : permissions) { 37 | array = new ArrayList<>(); 38 | cfg = new SecurityConfig(permission.getName()); 39 | //此处只添加了用户的名字,其实还可以添加更多权限的信息,例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。 40 | array.add(cfg); 41 | //用权限的getUrl() 作为map的key,用ConfigAttribute的集合作为 value, 42 | map.put(permission.getUrl(), array); 43 | } 44 | } 45 | 46 | //此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。 47 | @Override 48 | public Collection getAttributes(Object object) throws IllegalArgumentException { 49 | if (map == null) loadResourceDefine(); 50 | //object 中包含用户请求的request 信息 51 | HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); 52 | AntPathRequestMatcher matcher; 53 | String resUrl; 54 | for (Iterator iter = map.keySet().iterator(); iter.hasNext(); ) { 55 | resUrl = iter.next(); 56 | if (resUrl == null || resUrl.equals("")) 57 | continue; 58 | matcher = new AntPathRequestMatcher(resUrl); 59 | if (matcher.matches(request)) { 60 | return map.get(resUrl); 61 | } 62 | } 63 | return null; 64 | } 65 | 66 | //此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。 67 | //因为我不想每一次来了请求,都先要匹配一下权限表中的信息是不是包含此url, 68 | // 我准备直接拦截,不管请求的url 是什么都直接拦截,然后在MyAccessDecisionManager的decide 方法中做拦截还是放行的决策。 69 | //所以此方法的返回值不能返回 null 此处我就随便返回一下。 70 | // @Override 71 | // public Collection getAttributes(Object object) throws IllegalArgumentException { 72 | // Collection co=new ArrayList<>(); 73 | // co.add(new SecurityConfig("null")); 74 | // return co; 75 | // } 76 | 77 | @Override 78 | public Collection getAllConfigAttributes() { 79 | return null; 80 | } 81 | 82 | @Override 83 | public boolean supports(Class clazz) { 84 | return true; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/BytesOrJsonResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.http.Header; 6 | import org.apache.http.HttpEntity; 7 | import org.apache.http.HttpResponse; 8 | import org.apache.http.client.ClientProtocolException; 9 | import org.apache.http.client.ResponseHandler; 10 | import org.apache.http.entity.ContentType; 11 | import org.apache.http.util.EntityUtils; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | import com.luotuo.wechat.bean.MediaGetResult; 16 | import com.luotuo.wechat.utils.JsonUtil; 17 | 18 | /** 19 | * 二进制 或 JSON 数据Response处理 20 | * 21 | * @author LiYi 22 | * 23 | */ 24 | public class BytesOrJsonResponseHandler{ 25 | 26 | private static Logger logger = LoggerFactory.getLogger(BytesOrJsonResponseHandler.class); 27 | 28 | public static ResponseHandler createResponseHandler(final Class clazz){ 29 | return new BytesOrJsonResponseHandlerImpl(null,clazz); 30 | } 31 | 32 | public static class BytesOrJsonResponseHandlerImpl extends LocalResponseHandler implements ResponseHandler { 33 | 34 | private Class clazz; 35 | 36 | public BytesOrJsonResponseHandlerImpl(String uriId, Class clazz) { 37 | this.uriId = uriId; 38 | this.clazz = clazz; 39 | } 40 | 41 | @Override 42 | public T handleResponse(HttpResponse response) 43 | throws ClientProtocolException, IOException { 44 | int status = response.getStatusLine().getStatusCode(); 45 | if (status >= 200 && status < 300) { 46 | ContentType contentType = ContentType.get(response.getEntity()); 47 | //json data 48 | String contentTypeStr = contentType==null?null:contentType.getMimeType(); 49 | if(contentType != null && 50 | (ContentType.TEXT_PLAIN.getMimeType().equalsIgnoreCase(contentTypeStr) 51 | ||ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentTypeStr))){ 52 | HttpEntity entity = response.getEntity(); 53 | String str = EntityUtils.toString(entity,"utf-8"); 54 | logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}",super.uriId,System.currentTimeMillis()-super.startTime,str); 55 | return JsonUtil.parseObject(str, clazz); 56 | }else{ 57 | //bytes data 58 | try { 59 | T t = clazz.newInstance(); 60 | MediaGetResult mediaGetResult = (MediaGetResult)t; 61 | Header contentDisposition = response.getFirstHeader("Content-disposition"); 62 | if(contentDisposition != null){ 63 | String filename = contentDisposition.getValue().replaceAll(".*filename=\"(.*)\".*", "$1"); 64 | mediaGetResult.setFilename(filename); 65 | } 66 | mediaGetResult.setContentType(contentTypeStr); 67 | mediaGetResult.setBytes(EntityUtils.toByteArray(response.getEntity())); 68 | logger.info("URI[{}]ContentType:{} elapsed time:{} ms RESPONSE DATA:{}",super.uriId,contentTypeStr,System.currentTimeMillis()-super.startTime,""); 69 | return t; 70 | } catch (InstantiationException e) { 71 | // TODO Auto-generated catch block 72 | e.printStackTrace(); 73 | } catch (IllegalAccessException e) { 74 | // TODO Auto-generated catch block 75 | e.printStackTrace(); 76 | } 77 | } 78 | } else { 79 | throw new ClientProtocolException("Unexpected response status: " + status); 80 | } 81 | return null; 82 | } 83 | 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | import org.springframework.security.core.userdetails.UserDetails; 4 | 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | /** 9 | * Created by luotuo on 17-6-26. 10 | */ 11 | public class UserInfo implements UserDetails { 12 | private static final long serialVersionUID = -1041327031937199938L; 13 | 14 | /** 15 | * 用户ID 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 用户名称 21 | */ 22 | private String name; 23 | 24 | /** 25 | * 登录名称 26 | */ 27 | private String username; 28 | 29 | /** 30 | * 登录密码 31 | */ 32 | private String password; 33 | 34 | private boolean isAccountNonExpired = true; 35 | 36 | private boolean isAccountNonLocked = true; 37 | 38 | private boolean isCredentialsNonExpired = true; 39 | 40 | private boolean isEnabled = true; 41 | 42 | private Set authorities = new HashSet(); 43 | 44 | public static long getSerialVersionUID() { 45 | return serialVersionUID; 46 | } 47 | 48 | public Long getId() { 49 | return id; 50 | } 51 | 52 | public void setId(Long id) { 53 | this.id = id; 54 | } 55 | 56 | public String getName() { 57 | return name; 58 | } 59 | 60 | public void setName(String name) { 61 | this.name = name; 62 | } 63 | 64 | @Override 65 | public String getUsername() { 66 | return username; 67 | } 68 | 69 | public void setUsername(String username) { 70 | this.username = username; 71 | } 72 | 73 | @Override 74 | public String getPassword() { 75 | return password; 76 | } 77 | 78 | public void setPassword(String password) { 79 | this.password = password; 80 | } 81 | 82 | @Override 83 | public boolean isAccountNonExpired() { 84 | return isAccountNonExpired; 85 | } 86 | 87 | public void setAccountNonExpired(boolean accountNonExpired) { 88 | isAccountNonExpired = accountNonExpired; 89 | } 90 | 91 | @Override 92 | public boolean isAccountNonLocked() { 93 | return isAccountNonLocked; 94 | } 95 | 96 | public void setAccountNonLocked(boolean accountNonLocked) { 97 | isAccountNonLocked = accountNonLocked; 98 | } 99 | 100 | @Override 101 | public boolean isCredentialsNonExpired() { 102 | return isCredentialsNonExpired; 103 | } 104 | 105 | public void setCredentialsNonExpired(boolean credentialsNonExpired) { 106 | isCredentialsNonExpired = credentialsNonExpired; 107 | } 108 | 109 | @Override 110 | public boolean isEnabled() { 111 | return isEnabled; 112 | } 113 | 114 | public void setEnabled(boolean enabled) { 115 | isEnabled = enabled; 116 | } 117 | 118 | @Override 119 | public Set getAuthorities() { 120 | return authorities; 121 | } 122 | 123 | public void setAuthorities(Set authorities) { 124 | this.authorities = authorities; 125 | } 126 | 127 | /** 128 | * 重写比较方法,SpringSecurity根据用户名来比较是否同一个用户 129 | */ 130 | @Override 131 | public boolean equals(Object o){ 132 | if(o.toString().equals(this.username)) 133 | return true; 134 | return false; 135 | } 136 | 137 | @Override 138 | public int hashCode(){ 139 | return username.hashCode(); 140 | } 141 | 142 | 143 | @Override 144 | public String toString() { 145 | return this.username; 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/main/resources/application-weixin.properties: -------------------------------------------------------------------------------- 1 | #修改tomcat的默认的端口号,将8080改为8888 2 | server.port=8088 3 | server.context-path=/luotuo 4 | #jsp支持 5 | spring.mvc.view.prefix=/WEB-INF/jsp/ 6 | spring.mvc.view.suffix=.jsp 7 | application.message=Hello 8 | 9 | # 数据库访问配置 10 | #=====================multiple database config============================ 11 | #ds1 12 | # 127.0.0.1 13 | first.datasource.url=jdbc:mysql://127.0.0.1:3306/luotuo?characterEncoding=utf8&useSSL=true 14 | first.datasource.username=root 15 | first.datasource.password=root 16 | first.datasource.driver-class-name=com.mysql.jdbc.Driver 17 | first.datasource.type=org.apache.tomcat.jdbc.pool.DataSource 18 | first.datasource.max-wait=10000 19 | first.datasource.max-active=200 20 | first.datasource.test-on-borrow=true 21 | first.datasource.initial-size=5 22 | 23 | #ds2 24 | second.datasource.url=jdbc:mysql://127.0.0.1:3306/luotuo_system_config?characterEncoding=utf8&useSSL=true 25 | second.datasource.username=root 26 | second.datasource.password=root 27 | second.datasource.driver-class-name=com.mysql.jdbc.Driver 28 | second.datasource.type=org.apache.tomcat.jdbc.pool.DataSource 29 | second.datasource.max-wait=10000 30 | second.datasource.max-active=200 31 | second.datasource.test-on-borrow=true 32 | second.datasource.initial-size=5 33 | 34 | 35 | # 下面为连接池的补充设置,应用到上面所有数据源中 36 | # 初始化大小,最小,最大 37 | spring.datasource.initialSize=5 38 | spring.datasource.minIdle=5 39 | spring.datasource.maxActive=20 40 | # 配置获取连接等待超时的时间 41 | spring.datasource.maxWait=60000 42 | # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 43 | spring.datasource.timeBetweenEvictionRunsMillis=60000 44 | # 配置一个连接在池中最小生存的时间,单位是毫秒 45 | spring.datasource.minEvictableIdleTimeMillis=300000 46 | spring.datasource.validationQuery=SELECT 1 FROM DUAL 47 | spring.datasource.testWhileIdle=true 48 | spring.datasource.testOnBorrow=false 49 | spring.datasource.testOnReturn=false 50 | # 打开PSCache,并且指定每个连接上PSCache的大小 51 | spring.datasource.poolPreparedStatements=true 52 | spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 53 | # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 54 | spring.datasource.filters=stat,wall,log4j 55 | # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 56 | spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 57 | # 合并多个DruidDataSource的监控数据 58 | spring.datasource.useGlobalDataSourceStat=true 59 | 60 | 61 | #JPA Configuration: 62 | spring.jpa.database=MYSQL 63 | # Show or not log for each sql query 64 | spring.jpa.show-sql=true 65 | spring.jpa.generate-ddl=true 66 | # Hibernate ddl auto (create, create-drop, update) 67 | spring.jpa.hibernate.ddl-auto=none 68 | #spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect 69 | spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy 70 | #spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect 71 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 72 | 73 | #应用访问地址 74 | app.server.host.url=http://127.0.0.1:8088/luotuo 75 | app.server.base.url=http://127.0.0.1:8088 76 | #应用登录地址 77 | app.login.url=/login 78 | #应用登出地址 79 | app.logout.url=/logout 80 | 81 | ##security设置为false后可以直接访问actuator的bean 82 | management.security.enabled=true 83 | ##日志系统 默认使用logback 84 | logging.config=classpath:logback.xml 85 | logging.path=/luotuo 86 | 87 | 88 | wechat.client.clientId=yourwechatappid 89 | wechat.client.clientSecret=yourwechatsecret 90 | wechat.client.accessTokenUri=https://api.weixin.qq.com/sns/oauth2/access_token 91 | wechat.client.userAuthorizationUri=https://open.weixin.qq.com/connect/oauth2/authorize 92 | #wechat.client.clientAuthenticationScheme=query 93 | wechat.client.authenticationScheme=query 94 | wechat.resource.userInfoUri=https://api.weixin.qq.com/sns/userinfo 95 | 96 | callback.path.project=http://abc.luotuo.cn/luotuo -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | import com.luotuo.security.SecurityConfig; 4 | import com.luotuo.service.PrivilegeConfigService; 5 | import com.luotuo.service.URIResourceService; 6 | import com.luotuo.service.UserPrivilegeService; 7 | import com.luotuo.service.UserService; 8 | import com.luotuo.user.entity.PrivilegeConfig; 9 | import com.luotuo.user.entity.User; 10 | 11 | import com.luotuo.user.entity.UserPrivilege; 12 | import com.luotuo.utils.StringUtils; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.security.core.userdetails.UserDetailsService; 17 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.web.context.request.RequestContextHolder; 20 | import org.springframework.web.context.request.ServletRequestAttributes; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.util.ArrayList; 24 | import java.util.HashSet; 25 | import java.util.List; 26 | import java.util.Set; 27 | 28 | /** 29 | * Created by luotuo on 17-6-26. 30 | */ 31 | @Service 32 | public class CustomUserDetailsService implements UserDetailsService { 33 | 34 | @Autowired 35 | private UserService userService; 36 | 37 | @Autowired 38 | private URIResourceService uriResourceService; 39 | @Autowired 40 | private UserPrivilegeService userPrivilegeService; 41 | @Autowired 42 | private PrivilegeConfigService privilegeConfigService; 43 | 44 | @Override 45 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 46 | System.out.println("当前的用户名是:"+username); 47 | User user = userService.getUserByLoginName(username); 48 | if (user == null) 49 | throw new UsernameNotFoundException("Admin: " + username + "do not exsit!"); 50 | UserInfo userInfo = new UserInfo(); 51 | userInfo.setUsername(username); 52 | userInfo.setName(user.getName()); 53 | userInfo.setId(user.getId()); 54 | userInfo.setPassword(user.getPassword()); 55 | Set authorities = new HashSet(); 56 | System.out.println("userInfo.getId == " + userInfo.getId()); 57 | if (userInfo.getId() == 1) { 58 | // Admin, add all privileges 59 | List uris = uriResourceService.getAll(); 60 | for (String uri : uris) { 61 | AuthorityInfo authorityInfo = new AuthorityInfo(uri); 62 | authorities.add(authorityInfo); 63 | } 64 | } else { 65 | // Other users. Find user's privileges and add them 66 | List userPrivileges = userPrivilegeService.findByUserId(user.getId()); 67 | List privilegeIds = new ArrayList<>(); 68 | for (UserPrivilege p : userPrivileges) { 69 | privilegeIds.add(p.getPrivilege_id()); 70 | } 71 | if (!privilegeIds.isEmpty()) { 72 | List privilegeConfigs = privilegeConfigService.getByIds(privilegeIds); 73 | for (PrivilegeConfig p : privilegeConfigs) { 74 | if (StringUtils.isNotBlank(p.getUrl())) { 75 | AuthorityInfo authorityInfo = new AuthorityInfo(p.getUrl()); 76 | authorities.add(authorityInfo); 77 | } 78 | } 79 | } 80 | } 81 | userInfo.setAuthorities(authorities); 82 | return userInfo; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/MapUtil.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.lang.reflect.Field; 5 | import java.net.URLEncoder; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.Collections; 9 | import java.util.Comparator; 10 | import java.util.HashMap; 11 | import java.util.LinkedHashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | public class MapUtil { 16 | 17 | /** 18 | * Map key 排序 19 | * @param map map 20 | * @return map 21 | */ 22 | public static Map order(Map map){ 23 | HashMap tempMap = new LinkedHashMap(); 24 | List> infoIds = new ArrayList>( map.entrySet()); 25 | 26 | Collections.sort(infoIds, new Comparator>() { 27 | public int compare(Map.Entry o1,Map.Entry o2) { 28 | return (o1.getKey()).toString().compareTo(o2.getKey()); 29 | } 30 | }); 31 | 32 | for (int i = 0; i < infoIds.size(); i++) { 33 | Map.Entry item = infoIds.get(i); 34 | tempMap.put(item.getKey(), item.getValue()); 35 | } 36 | return tempMap; 37 | } 38 | 39 | 40 | /** 41 | * 转换对象为map 42 | * @param object object 43 | * @param ignore ignore 44 | * @return map 45 | */ 46 | public static Map objectToMap(Object object,String... ignore){ 47 | Map tempMap = new LinkedHashMap(); 48 | for(Field f : getAllFields(object.getClass())){ 49 | if(!f.isAccessible()){ 50 | f.setAccessible(true); 51 | } 52 | boolean ig = false; 53 | if(ignore!=null&&ignore.length>0){ 54 | for(String i : ignore){ 55 | if(i.equals(f.getName())){ 56 | ig = true; 57 | break; 58 | } 59 | } 60 | } 61 | if(ig){ 62 | continue; 63 | }else{ 64 | Object o = null; 65 | try { 66 | o = f.get(object); 67 | } catch (IllegalArgumentException e) { 68 | e.printStackTrace(); 69 | } catch (IllegalAccessException e) { 70 | e.printStackTrace(); 71 | } 72 | tempMap.put(f.getName(), o==null?"":o.toString()); 73 | } 74 | } 75 | return tempMap; 76 | } 77 | 78 | /** 79 | * 获取所有Fields,包含父类field 80 | * @param clazz clazz 81 | * @return list 82 | */ 83 | private static List getAllFields(Class clazz){ 84 | if(!clazz.equals(Object.class)){ 85 | List fields = new ArrayList(Arrays.asList(clazz.getDeclaredFields())); 86 | List fields2 = getAllFields(clazz.getSuperclass()); 87 | if(fields2!=null){ 88 | fields.addAll(fields2); 89 | } 90 | return fields; 91 | }else{ 92 | return null; 93 | } 94 | } 95 | 96 | /** 97 | * url 参数串连 98 | * @param map map 99 | * @param keyLower keyLower 100 | * @param valueUrlencode valueUrlencode 101 | * @return string 102 | */ 103 | public static String mapJoin(Map map,boolean keyLower,boolean valueUrlencode){ 104 | StringBuilder stringBuilder = new StringBuilder(); 105 | for(String key :map.keySet()){ 106 | if(map.get(key)!=null&&!"".equals(map.get(key))){ 107 | try { 108 | String temp = (key.endsWith("_")&&key.length()>1)?key.substring(0,key.length()-1):key; 109 | stringBuilder.append(keyLower?temp.toLowerCase():temp) 110 | .append("=") 111 | .append(valueUrlencode?URLEncoder.encode(map.get(key),"utf-8").replace("+", "%20"):map.get(key)) 112 | .append("&"); 113 | } catch (UnsupportedEncodingException e) { 114 | e.printStackTrace(); 115 | } 116 | } 117 | } 118 | if(stringBuilder.length()>0){ 119 | stringBuilder.deleteCharAt(stringBuilder.length()-1); 120 | } 121 | return stringBuilder.toString(); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/SpecificationFactory.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import org.springframework.data.jpa.domain.Specification; 4 | 5 | import javax.persistence.criteria.Expression; 6 | import java.util.Collection; 7 | import java.util.Date; 8 | 9 | /** 10 | * Created by liuma on 2017/7/24. 11 | * 支持jdk1.8即以上lambda 12 | */ 13 | public final class SpecificationFactory { 14 | 15 | /** 16 | * 模糊查询,匹配对应字段 17 | * @param attribute 18 | * @param value 19 | * @return 20 | */ 21 | public static Specification containsLike(String attribute, String value) { 22 | return (root, query, cb) -> cb.like(root.get(attribute), "%" + value + "%"); 23 | } 24 | /** 25 | * 某字段的值等于value的查询条件 26 | * @param attribute 27 | * @param value 28 | * @return 29 | */ 30 | public static Specification equal(String attribute, Object value) { 31 | return (root, query, cb) -> cb.equal(root.get(attribute),value); 32 | } 33 | 34 | /** 35 | *获取对应属性比输入值大的集合涉及int值、long值、double值 36 | * @param attribute 37 | * @param value 38 | * @return 39 | * */ 40 | public static Specification greater(String attribute, Long value) { 41 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 42 | } 43 | public static Specification greater(String attribute, long value) { 44 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 45 | } 46 | public static Specification greater(String attribute, Integer value) { 47 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 48 | } 49 | public static Specification greater(String attribute, int value) { 50 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 51 | } 52 | public static Specification greater(String attribute, Double value) { 53 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 54 | } 55 | public static Specification greater(String attribute, double value) { 56 | return (root, query, cb) -> cb.gt(root.get(attribute),value); 57 | } 58 | /** 59 | *获取对应属性比输入值大的集合涉及int值、long值、double值、Date值 60 | * @param attribute 61 | * @param value 62 | * @return 63 | * */ 64 | 65 | /** 66 | * 获取对应属性的值所在区间,涉及int值、long值、double值、Date值 67 | * @param attribute 68 | * @param min 69 | * @param max 70 | * @return 71 | */ 72 | public static Specification isBetween(String attribute, Long min, Long max) { 73 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 74 | } 75 | public static Specification isBetween(String attribute, long min, long max) { 76 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 77 | } 78 | public static Specification isBetween(String attribute, int min, int max) { 79 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 80 | } 81 | public static Specification isBetween(String attribute, Integer min, Integer max) { 82 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 83 | } 84 | public static Specification isBetween(String attribute, double min, double max) { 85 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 86 | } 87 | public static Specification isBetween(String attribute, Double min, Double max) { 88 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 89 | } 90 | public static Specification isBetween(String attribute, Date min, Date max) { 91 | return (root, query, cb) -> cb.between(root.get(attribute), min, max); 92 | } 93 | /** 94 | * 通过属性名和集合实现in查询 95 | * @param attribute 96 | * @param c 97 | * @return 98 | */ 99 | public static Specification in(String attribute, Collection c) { 100 | return (root, query, cb) -> root.get(attribute).in(c); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Random; 6 | import java.util.regex.Pattern; 7 | 8 | /** 9 | * Created by liuma on 2017/7/20. 10 | */ 11 | public class StringUtils { 12 | 13 | public static Long[] parseLongArray(String input) { 14 | if (input == null || input.length() == 0) return null; 15 | input = input.trim(); 16 | input = input.replace("\"", ""); 17 | input = input.replace("'", ""); 18 | input = input.replace(",", ","); 19 | String[] idstr = input.split(","); 20 | Long[] idlongs = new Long[idstr.length]; 21 | for (int i = 0; i < idlongs.length; i++) { 22 | idlongs[i] = Long.parseLong(idstr[i]); 23 | } 24 | return idlongs; 25 | } 26 | 27 | public static List StringToLongList(String inputs) { 28 | if(isBlank(inputs))return new ArrayList<>(); 29 | inputs = inputs.trim(); 30 | inputs = inputs.replace("\"", ""); 31 | inputs = inputs.replace("'", ""); 32 | String[] idstr = inputs.split(","); 33 | List LongList = new ArrayList<>(); 34 | for (int i = 0; i < idstr.length; i++) { 35 | LongList.add(Long.parseLong(idstr[i])); 36 | } 37 | return LongList; 38 | } 39 | 40 | //字符串 41 | public static boolean isNotBlank(String input) { 42 | if (input == null) return false; 43 | return (!input.isEmpty()); 44 | } 45 | 46 | public static boolean isBlank(String input) { 47 | if (input == null) return true; 48 | return input.isEmpty(); 49 | } 50 | 51 | 52 | public static String join(List input, char port) { 53 | return org.apache.tomcat.util.buf.StringUtils.join(input, port); 54 | } 55 | 56 | public static String joinLong(List inputs, char port) { 57 | if(inputs==null||inputs.size()==0)return ""; 58 | ListnewInput=new ArrayList<>(); 59 | for(Long input:inputs)newInput.add(""+input); 60 | return org.apache.tomcat.util.buf.StringUtils.join(newInput, port); 61 | } 62 | 63 | 64 | 65 | public static Long StringToLong(String id){ 66 | try{ 67 | return Long.valueOf(id); 68 | }catch (Exception e){ 69 | e.printStackTrace(); 70 | return 0L; 71 | } 72 | 73 | } 74 | 75 | //替换标签,
换行 76 | public static String stripHtml(String input){ 77 | if(isBlank(input))return null; 78 | //

段落替换为换行 79 | input = input.replaceAll("

", "\r\n"); 80 | //

替换为换行 81 | input = input.replaceAll("", "\r\n"); 82 | // 去掉其它的<>之间的东西 83 | input = input.replaceAll("\\<.*?>", ""); 84 | // 还原HTML 85 | // content = HTMLDecoder.decode(content); 86 | return input; 87 | } 88 | //判断是否是电话号码 89 | public static boolean isPhoneNum(String phoneNumber){ 90 | String PHONE_PATTERN="^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17([0,1,6,7,]))|(18[0-2,5-9]))\\d{8}$"; 91 | return Pattern.compile(PHONE_PATTERN).matcher(phoneNumber).matches(); 92 | } 93 | public static boolean isNotPhoneNum(String phoneNumber){ 94 | return !isPhoneNum(phoneNumber); 95 | } 96 | 97 | public static String randomCode(int length){ 98 | Random random = new Random(); 99 | String code=""; 100 | while(length>0){ 101 | length--; 102 | code+=random.nextInt(10); 103 | } 104 | return code; 105 | } 106 | 107 | public static String toLowerCaseFirstOne(String s) { 108 | if(Character.isLowerCase(s.charAt(0))) 109 | return s; 110 | char[] cs = s.toCharArray(); 111 | cs[0] += 32; 112 | return String.valueOf(cs); 113 | } 114 | 115 | public static String toUpperCaseFirstOne(String s) { 116 | if(Character.isUpperCase(s.charAt(0))) 117 | return s; 118 | char[] cs = s.toCharArray(); 119 | cs[0] -= 32; 120 | return String.valueOf(cs); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | import java.util.Locale; 7 | 8 | /** 9 | * Created by liuma on 2017/7/31. 10 | */ 11 | public class DateUtils { 12 | 13 | /** 14 | * 计算两个Date之间的工作日时间差 15 | * 16 | * @param start 开始时间 17 | * @param end 结束时间 18 | * @return int 返回两天之间的工作日时间 19 | */ 20 | public static int countDutyday(Date start, Date end) { 21 | if (start == null || end == null) return 0; 22 | if (start.after(end)) return 0; 23 | Calendar c_start = Calendar.getInstance(); 24 | Calendar c_end = Calendar.getInstance(); 25 | c_start.setTime(start); 26 | c_end.setTime(end); 27 | //时分秒毫秒清零 28 | c_start.set(Calendar.HOUR_OF_DAY, 0); 29 | c_start.set(Calendar.MINUTE, 0); 30 | c_start.set(Calendar.SECOND, 0); 31 | c_start.set(Calendar.MILLISECOND, 0); 32 | c_end.set(Calendar.HOUR_OF_DAY, 0); 33 | c_end.set(Calendar.MINUTE, 0); 34 | c_end.set(Calendar.SECOND, 0); 35 | c_end.set(Calendar.MILLISECOND, 0); 36 | //初始化第二个日期,这里的天数可以随便的设置 37 | int dutyDay = 0; 38 | while (c_start.compareTo(c_end) < 0) { 39 | if (c_start.get(Calendar.DAY_OF_WEEK) != 1 && c_start.get(Calendar.DAY_OF_WEEK) != 7) 40 | dutyDay++; 41 | c_start.add(Calendar.DAY_OF_YEAR, 1); 42 | } 43 | return dutyDay; 44 | } 45 | 46 | /** 47 | * 计算两个Date之间的工作日时间差 48 | * 49 | * @param start 开始时间 50 | * @param end 结束时间 51 | * @return int 返回两天之间的节假日时间 52 | */ 53 | public static int countHoliday(Date start, Date end) { 54 | if (start == null || end == null) return 0; 55 | if (start.after(end)) return 0; 56 | Calendar c_start = Calendar.getInstance(); 57 | Calendar c_end = Calendar.getInstance(); 58 | c_start.setTime(start); 59 | c_end.setTime(end); 60 | //初始化第二个日期,这里的天数可以随便的设置 61 | int holiday = 0; 62 | while (start.compareTo(end) <= 0) { 63 | if (c_start.get(Calendar.DAY_OF_WEEK) == 1 && c_start.get(Calendar.DAY_OF_WEEK) == 7) 64 | holiday++; 65 | c_start.add(Calendar.DAY_OF_YEAR, 1); 66 | } 67 | return holiday; 68 | } 69 | 70 | /** 71 | * 获取某天0.0.0时间 72 | * */ 73 | public static Date getStartDate(){ 74 | Calendar calendar = Calendar.getInstance(); 75 | calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 76 | 0, 0, 0); 77 | return calendar.getTime(); 78 | } 79 | public static Date getEndDate(){ 80 | Calendar calendar = Calendar.getInstance(); 81 | calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 82 | 23, 59, 59); 83 | return calendar.getTime(); 84 | } 85 | 86 | /** 87 | * 获取服务器时间 88 | */ 89 | public static Date getCurrentDate() { 90 | Date date = new Date(); 91 | return date; 92 | } 93 | 94 | /** 95 | * 获取当年 96 | */ 97 | public static String getYear() { 98 | return new SimpleDateFormat("yy", Locale.CHINESE).format(new Date()); 99 | } 100 | 101 | 102 | public static String timeCalculate(Date start,Date end){ 103 | if(start==null)return "--"; 104 | if(end==null)end=getCurrentDate(); 105 | Long minus=end.getTime()-start.getTime(); 106 | if(minus<0)return "-1"; 107 | Long day=minus/(3600*24*1000); 108 | Long hour=(minus-day*(3600*1000*24))/(3600*1000); 109 | Long minutes=(minus-day*(3600*1000*24)-hour*(3600*1000))/(60*1000); 110 | Long seconds=(minus-day*(3600*1000*24)-hour*(3600*1000)-minutes*60*1000)/1000; 111 | if(day>0)return day+"天 "+hour+"小时"+minutes+"分"; 112 | else return hour+"小时"+minutes+"分"; 113 | } 114 | 115 | public static void main(String[]args){ 116 | String one=timeCalculate(null,null); 117 | String two=timeCalculate(new Date(1502619414000L),new Date(1502619414000L)); 118 | String three=timeCalculate(new Date(1502619414000L),new Date(1502619414000L)); 119 | String four=timeCalculate(new Date(1187259414000L),null); 120 | String five=timeCalculate(new Date(1187259414000L),new Date(1502792214000L)); 121 | 122 | } 123 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/MyAuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | /** 3 | * Created by luotuo on 17-6-19. 4 | */ 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | import com.luotuo.global.result.Response; 13 | import org.apache.commons.logging.Log; 14 | import org.apache.commons.logging.LogFactory; 15 | import org.springframework.security.core.Authentication; 16 | import org.springframework.security.web.DefaultRedirectStrategy; 17 | import org.springframework.security.web.RedirectStrategy; 18 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 19 | import org.springframework.security.web.savedrequest.HttpSessionRequestCache; 20 | import org.springframework.security.web.savedrequest.RequestCache; 21 | import org.springframework.security.web.savedrequest.SavedRequest; 22 | import org.springframework.util.StringUtils; 23 | 24 | public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 25 | protected final Log logger = LogFactory.getLog(this.getClass()); 26 | private RequestCache requestCache = new HttpSessionRequestCache(); 27 | 28 | private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 29 | 30 | public MyAuthenticationSuccessHandler() { 31 | } 32 | 33 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { 34 | SavedRequest savedRequest = this.requestCache.getRequest(request, response); 35 | if(savedRequest == null) { 36 | //super.onAuthenticationSuccess(request, response, authentication); 37 | handle(request, response, authentication); 38 | super.clearAuthenticationAttributes(request); 39 | } else { 40 | String targetUrlParameter = this.getTargetUrlParameter(); 41 | if(!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) { 42 | this.clearAuthenticationAttributes(request); 43 | String targetUrl = savedRequest.getRedirectUrl(); 44 | this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl); 45 | //this.getRedirectStrategy().sendRedirect(request, response, targetUrl); 46 | } else { 47 | this.requestCache.removeRequest(request, response); 48 | //super.onAuthenticationSuccess(request, response, authentication); 49 | handle(request, response, authentication); 50 | super.clearAuthenticationAttributes(request); 51 | } 52 | } 53 | } 54 | 55 | public void setRequestCache(RequestCache requestCache) { 56 | this.requestCache = requestCache; 57 | } 58 | 59 | @Override 60 | protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 61 | String targetUrl = this.determineTargetUrl(request, response); 62 | if(response.isCommitted()) { 63 | this.logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); 64 | } else { 65 | ObjectMapper mapper = new ObjectMapper(); 66 | response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); 67 | response.setHeader("Access-Control-Allow-Credentials", "true"); 68 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 69 | response.setHeader("Access-Control-Max-Age", "3600"); 70 | response.setHeader("Access-Control-Allow-Headers", "X-Request-With, JWCQ, Origin,Content-Type"); 71 | response.setContentType("text/plain;charset='utf-8'"); 72 | response.setCharacterEncoding("UTF-8"); 73 | response.setStatus(200); 74 | 75 | // Our ajax request, redirect it to login web page 76 | Response response1 = new Response(); 77 | response1.setSuccess(1); 78 | response1.setMessage("success"); 79 | response1.setResult("登录成功"); 80 | String responseStr = ""; 81 | PrintWriter out = response.getWriter(); 82 | try { 83 | responseStr = mapper.writeValueAsString(response1); 84 | out.append(responseStr); 85 | } catch (IOException ioe) { 86 | // FIXME: Add log here! 87 | out.append(ioe.toString()); 88 | } 89 | out.close(); 90 | } 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/StreamUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.FilterInputStream; 5 | import java.io.FilterOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.InputStreamReader; 9 | import java.io.OutputStream; 10 | import java.io.OutputStreamWriter; 11 | import java.io.Writer; 12 | import java.nio.charset.Charset; 13 | 14 | 15 | public class StreamUtils { 16 | public static final int BUFFER_SIZE = 4096; 17 | 18 | 19 | /** 20 | * Copy the contents of the given InputStream into a new byte array. 21 | * Leaves the stream open when done. 22 | * @param in the stream to copy from 23 | * @return the new byte array that has been copied to 24 | * @throws IOException in case of I/O errors 25 | */ 26 | public static byte[] copyToByteArray(InputStream in) throws IOException { 27 | ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); 28 | copy(in, out); 29 | return out.toByteArray(); 30 | } 31 | 32 | /** 33 | * Copy the contents of the given InputStream into a String. 34 | * Leaves the stream open when done. 35 | * @param in the InputStream to copy from 36 | * @param charset charset 37 | * @return the String that has been copied to 38 | * @throws IOException in case of I/O errors 39 | */ 40 | public static String copyToString(InputStream in, Charset charset) throws IOException { 41 | StringBuilder out = new StringBuilder(); 42 | InputStreamReader reader = new InputStreamReader(in, charset); 43 | char[] buffer = new char[BUFFER_SIZE]; 44 | int bytesRead = -1; 45 | while ((bytesRead = reader.read(buffer)) != -1) { 46 | out.append(buffer, 0, bytesRead); 47 | } 48 | return out.toString(); 49 | } 50 | 51 | /** 52 | * Copy the contents of the given byte array to the given OutputStream. 53 | * Leaves the stream open when done. 54 | * @param in the byte array to copy from 55 | * @param out the OutputStream to copy to 56 | * @throws IOException in case of I/O errors 57 | */ 58 | public static void copy(byte[] in, OutputStream out) throws IOException { 59 | out.write(in); 60 | } 61 | 62 | /** 63 | * Copy the contents of the given String to the given output OutputStream. 64 | * Leaves the stream open when done. 65 | * @param in the String to copy from 66 | * @param charset the Charset 67 | * @param out the OutputStream to copy to 68 | * @throws IOException in case of I/O errors 69 | */ 70 | public static void copy(String in, Charset charset, OutputStream out) throws IOException { 71 | Writer writer = new OutputStreamWriter(out, charset); 72 | writer.write(in); 73 | writer.flush(); 74 | } 75 | 76 | /** 77 | * Copy the contents of the given InputStream to the given OutputStream. 78 | * Leaves both streams open when done. 79 | * @param in the InputStream to copy from 80 | * @param out the OutputStream to copy to 81 | * @return the number of bytes copied 82 | * @throws IOException in case of I/O errors 83 | */ 84 | public static int copy(InputStream in, OutputStream out) throws IOException { 85 | int byteCount = 0; 86 | byte[] buffer = new byte[BUFFER_SIZE]; 87 | int bytesRead = -1; 88 | while ((bytesRead = in.read(buffer)) != -1) { 89 | out.write(buffer, 0, bytesRead); 90 | byteCount += bytesRead; 91 | } 92 | out.flush(); 93 | return byteCount; 94 | } 95 | 96 | /** 97 | * Returns a variant of the given {@link InputStream} where calling 98 | * {@link InputStream#close() close()} has no effect. 99 | * @param in the InputStream to decorate 100 | * @return a version of the InputStream that ignores calls to close 101 | */ 102 | public static InputStream nonClosing(InputStream in) { 103 | return new NonClosingInputStream(in); 104 | } 105 | 106 | /** 107 | * Returns a variant of the given {@link OutputStream} where calling 108 | * {@link OutputStream#close() close()} has no effect. 109 | * @param out the OutputStream to decorate 110 | * @return a version of the OutputStream that ignores calls to close 111 | */ 112 | public static OutputStream nonClosing(OutputStream out) { 113 | return new NonClosingOutputStream(out); 114 | } 115 | 116 | 117 | private static class NonClosingInputStream extends FilterInputStream { 118 | 119 | public NonClosingInputStream(InputStream in) { 120 | super(in); 121 | } 122 | 123 | @Override 124 | public void close() throws IOException { 125 | } 126 | } 127 | 128 | 129 | private static class NonClosingOutputStream extends FilterOutputStream { 130 | 131 | public NonClosingOutputStream(OutputStream out) { 132 | super(out); 133 | } 134 | 135 | @Override 136 | public void write(byte[] b, int off, int let) throws IOException { 137 | // It is critical that we override this method for performance 138 | out.write(b, off, let); 139 | } 140 | 141 | @Override 142 | public void close() throws IOException { 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/service/DepartmentService.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.service; 2 | 3 | import com.luotuo.user.entity.Department; 4 | import com.luotuo.user.entity.DepartmentResponse; 5 | import com.luotuo.user.repository.DepartmentRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by luotuo on 17-7-3. 15 | */ 16 | @Service 17 | @Transactional("secondTransactionManager") 18 | public class DepartmentService { 19 | @Autowired 20 | private DepartmentRepository departmentRepository; 21 | /** 22 | * @description 获取部门的列表,排好序 23 | * @return 24 | */ 25 | public List findAllTree() { 26 | // FIXME: We need a better way to build this tree in the future! 27 | // Find all roots first 28 | int level = 1; 29 | List temp = departmentRepository.findByLevel(level); 30 | List res = new ArrayList<>(); 31 | if (temp.size() > 0) { 32 | for (Department p1 : temp) { 33 | DepartmentResponse dr = new DepartmentResponse(); 34 | dr.set(p1, ""); 35 | res.add(dr); 36 | List level2 = departmentRepository.findByPid(p1.getId()); 37 | if (level2.size() > 0) { 38 | for (Department p2 : level2) { 39 | DepartmentResponse dr1 = new DepartmentResponse(); 40 | dr1.set(p2, p1.getName()); 41 | res.add(dr1); 42 | } 43 | } 44 | } 45 | } else { 46 | level = 2; 47 | List level2 = departmentRepository.findByLevel(level); 48 | if (level2.size() > 0) { 49 | for (Department p2 : level2) { 50 | DepartmentResponse dr1 = new DepartmentResponse(); 51 | dr1.set(p2, ""); 52 | res.add(dr1); 53 | } 54 | } else 55 | return level2; 56 | } 57 | 58 | return res; 59 | } 60 | /** 61 | * @description 获取所有部门 62 | * @return 63 | */ 64 | public List findAllList() { 65 | List departments = departmentRepository.findAll(); 66 | return departments; 67 | } 68 | /** 69 | * @description 通过id获取部门 70 | * @param id 部门id 71 | * @return 72 | */ 73 | public Department findById(Long id) { return departmentRepository.findById(id); } 74 | /** 75 | * @description 通过id删除部门(会递归删除下一级所有部门) 76 | * @param id 部门id 77 | */ 78 | public void deleteById(Long id) { 79 | // Delete all children 80 | List children = departmentRepository.findByPid(id); 81 | for (Department p : children) { 82 | List pp = departmentRepository.findByPid(p.getId()); 83 | if (pp == null) { 84 | departmentRepository.delete(p.getId()); 85 | } else { 86 | for (Department pChild : pp) { 87 | deleteById(pChild.getId()); 88 | } 89 | } 90 | } 91 | departmentRepository.delete(id); 92 | } 93 | /** 94 | * @description 保存部门 95 | * @param pid 部门pid 96 | * @param name 部门名称 97 | * @param level 部门级别 98 | * @return 99 | */ 100 | public Department save(long pid, String name, int level) { 101 | Department department = new Department(); 102 | department.setPid(pid); 103 | department.setLevel(level); 104 | department.setName(name); 105 | department = departmentRepository.save(department); 106 | return department; 107 | } 108 | /** 109 | * @description 更新部门 110 | * @param id 部门id 111 | * @param pid 部门pid 112 | * @param name 部门名称 113 | * @param level 部门级别 114 | * @return 115 | */ 116 | public Department update(long id, long pid, String name, int level) { 117 | Department department = null; 118 | department = departmentRepository.findById(id); 119 | if (department == null) 120 | department = new Department(); 121 | department.setPid(pid); 122 | department.setLevel(level); 123 | department.setName(name); 124 | departmentRepository.save(department); 125 | return department; 126 | } 127 | /** 128 | * @description 获取某个部门的所有子部门 129 | * @param pid 父部门id 130 | * @return 131 | */ 132 | public List getByPid(long pid) { 133 | return departmentRepository.findByPid(pid); 134 | } 135 | /** 136 | * @description 通过名称获取部门 137 | * @param name 部门名称 138 | * @return 139 | */ 140 | public List getByName(String name) { 141 | return departmentRepository.getByName(name); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/custom/MyAccessDecisionManager.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.custom; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.luotuo.global.result.Response; 5 | import com.luotuo.user.entity.UserWechat; 6 | import com.luotuo.utils.JsonUtils; 7 | import org.springframework.security.access.AccessDecisionManager; 8 | import org.springframework.security.access.AccessDeniedException; 9 | import org.springframework.security.access.ConfigAttribute; 10 | import org.springframework.security.authentication.InsufficientAuthenticationException; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.GrantedAuthority; 13 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 14 | import org.springframework.security.web.FilterInvocation; 15 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 16 | import org.springframework.stereotype.Service; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import java.io.IOException; 21 | import java.io.PrintWriter; 22 | import java.net.URLEncoder; 23 | import java.security.Principal; 24 | import java.util.Collection; 25 | 26 | /** 27 | * Created by luotuo on 17-7-3. 28 | */ 29 | @Service 30 | public class MyAccessDecisionManager implements AccessDecisionManager { 31 | 32 | //decide 方法是判定是否拥有权限的决策方法 33 | @Override 34 | public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { 35 | HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); 36 | HttpServletResponse response = ((FilterInvocation) object).getResponse(); 37 | String url, method; 38 | AntPathRequestMatcher matcher; 39 | for (GrantedAuthority ga : authentication.getAuthorities()) { 40 | if (ga instanceof AuthorityInfo) { 41 | AuthorityInfo urlGrantedAuthority = (AuthorityInfo) ga; 42 | url = urlGrantedAuthority.getUrl(); 43 | method = urlGrantedAuthority.getMethod(); 44 | matcher = new AntPathRequestMatcher(url); 45 | if (matcher.matches(request)) { 46 | //当权限表权限的method为ALL时表示拥有此路径的所有请求方式权利。 47 | // if (method.equals(request.getMethod())) { 48 | // return; 49 | // } 50 | return; 51 | } 52 | } else if (ga.getAuthority().equals("ROLE_ANONYMOUS")) {//未登录只允许访问 login 页面 53 | matcher = new AntPathRequestMatcher("/login"); 54 | if (matcher.matches(request)) { 55 | return; 56 | } 57 | } 58 | } 59 | // Tell web that you have no right! 60 | //throw new AccessDeniedException("no right"); 61 | if (request.getRequestURI().equals("/luotuo/user/currentUserInfo") || 62 | request.getRequestURI().equals("/luotuo/user/join") || 63 | request.getRequestURI().equals("/luotuo/user/wechatJoin")) 64 | return; 65 | buildAFailureResponse(response, request, authentication); 66 | throw new AccessDeniedException("no right"); 67 | } 68 | 69 | private HttpServletResponse buildAFailureResponse(HttpServletResponse response, 70 | HttpServletRequest request, 71 | Authentication authentication) { 72 | response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); 73 | response.setHeader("Access-Control-Allow-Credentials", "true"); 74 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 75 | response.setHeader("Access-Control-Max-Age", "3600"); 76 | response.setHeader("Access-Control-Allow-Headers", "X-Request-With, JWCQ, Origin,Content-Type"); 77 | response.setContentType("text/plain;charset='utf-8'"); 78 | response.setCharacterEncoding("UTF-8"); 79 | response.setStatus(200); 80 | // Our ajax request 81 | Response response1 = new Response(); 82 | response1.setSuccess(0); 83 | String resStr = "没有权限"; 84 | if (authentication.getPrincipal().toString().equals("anonymousUser")) { 85 | resStr = "请登录"; 86 | response.setStatus(208); 87 | } 88 | response1.setMessage(resStr); 89 | response1.setResult(resStr); 90 | String responseStr = ""; 91 | try { 92 | responseStr = JsonUtils.writeEntityJSON(response1); 93 | PrintWriter out = response.getWriter(); 94 | out.append(responseStr); 95 | out.close(); 96 | } catch (IOException ioe) { 97 | // FIXME: Add log here! 98 | } 99 | return response; 100 | } 101 | 102 | @Override 103 | public boolean supports(ConfigAttribute attribute) { 104 | return true; 105 | } 106 | 107 | @Override 108 | public boolean supports(Class clazz) { 109 | return true; 110 | } 111 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/XMLConverUtil.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.InputStreamReader; 6 | import java.io.Reader; 7 | import java.io.StringReader; 8 | import java.io.StringWriter; 9 | import java.io.Writer; 10 | import java.nio.charset.Charset; 11 | import java.util.HashMap; 12 | import java.util.LinkedHashMap; 13 | import java.util.Map; 14 | 15 | import javax.xml.bind.JAXBContext; 16 | import javax.xml.bind.JAXBException; 17 | import javax.xml.bind.Marshaller; 18 | import javax.xml.bind.Unmarshaller; 19 | import javax.xml.parsers.DocumentBuilder; 20 | import javax.xml.parsers.DocumentBuilderFactory; 21 | import javax.xml.parsers.ParserConfigurationException; 22 | 23 | import org.w3c.dom.DOMException; 24 | import org.w3c.dom.Document; 25 | import org.w3c.dom.Element; 26 | import org.w3c.dom.Node; 27 | import org.w3c.dom.NodeList; 28 | import org.xml.sax.InputSource; 29 | import org.xml.sax.SAXException; 30 | 31 | import com.sun.xml.bind.marshaller.CharacterEscapeHandler; 32 | 33 | /** 34 | * XML 数据接收对象转换工具类 35 | * @author LiYi 36 | * 37 | */ 38 | public class XMLConverUtil{ 39 | 40 | private static final ThreadLocal,Marshaller>> mMapLocal = new ThreadLocal,Marshaller>>() { 41 | @Override 42 | protected Map, Marshaller> initialValue() { 43 | return new HashMap, Marshaller>(); 44 | } 45 | }; 46 | 47 | private static final ThreadLocal,Unmarshaller>> uMapLocal = new ThreadLocal,Unmarshaller>>(){ 48 | @Override 49 | protected Map, Unmarshaller> initialValue() { 50 | return new HashMap, Unmarshaller>(); 51 | } 52 | }; 53 | 54 | /** 55 | * XML to Object 56 | * @param T 57 | * @param clazz clazz 58 | * @param xml xml 59 | * @return T 60 | */ 61 | public static T convertToObject(Class clazz,String xml){ 62 | return convertToObject(clazz,new StringReader(xml)); 63 | } 64 | 65 | /** 66 | * XML to Object 67 | * @param T 68 | * @param clazz clazz 69 | * @param inputStream inputStream 70 | * @return T 71 | */ 72 | public static T convertToObject(Class clazz,InputStream inputStream){ 73 | return convertToObject(clazz,new InputStreamReader(inputStream)); 74 | } 75 | 76 | /** 77 | * XML to Object 78 | * @param T 79 | * @param clazz clazz 80 | * @param inputStream inputStream 81 | * @param charset charset 82 | * @return T 83 | */ 84 | public static T convertToObject(Class clazz,InputStream inputStream,Charset charset){ 85 | return convertToObject(clazz,new InputStreamReader(inputStream, charset)); 86 | } 87 | 88 | /** 89 | * XML to Object 90 | * @param T 91 | * @param clazz clazz 92 | * @param reader reader 93 | * @return T 94 | */ 95 | @SuppressWarnings("unchecked") 96 | public static T convertToObject(Class clazz,Reader reader){ 97 | try { 98 | Map, Unmarshaller> uMap = uMapLocal.get(); 99 | if(!uMap.containsKey(clazz)){ 100 | JAXBContext jaxbContext = JAXBContext.newInstance(clazz); 101 | Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 102 | uMap.put(clazz, unmarshaller); 103 | } 104 | return (T) uMap.get(clazz).unmarshal(reader); 105 | } catch (JAXBException e) { 106 | e.printStackTrace(); 107 | } 108 | return null; 109 | } 110 | 111 | /** 112 | * Object to XML 113 | * @param object object 114 | * @return xml 115 | */ 116 | public static String convertToXML(Object object){ 117 | try { 118 | Map, Marshaller> mMap = mMapLocal.get(); 119 | if(!mMap.containsKey(object.getClass())){ 120 | JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); 121 | Marshaller marshaller = jaxbContext.createMarshaller(); 122 | marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 123 | //设置CDATA输出字符 124 | marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() { 125 | public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException { 126 | writer.write(ac, i, j); 127 | } 128 | }); 129 | mMap.put(object.getClass(), marshaller); 130 | } 131 | StringWriter stringWriter = new StringWriter(); 132 | mMap.get(object.getClass()).marshal(object,stringWriter); 133 | return stringWriter.getBuffer().toString(); 134 | } catch (JAXBException e) { 135 | e.printStackTrace(); 136 | } 137 | return null; 138 | } 139 | 140 | /** 141 | * 转换简单的xml to map 142 | * @param xml xml 143 | * @return map 144 | */ 145 | public static Map convertToMap(String xml){ 146 | Map map = new LinkedHashMap(); 147 | try { 148 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 149 | DocumentBuilder db = dbf.newDocumentBuilder(); 150 | StringReader sr = new StringReader(xml); 151 | InputSource is = new InputSource(sr); 152 | Document document = db.parse(is); 153 | 154 | Element root = document.getDocumentElement(); 155 | if(root != null){ 156 | NodeList childNodes = root.getChildNodes(); 157 | if(childNodes != null && childNodes.getLength()>0){ 158 | for(int i = 0;i < childNodes.getLength();i++){ 159 | Node node = childNodes.item(i); 160 | if( node != null && node.getNodeType() == Node.ELEMENT_NODE){ 161 | map.put(node.getNodeName(), node.getTextContent()); 162 | } 163 | } 164 | } 165 | } 166 | } catch (DOMException e) { 167 | e.printStackTrace(); 168 | } catch (ParserConfigurationException e) { 169 | e.printStackTrace(); 170 | } catch (SAXException e) { 171 | e.printStackTrace(); 172 | } catch (IOException e) { 173 | e.printStackTrace(); 174 | } 175 | return map; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/utils/JsUtil.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat.utils; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.UUID; 6 | 7 | import org.apache.commons.codec.digest.DigestUtils; 8 | 9 | public class JsUtil { 10 | 11 | //2.5.3 2.8.2 更新 12 | public static final String[] ALL_JS_API_LIST = new String[]{ 13 | //基础接口-------------------- 14 | "checkJsApi", //判断当前客户端版本是否支持指定JS接口 15 | //分享接口-------------------- 16 | "onMenuShareTimeline", //分享到朋友圈 17 | "onMenuShareAppMessage", //分享给朋友 18 | "onMenuShareQQ", //分享到QQ 19 | "onMenuShareWeibo", //分享到腾讯微博 20 | "onMenuShareQZone", //分享到QQ空间 21 | //图像接口-------------------- 22 | "chooseImage", //拍照或从手机相册中选图 23 | "previewImage", //预览图片 24 | "uploadImage", //上传图片 25 | "downloadImage", //下载图片 26 | //音频接口-------------------- 27 | "startRecord", //开始录音 28 | "stopRecord", //停止录音 29 | "onVoiceRecordEnd", //监听录音自动停止 30 | "playVoice", //播放语音 31 | "pauseVoice", //暂停播放 32 | "stopVoice", //停止播放 33 | "onVoicePlayEnd", //监听语音播放完毕 34 | "uploadVoice", //上传语音 35 | "downloadVoice", //下载语音 36 | //智能接口------------------- 37 | "translateVoice", //识别音频并返回识别结果 38 | //设备信息------------------- 39 | "getNetworkType", //获取网络状态 40 | //地理位置------------------- 41 | "openLocation", //使用微信内置地图查看位置 42 | "getLocation", //获取地理位置 43 | //摇一摇周边----------------- 44 | "startSearchBeacons", //开启查找周边ibeacon设备 45 | "stopSearchBeacons", //关闭查找周边ibeacon设备 46 | "onSearchBeacons", //监听周边ibeacon设备 47 | //界面操作------------------- 48 | "hideOptionMenu", //隐藏右上角菜单 49 | "showOptionMenu", //显示右上角菜单 50 | "closeWindow", //关闭当前网页窗口 51 | "hideMenuItems", //批量隐藏功能按钮 52 | "showMenuItems", //批量显示功能按钮 53 | "hideAllNonBaseMenuItem", //隐藏所有非基础按钮 54 | "showAllNonBaseMenuItem", //显示所有功能按钮 55 | //微信扫一扫----------------- 56 | "scanQRCode", //调起微信扫一扫 57 | //微信小店------------------- 58 | "openProductSpecificView", //跳转微信商品页 59 | //微信卡券------------------- 60 | "chooseCard", //拉取适用卡券列表并获取用户选择信息 61 | "addCard", //批量添加卡券 62 | "openCard", //查看微信卡包中的卡券 63 | //微信支付------------------- 64 | "chooseWXPay" //发起一个微信支付 65 | }; 66 | 67 | /** 68 | * 生成 config接口 signature 69 | * @param noncestr noncestr 70 | * @param jsapi_ticket jsapi_ticket 71 | * @param timestamp timestamp 72 | * @param url url 73 | * @return sign 74 | */ 75 | public static String generateConfigSignature(String noncestr,String jsapi_ticket,String timestamp,String url){ 76 | Map map = new HashMap(); 77 | map.put("noncestr", noncestr); 78 | map.put("jsapi_ticket", jsapi_ticket); 79 | map.put("timestamp", timestamp); 80 | map.put("url", url); 81 | 82 | Map tmap = MapUtil.order(map); 83 | String str = MapUtil.mapJoin(tmap,true,false); 84 | return DigestUtils.shaHex(str); 85 | } 86 | 87 | /** 88 | * 生成 config接口注入权限验证 JSON 89 | * @param jsapi_ticket jsapi_ticket 90 | * @param debug debug 91 | * @param appId appId 92 | * @param url url 93 | * @param jsApiList 可以为空
94 | * 基础接口
95 | *checkJsApi 判断当前客户端版本是否支持指定JS接口
96 | * 分享接口
97 | *onMenuShareTimeline 分享到朋友圈
98 | *onMenuShareAppMessage 分享给朋友
99 | *onMenuShareQQ 分享到QQ
100 | *onMenuShareWeibo 分享到腾讯微博
101 | *onMenuShareQZone 分享到QQ空间
102 | * 图像接口
103 | *chooseImage 拍照或从手机相册中选图
104 | *previewImage 预览图片
105 | *uploadImage 上传图片
106 | *downloadImage 下载图片
107 | * 音频接口
108 | *startRecord 开始录音
109 | *stopRecord 停止录音
110 | *onVoiceRecordEnd 监听录音自动停止
111 | *playVoice 播放语音
112 | *pauseVoice 暂停播放
113 | *stopVoice 停止播放
114 | *onVoicePlayEnd 监听语音播放完毕
115 | *uploadVoice 上传语音
116 | *downloadVoice 下载语音
117 | * 智能接口
118 | *translateVoice 识别音频并返回识别结果
119 | * 设备信息
120 | *getNetworkType 获取网络状态
121 | * 地理位置
122 | *openLocation 使用微信内置地图查看位置
123 | *getLocation 获取地理位置
124 | * 摇一摇周边
125 | *startSearchBeacons 开启查找周边ibeacon设备
126 | *stopSearchBeacons 关闭查找周边ibeacon设备
127 | *onSearchBeacons 监听周边ibeacon设备
128 | * 界面操作
129 | *hideOptionMenu 隐藏右上角菜单
130 | *showOptionMenu 显示右上角菜单
131 | *closeWindow 关闭当前网页窗口
132 | *hideMenuItems 批量隐藏功能按钮
133 | *showMenuItems 批量显示功能按钮
134 | *hideAllNonBaseMenuItem 隐藏所有非基础按钮
135 | *showAllNonBaseMenuItem 显示所有功能按钮
136 | * 微信扫一扫
137 | *scanQRCode 调起微信扫一扫
138 | * 微信小店
139 | *openProductSpecificView 跳转微信商品页
140 | * 微信卡券
141 | *chooseCard 拉取适用卡券列表并获取用户选择信息
142 | *addCard 批量添加卡券
143 | *openCard 查看微信卡包中的卡券
144 | 微信支付
145 | *chooseWXPay 发起一个微信支付
146 | * @return json 147 | */ 148 | public static String generateConfigJson(String jsapi_ticket,boolean debug,String appId,String url,String... jsApiList){ 149 | long timestamp = System.currentTimeMillis()/1000; 150 | String nonceStr = UUID.randomUUID().toString(); 151 | String signature = generateConfigSignature(nonceStr, jsapi_ticket,timestamp+"",url); 152 | return new StringBuilder() 153 | .append("{") 154 | .append("debug:").append(debug).append(",") 155 | .append("appId:").append("'").append(appId).append("'").append(",") 156 | .append("timestamp:").append(timestamp).append(",") 157 | .append("nonceStr:").append("'").append(nonceStr).append("'").append(",") 158 | .append("signature:").append("'").append(signature).append("'").append(",") 159 | .append("jsApiList:").append(JsonUtil.toJSONString(jsApiList==null?ALL_JS_API_LIST:jsApiList)) 160 | .append("}").toString(); 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ${LOG_HOME}/log_error.log 14 | 15 | 16 | 18 | ${LOG_HOME}/error/log-error-%d{yyyy-MM-dd}.%i.log 19 | 30 20 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | true 28 | 29 | 30 | ===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n 31 | utf-8 32 | 33 | 34 | 35 | error 36 | ACCEPT 37 | DENY 38 | 39 | 40 | 41 | 42 | 43 | 44 | ${LOG_HOME}/log_warn.log 45 | 46 | 47 | 49 | ${LOG_HOME}/warn/log-warn-%d{yyyy-MM-dd}.%i.log 50 | 30 51 | 53 | 54 | 10MB 55 | 56 | 57 | 58 | true 59 | 60 | 61 | ===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n 62 | utf-8 63 | 64 | 65 | 66 | warn 67 | ACCEPT 68 | DENY 69 | 70 | 71 | 72 | 73 | 74 | 75 | ${LOG_HOME}/log_info.log 76 | 77 | 78 | 80 | ${LOG_HOME}/info/log-info-%d{yyyy-MM-dd}.%i.log 81 | 30 82 | 84 | 85 | 10MB 86 | 87 | 88 | 89 | true 90 | 91 | 92 | ===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n 93 | utf-8 94 | 95 | 96 | 97 | info 98 | ACCEPT 99 | DENY 100 | 101 | 102 | 103 | 104 | 105 | 106 | ===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n 107 | utf-8 108 | 109 | 110 | 111 | debug 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/MyOAuth2ClientAuthenticationProcessingFilter.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | import org.springframework.context.ApplicationEvent; 4 | import org.springframework.context.ApplicationEventPublisher; 5 | import org.springframework.security.authentication.AuthenticationDetailsSource; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.authentication.BadCredentialsException; 8 | import org.springframework.security.authentication.event.AuthenticationSuccessEvent; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.oauth2.client.OAuth2RestOperations; 12 | import org.springframework.security.oauth2.client.filter.OAuth2AuthenticationFailureEvent; 13 | import org.springframework.security.oauth2.client.http.AccessTokenRequiredException; 14 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 15 | import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; 16 | import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; 17 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 18 | import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; 19 | import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetailsSource; 20 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 21 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 22 | import org.springframework.util.Assert; 23 | 24 | import javax.servlet.FilterChain; 25 | import javax.servlet.ServletException; 26 | import javax.servlet.http.HttpServletRequest; 27 | import javax.servlet.http.HttpServletResponse; 28 | import java.io.IOException; 29 | 30 | /** 31 | * Created by luotuo on 17-9-27. 32 | */ 33 | public class MyOAuth2ClientAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { 34 | public OAuth2RestOperations restTemplate; 35 | private MyResourceServerTokenServices tokenServices; 36 | private AuthenticationDetailsSource authenticationDetailsSource = new OAuth2AuthenticationDetailsSource(); 37 | private ApplicationEventPublisher eventPublisher; 38 | 39 | public void setTokenServices(MyResourceServerTokenServices tokenServices) { 40 | this.tokenServices = tokenServices; 41 | } 42 | 43 | public void setRestTemplate(OAuth2RestOperations restTemplate) { 44 | this.restTemplate = restTemplate; 45 | } 46 | 47 | public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) { 48 | this.eventPublisher = eventPublisher; 49 | super.setApplicationEventPublisher(eventPublisher); 50 | } 51 | 52 | public MyOAuth2ClientAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { 53 | super(defaultFilterProcessesUrl); 54 | this.setAuthenticationManager(new MyOAuth2ClientAuthenticationProcessingFilter.NoopAuthenticationManager()); 55 | this.setAuthenticationDetailsSource(this.authenticationDetailsSource); 56 | } 57 | 58 | public void afterPropertiesSet() { 59 | Assert.state(this.restTemplate != null, "Supply a rest-template"); 60 | super.afterPropertiesSet(); 61 | } 62 | 63 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { 64 | OAuth2AccessToken accessToken; 65 | BadCredentialsException bad; 66 | try { 67 | accessToken = this.restTemplate.getAccessToken(); 68 | } catch (OAuth2Exception var7) { 69 | bad = new BadCredentialsException("Could not obtain access token", var7); 70 | this.publish(new OAuth2AuthenticationFailureEvent(bad)); 71 | throw bad; 72 | } 73 | 74 | try { 75 | OAuth2Authentication result = this.tokenServices.loadAuthentication(accessToken.getValue(), 76 | request.getRemoteHost()); 77 | if(this.authenticationDetailsSource != null) { 78 | request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, accessToken.getValue()); 79 | request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType()); 80 | result.setDetails(this.authenticationDetailsSource.buildDetails(request)); 81 | } 82 | 83 | this.publish(new AuthenticationSuccessEvent(result)); 84 | return result; 85 | } catch (InvalidTokenException var6) { 86 | bad = new BadCredentialsException("Could not obtain user details from token", var6); 87 | this.publish(new OAuth2AuthenticationFailureEvent(bad)); 88 | throw bad; 89 | } 90 | } 91 | 92 | private void publish(ApplicationEvent event) { 93 | if(this.eventPublisher != null) { 94 | this.eventPublisher.publishEvent(event); 95 | } 96 | 97 | } 98 | 99 | protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { 100 | super.successfulAuthentication(request, response, chain, authResult); 101 | this.restTemplate.getAccessToken(); 102 | } 103 | 104 | protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { 105 | if(failed instanceof AccessTokenRequiredException) { 106 | throw failed; 107 | } else { 108 | super.unsuccessfulAuthentication(request, response, failed); 109 | } 110 | } 111 | 112 | private static class NoopAuthenticationManager implements AuthenticationManager { 113 | private NoopAuthenticationManager() { 114 | } 115 | 116 | public Authentication authenticate(Authentication authentication) throws AuthenticationException { 117 | throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager"); 118 | } 119 | } 120 | } 121 | 122 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/utils/HttpUtils.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.utils; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.InvocationTargetException; 6 | import java.lang.reflect.Method; 7 | import java.math.BigDecimal; 8 | 9 | public class HttpUtils { 10 | 11 | /** 12 | *@param request 13 | *@param Clazz 传入的实体类 14 | *@function 返回的是格式化后的对象。本函数将request根据传入的类Clazz进行格式化 15 | *@return dtoObj 16 | */ 17 | public static Object FormatRequest(HttpServletRequest request, Class Clazz) { 18 | Object dtoObj = null; 19 | if ((Clazz == null) || (request == null)) 20 | return dtoObj; 21 | try { 22 | //实例化对象 23 | dtoObj = Clazz.newInstance(); 24 | setDTOValue(request, dtoObj); 25 | } catch (Exception ex) { 26 | ex.printStackTrace(); 27 | } 28 | return dtoObj; 29 | } 30 | /** 31 | *@param request 32 | *@param object 传入的实体对象 33 | *@function 返回的是格式化后的对象。 34 | * 本函数将request根据传入的对象object进行格式化, 35 | * 如果不存在的属性,则不改变原值。适合用于update 36 | *@return dtoObj 37 | */ 38 | public static Object FormatRequest(HttpServletRequest request, Object object) { 39 | if ((object == null) || (request == null)) 40 | return object; 41 | try { 42 | setDTOValue(request, object); 43 | } catch (Exception ex) { 44 | ex.printStackTrace(); 45 | } 46 | return object; 47 | } 48 | /** 49 | * 保存数据 50 | *@param request 51 | *@param dto 52 | *@throws Exception 53 | */ 54 | public static void setDTOValue(HttpServletRequest request, Object dto) throws Exception { 55 | if ((dto == null) || (request == null)) 56 | return; 57 | //得到类中所有的方法 基本上都是set和get方法 58 | Method[] methods = dto.getClass().getMethods(); 59 | for (int i = 0; i < methods.length; i++) { 60 | try { 61 | //方法名 62 | String methodName = methods[i].getName(); 63 | //方法参数的类型 64 | Class[] type = methods[i].getParameterTypes(); 65 | //当时set方法时,判断依据:setXxxx类型 66 | if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) { 67 | //将set后面的大写字母转成小写并截取出来 68 | String name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4); 69 | Object objValue = getBindValue(request, name, type[0]); 70 | if (objValue != null) {//request中数据不为空时,则赋值 71 | Object[] value = { objValue }; 72 | invokeMothod(dto, methodName, type, value); 73 | } 74 | } 75 | } catch (Exception ex) { 76 | throw ex; 77 | } 78 | } 79 | } 80 | /** 81 | * 通过request得到相应的值 82 | *@param request HttpServletRequest 83 | *@param bindName 属性名 84 | *@param bindType 属性的类型 85 | *@return 86 | */ 87 | public static Object getBindValue(HttpServletRequest request, String bindName, Class bindType) { 88 | //得到request中的值 89 | String value = request.getParameter(bindName); 90 | if (value != null) { 91 | value = value.trim();//去除值中前后空格 92 | } 93 | return getBindValue(value, bindType); 94 | } 95 | /** 96 | * 通过调用方法名(setXxxx)将值设置到属性中 97 | *@param classObject 实体类对象 98 | *@param strMethodName 方法名(一般都是setXxxx) 99 | *@param argsType 属性类型数组 100 | *@param args 属性值数组 101 | *@return 102 | *@throws NoSuchMethodException 103 | *@throws SecurityException 104 | *@throws IllegalAccessException 105 | *@throws IllegalArgumentException 106 | *@throws InvocationTargetException 107 | */ 108 | public static Object invokeMothod(Object classObject, String strMethodName, Class[] argsType, Object[] args) 109 | throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, 110 | InvocationTargetException { 111 | //得到classObject这个类的方法 112 | Method concatMethod = classObject.getClass().getMethod(strMethodName, argsType); 113 | //调用方法将classObject赋值到相应的属性 114 | return concatMethod.invoke(classObject, args); 115 | } 116 | /** 117 | * 根据bindType类型的不同转成相应的类型值 118 | *@param value String类型的值,要根据bindType类型的不同转成相应的类型值 119 | *@param bindType 属性的类型 120 | *@return 121 | */ 122 | public static Object getBindValue(String value, Class bindType) { 123 | if (value == null) 124 | return null; 125 | String typeName = bindType.getName(); 126 | if (value.trim().length() == 0) { 127 | if (typeName.equals("java.lang.String")) return value; 128 | else return null; 129 | } 130 | 131 | //依次判断各种类型并转换相应的值 132 | if (typeName.equals("java.lang.String")) 133 | return value; 134 | //如果前端引入的有引号 135 | value=value.replace("\"",""); 136 | value=value.replace("\'",""); 137 | if (typeName.equals("int")) 138 | return new Integer(Integer.valueOf(value)); 139 | if (typeName.equals("long")) 140 | return new Long(Long.valueOf(value)); 141 | if (typeName.equals("boolean")) 142 | return new Boolean(value); 143 | if (typeName.equals("float")) 144 | return new Float(value); 145 | if (typeName.equals("double")) 146 | return new Double(value); 147 | if (typeName.equals("java.math.BigDecimal")) { 148 | if ("NaN.00".equals(value)) 149 | return new BigDecimal("0"); 150 | return new BigDecimal(value.trim()); 151 | } 152 | if (typeName.equals("java.util.Date")) 153 | return Format.formatDate(value); 154 | if (typeName.equals("java.lang.Integer")) 155 | return new Integer(Integer.valueOf(value)); 156 | if (typeName.equals("java.lang.Long")) { 157 | return new Long(Long.valueOf(value)); 158 | } 159 | if (typeName.equals("java.lang.Boolean")) { 160 | return new Boolean(Boolean.valueOf(value)); 161 | } 162 | return value; 163 | } 164 | } -------------------------------------------------------------------------------- /src/main/java/com/luotuo/wechat/HttpClientFactory.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.wechat; 2 | 3 | import java.io.IOException; 4 | import java.io.InterruptedIOException; 5 | import java.net.UnknownHostException; 6 | import java.security.KeyManagementException; 7 | import java.security.KeyStore; 8 | import java.security.KeyStoreException; 9 | import java.security.NoSuchAlgorithmException; 10 | import java.security.UnrecoverableKeyException; 11 | 12 | import javax.net.ssl.SSLContext; 13 | import javax.net.ssl.SSLException; 14 | 15 | import org.apache.http.HttpEntityEnclosingRequest; 16 | import org.apache.http.HttpRequest; 17 | import org.apache.http.client.HttpRequestRetryHandler; 18 | import org.apache.http.client.protocol.HttpClientContext; 19 | import org.apache.http.config.SocketConfig; 20 | import org.apache.http.conn.ConnectTimeoutException; 21 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 22 | import org.apache.http.conn.ssl.SSLContexts; 23 | import org.apache.http.impl.client.CloseableHttpClient; 24 | import org.apache.http.impl.client.HttpClientBuilder; 25 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 26 | import org.apache.http.protocol.HttpContext; 27 | 28 | /** 29 | * httpclient 4.3.x 30 | * @author Yi 31 | * 32 | */ 33 | public class HttpClientFactory{ 34 | 35 | private static final String[] supportedProtocols = new String[]{"TLSv1"}; 36 | 37 | public static CloseableHttpClient createHttpClient() { 38 | return createHttpClient(100,10,5000,2); 39 | } 40 | 41 | /** 42 | * 43 | * @param maxTotal maxTotal 44 | * @param maxPerRoute maxPerRoute 45 | * @param timeout timeout 46 | * @param retryExecutionCount retryExecutionCount 47 | * @return CloseableHttpClient 48 | */ 49 | public static CloseableHttpClient createHttpClient(int maxTotal,int maxPerRoute,int timeout,int retryExecutionCount) { 50 | try { 51 | SSLContext sslContext = SSLContexts.custom().useSSL().build(); 52 | SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 53 | PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); 54 | poolingHttpClientConnectionManager.setMaxTotal(maxTotal); 55 | poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute); 56 | SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); 57 | poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig); 58 | return HttpClientBuilder.create() 59 | .setConnectionManager(poolingHttpClientConnectionManager) 60 | .setSSLSocketFactory(sf) 61 | .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) 62 | .build(); 63 | } catch (KeyManagementException e) { 64 | e.printStackTrace(); 65 | } catch (NoSuchAlgorithmException e) { 66 | e.printStackTrace(); 67 | } 68 | return null; 69 | } 70 | 71 | /** 72 | * Key store 类型HttpClient 73 | * @param keystore keystore 74 | * @param keyPassword keyPassword 75 | * @param timeout timeout 76 | * @param retryExecutionCount retryExecutionCount 77 | * @return CloseableHttpClient 78 | */ 79 | public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,int timeout,int retryExecutionCount) { 80 | return createKeyMaterialHttpClient(keystore, keyPassword, supportedProtocols,timeout,retryExecutionCount); 81 | } 82 | 83 | /** 84 | * Key store 类型HttpClient 85 | * @param keystore keystore 86 | * @param keyPassword keyPassword 87 | * @param supportedProtocols supportedProtocols 88 | * @param timeout timeout 89 | * @param retryExecutionCount retryExecutionCount 90 | * @return CloseableHttpClient 91 | */ 92 | public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,String[] supportedProtocols,int timeout,int retryExecutionCount) { 93 | try { 94 | SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build(); 95 | SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,supportedProtocols, 96 | null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); 97 | SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); 98 | return HttpClientBuilder.create() 99 | .setDefaultSocketConfig(socketConfig) 100 | .setSSLSocketFactory(sf) 101 | .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) 102 | .build(); 103 | } catch (KeyManagementException e) { 104 | e.printStackTrace(); 105 | } catch (NoSuchAlgorithmException e) { 106 | e.printStackTrace(); 107 | } catch (UnrecoverableKeyException e) { 108 | e.printStackTrace(); 109 | } catch (KeyStoreException e) { 110 | e.printStackTrace(); 111 | } 112 | return null; 113 | } 114 | 115 | /** 116 | * 117 | * HttpClient 超时重试 118 | * @author LiYi 119 | */ 120 | private static class HttpRequestRetryHandlerImpl implements HttpRequestRetryHandler{ 121 | 122 | private int retryExecutionCount; 123 | 124 | public HttpRequestRetryHandlerImpl(int retryExecutionCount){ 125 | this.retryExecutionCount = retryExecutionCount; 126 | } 127 | 128 | @Override 129 | public boolean retryRequest( 130 | IOException exception, 131 | int executionCount, 132 | HttpContext context) { 133 | if (executionCount > retryExecutionCount) { 134 | return false; 135 | } 136 | if (exception instanceof InterruptedIOException) { 137 | return false; 138 | } 139 | if (exception instanceof UnknownHostException) { 140 | return false; 141 | } 142 | if (exception instanceof ConnectTimeoutException) { 143 | return true; 144 | } 145 | if (exception instanceof SSLException) { 146 | return false; 147 | } 148 | HttpClientContext clientContext = HttpClientContext.adapt(context); 149 | HttpRequest request = clientContext.getRequest(); 150 | boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); 151 | if (idempotent) { 152 | // Retry if the request is considered idempotent 153 | return true; 154 | } 155 | return false; 156 | } 157 | 158 | }; 159 | 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/com/luotuo/config/MySimpleUrlAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.luotuo.config; 2 | 3 | /** 4 | * Created by luotuo on 17-6-22. 5 | */ 6 | 7 | import com.luotuo.global.result.Response; 8 | 9 | import java.io.IOException; 10 | import java.io.PrintWriter; 11 | import java.net.URLEncoder; 12 | import java.util.Enumeration; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import javax.servlet.http.HttpSession; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.luotuo.utils.SystemConfig; 20 | import org.apache.commons.logging.Log; 21 | import org.apache.commons.logging.LogFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.beans.factory.annotation.Value; 24 | import org.springframework.context.annotation.Configuration; 25 | import org.springframework.security.authentication.BadCredentialsException; 26 | import org.springframework.security.core.AuthenticationException; 27 | import org.springframework.security.web.DefaultRedirectStrategy; 28 | import org.springframework.security.web.RedirectStrategy; 29 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 30 | import org.springframework.security.web.authentication.session.SessionAuthenticationException; 31 | import org.springframework.security.web.util.UrlUtils; 32 | import org.springframework.stereotype.Service; 33 | import org.springframework.util.Assert; 34 | 35 | public class MySimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler { 36 | protected final Log logger = LogFactory.getLog(this.getClass()); 37 | private String defaultFailureUrl; 38 | private boolean forwardToDestination = false; 39 | private boolean allowSessionCreation = true; 40 | private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 41 | 42 | public MySimpleUrlAuthenticationFailureHandler() { 43 | } 44 | 45 | public MySimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) { 46 | this.setDefaultFailureUrl(defaultFailureUrl); 47 | } 48 | 49 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 50 | if (this.defaultFailureUrl == null) { 51 | if (request.getMethod().equalsIgnoreCase("OPTIONS")) { 52 | response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); 53 | response.setHeader("Access-Control-Allow-Credentials", "true"); 54 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 55 | response.setHeader("Access-Control-Max-Age", "3600"); 56 | response.setHeader("Access-Control-Allow-Headers", "X-Request-With, LUOTUO, Origin,Content-Type, luotuo"); 57 | response.setCharacterEncoding("UTF-8"); 58 | response.setStatus(202); 59 | } else { 60 | this.logger.debug("No failure URL set, sending 401 Unauthorized error"); 61 | System.out.println("onAuthenticationFailure======================================"); 62 | ObjectMapper mapper = new ObjectMapper(); 63 | response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); 64 | response.setHeader("Access-Control-Allow-Credentials", "true"); 65 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 66 | response.setHeader("Access-Control-Max-Age", "3600"); 67 | response.setHeader("Access-Control-Allow-Headers", "X-Request-With, LUOTUO, Origin,Content-Type"); 68 | response.setContentType("text/plain;charset='utf-8'"); 69 | response.setCharacterEncoding("UTF-8"); 70 | response.setStatus(200); 71 | 72 | // Our ajax request, redirect it to login web page 73 | Response response1 = new Response(); 74 | response1.setSuccess(1); 75 | response1.setMessage("success"); 76 | response1.setResult("登录失败,用户名或密码错误"); 77 | String responseStr = ""; 78 | PrintWriter out = response.getWriter(); 79 | try { 80 | responseStr = mapper.writeValueAsString(response1); 81 | out.append(responseStr); 82 | } catch (IOException ioe) { 83 | // FIXME: Add log here! 84 | out.append(ioe.toString()); 85 | } 86 | out.close(); 87 | System.out.println("Return our response!"); 88 | } 89 | } 90 | } 91 | 92 | protected final void saveException(HttpServletRequest request, AuthenticationException exception) { 93 | if (this.forwardToDestination) { 94 | request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception); 95 | } else { 96 | HttpSession session = request.getSession(false); 97 | if (session != null || this.allowSessionCreation) { 98 | request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception); 99 | } 100 | } 101 | 102 | } 103 | 104 | public void setDefaultFailureUrl(String defaultFailureUrl) { 105 | Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), "'" + defaultFailureUrl + "' is not a valid redirect URL"); 106 | this.defaultFailureUrl = defaultFailureUrl; 107 | } 108 | 109 | protected boolean isUseForward() { 110 | return this.forwardToDestination; 111 | } 112 | 113 | public void setUseForward(boolean forwardToDestination) { 114 | this.forwardToDestination = forwardToDestination; 115 | } 116 | 117 | public void setRedirectStrategy(RedirectStrategy redirectStrategy) { 118 | this.redirectStrategy = redirectStrategy; 119 | } 120 | 121 | protected RedirectStrategy getRedirectStrategy() { 122 | return this.redirectStrategy; 123 | } 124 | 125 | protected boolean isAllowSessionCreation() { 126 | return this.allowSessionCreation; 127 | } 128 | 129 | public void setAllowSessionCreation(boolean allowSessionCreation) { 130 | this.allowSessionCreation = allowSessionCreation; 131 | } 132 | } 133 | 134 | --------------------------------------------------------------------------------