Browse Source

add oauth2 impl

zhouhao 7 years ago
parent
commit
64556009e5

+ 26 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/pom.xml

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>hsweb-system-file-service</artifactId>
+        <groupId>org.hswebframework.web</groupId>
+        <version>3.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>hsweb-system-file-service-oauth2</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-system-file-service-api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-commons-service-oauth2</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+    </dependencies>
+</project>

+ 28 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/main/java/org/hswebframework/web/service/file/oauth2/OAuth2FileAutoConfiguration.java

@@ -0,0 +1,28 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author zhouhao
+ * @since 3.0
+ */
+@Configuration
+@ConditionalOnBean(OAuth2RequestService.class)
+public class OAuth2FileAutoConfiguration {
+
+    @ConfigurationProperties(prefix = "hsweb.oauth2.file-server")
+    @Bean
+    public OAuth2FileInfoService oAuth2FileInfoService() {
+        return new OAuth2FileInfoService();
+    }
+
+    @ConfigurationProperties(prefix = "hsweb.oauth2.file-server")
+    @Bean
+    public OAuth2FileService oAuth2FileService() {
+        return new OAuth2FileService();
+    }
+}

+ 50 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/main/java/org/hswebframework/web/service/file/oauth2/OAuth2FileInfoService.java

@@ -0,0 +1,50 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import org.hswebframework.web.commons.entity.param.QueryParamEntity;
+import org.hswebframework.web.entity.file.FileInfoEntity;
+import org.hswebframework.web.service.file.FileInfoService;
+import org.hswebframework.web.service.oauth2.AbstractOAuth2CrudService;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * @author zhouhao
+ * @since
+ */
+
+public class OAuth2FileInfoService extends AbstractOAuth2CrudService<FileInfoEntity, String> implements FileInfoService {
+
+    private String serviceId = "file-server";
+
+    private String uriPrefix = "file-info";
+
+    @Override
+    public FileInfoEntity selectByMd5(String md5) {
+        return selectSingle(QueryParamEntity
+                .single(FileInfoEntity.md5, md5));
+    }
+
+    @Override
+    public FileInfoEntity selectByIdOrMd5(String idOrMd5) {
+        return selectSingle(QueryParamEntity
+                .single(FileInfoEntity.id, idOrMd5)
+                .or(FileInfoEntity.md5, idOrMd5));
+    }
+
+    @Override
+    public String getServiceId() {
+        return serviceId;
+    }
+
+    @Override
+    public String getUriPrefix() {
+        return uriPrefix;
+    }
+
+    public void setServiceId(String serviceId) {
+        this.serviceId = serviceId;
+    }
+
+    public void setUriPrefix(String uriPrefix) {
+        this.uriPrefix = uriPrefix;
+    }
+}

+ 85 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/main/java/org/hswebframework/web/service/file/oauth2/OAuth2FileService.java

@@ -0,0 +1,85 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+import org.hswebframework.web.entity.file.FileInfoEntity;
+import org.hswebframework.web.entity.file.SimpleFileInfoEntity;
+import org.hswebframework.web.service.file.FileService;
+import org.hswebframework.web.service.oauth2.OAuth2ServiceSupport;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.util.StreamUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @author zhouhao
+ * @since 3.0
+ */
+@ConfigurationProperties(prefix = "hsweb.oauth2.file-server")
+public class OAuth2FileService implements FileService, OAuth2ServiceSupport {
+    private String serviceId = "file-server";
+
+    private String uriPrefix = "file";
+
+    @Autowired
+    private OAuth2RequestService requestService;
+
+    @Override
+    public InputStream readFile(String fileIdOrMd5) {
+        return createRequest("/md5/download/" + fileIdOrMd5)
+                .get()
+                .as(OAuth2Response::asStream);
+    }
+
+    @Override
+    public FileInfoEntity saveFile(InputStream fileStream, String fileName, String type, String creatorId) throws IOException {
+        return createRequest("/upload")
+                .upload(fileName, fileStream)
+                .post().as(getEntityType());
+    }
+
+    @Override
+    public String saveStaticFile(InputStream fileStream, String fileName) throws IOException {
+        return createRequest("/upload-static")
+                .upload(fileName, fileStream)
+                .post()
+                .as(String.class);
+    }
+
+    @Override
+    public void writeFile(String fileId, OutputStream out, long skip) throws IOException {
+        StreamUtils.copy(createRequest("/download/" + fileId)
+                .header("Range", "bytes=" + skip)
+                .get().asStream(), out);
+    }
+
+    @Override
+    public OAuth2RequestService getRequestService() {
+        return requestService;
+    }
+
+    @Override
+    public String getServiceId() {
+        return serviceId;
+    }
+
+    @Override
+    public String getUriPrefix() {
+        return uriPrefix;
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Class<SimpleFileInfoEntity> getEntityType() {
+        return SimpleFileInfoEntity.class;
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Class<String> getPrimaryKeyType() {
+        return String.class;
+    }
+}

+ 3 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/main/resources/META-INF/spring.factories

@@ -0,0 +1,3 @@
+# Auto Configure
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+org.hswebframework.web.service.file.oauth2.OAuth2FileAutoConfiguration

+ 104 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/test/java/org/hswebframework/web/service/file/oauth2/MockOAuth2Request.java

@@ -0,0 +1,104 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import lombok.extern.slf4j.Slf4j;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
+import org.hswebframework.web.authorization.oauth2.client.request.TokenExpiredCallBack;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+
+import java.io.InputStream;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+@Slf4j
+public class MockOAuth2Request implements OAuth2Request {
+
+    private Function<String,OAuth2Response> responseGetter;
+
+    public MockOAuth2Request(Function<String,OAuth2Response> responseGetter) {
+        this.responseGetter = responseGetter;
+    }
+
+    @Override
+    public OAuth2Request onRefreshTokenExpired(TokenExpiredCallBack refreshTokenExpiredCallBack) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request onTokenExpired(TokenExpiredCallBack callback) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request param(String name, Object value) {
+        log.info("set param :{}={}", name, value);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request params(Map<String, String> params) {
+        log.info("set params :{}", params);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request upload(String name, InputStream inputStream) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request requestBody(String value) {
+        log.info("set request body :{}", value);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request header(String name, String value) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request cookie(String cookie) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request contentType(String contentType) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request accept(String accept) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request timeout(long millisecond, Consumer<OAuth2Request> timeoutCallBack) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Response get() {
+        return responseGetter.apply("get");
+    }
+
+    @Override
+    public OAuth2Response put() {
+        return responseGetter.apply("put");
+    }
+
+    @Override
+    public OAuth2Response post() {
+        return responseGetter.apply("post");
+    }
+
+    @Override
+    public OAuth2Response delete() {
+        return responseGetter.apply("delete");
+    }
+
+    @Override
+    public OAuth2Response patch() {
+        return responseGetter.apply("patch");
+    }
+}

+ 71 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/test/java/org/hswebframework/web/service/file/oauth2/MockOAuth2Response.java

@@ -0,0 +1,71 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import org.hswebframework.web.authorization.oauth2.client.request.ResponseConvertHandler;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+import org.hswebframework.web.authorization.oauth2.client.response.ResponseConvert;
+import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseConvertSupport;
+import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilderFactory;
+import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
+import org.hswebframework.web.oauth2.core.ErrorType;
+import org.springframework.util.StreamUtils;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+public class MockOAuth2Response implements OAuth2Response {
+
+    private InputStream result;
+
+    private ResponseConvertHandler handler = new HswebResponseConvertSupport(new SimpleAuthenticationBuilderFactory(new SimpleDataAccessConfigBuilderFactory()));
+
+    @Override
+    public InputStream asStream() {
+        return result;
+    }
+
+    public MockOAuth2Response(InputStream result) {
+        this.result = result;
+    }
+
+    @Override
+    public String asString() {
+        return new String(asBytes());
+    }
+
+    @Override
+    public byte[] asBytes() {
+        try {
+            return StreamUtils.copyToByteArray(result);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public <T> T as(ResponseConvert<T> convert) {
+        return convert.convert(this);
+    }
+
+    @Override
+    public <T> T as(Class<T> type) {
+        return handler.convert(this, type);
+    }
+
+    @Override
+    public <T> List<T> asList(Class<T> type) {
+        return handler.convertList(this, type);
+    }
+
+    @Override
+    public int status() {
+        return 200;
+    }
+
+    @Override
+    public OAuth2Response onError(BiConsumer<OAuth2Response, ErrorType> onError) {
+        return this;
+    }
+}

+ 111 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/hsweb-system-file-service-oauth2/src/test/java/org/hswebframework/web/service/file/oauth2/OAuth2FileServiceTest.java

@@ -0,0 +1,111 @@
+package org.hswebframework.web.service.file.oauth2;
+
+import com.alibaba.fastjson.JSON;
+import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
+import org.hswebframework.web.authorization.oauth2.client.OAuth2SessionBuilder;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
+import org.hswebframework.web.commons.entity.PagerResult;
+import org.hswebframework.web.controller.message.ResponseMessage;
+import org.hswebframework.web.entity.file.FileInfoEntity;
+import org.hswebframework.web.entity.file.SimpleFileInfoEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author zhouhao
+ * @since
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class OAuth2FileServiceTest {
+
+    @InjectMocks
+    private OAuth2FileService fileService = new OAuth2FileService();
+
+    @Mock
+    private OAuth2RequestService auth2RequestService;
+
+    @Mock
+    private OAuth2Session oAuth2Session;
+
+    @Before
+    public void init() {
+        when(oAuth2Session.request("file/download/test")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("get", new ByteArrayInputStream("test".getBytes())))
+        );
+
+        when(oAuth2Session.request("file/upload")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("post", ResponseMessage.ok(SimpleFileInfoEntity.builder()
+                                .md5("test")
+                                .build()).toString()))
+        );
+
+        when(oAuth2Session.request("file/upload-static")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("post", ResponseMessage.ok("http://file-server/upload/test.png").toString())));
+        OAuth2SessionBuilder builder = mock(OAuth2SessionBuilder.class);
+        when(builder.byClientCredentials()).thenReturn(oAuth2Session);
+
+        when(auth2RequestService.create(anyString())).thenReturn(builder);
+
+    }
+
+    @Test
+    public void uploadTest() throws IOException {
+        String staticFile = fileService.saveStaticFile(new ByteArrayInputStream("test".getBytes()), "test");
+        Assert.assertEquals(staticFile, "http://file-server/upload/test.png");
+        FileInfoEntity entity = fileService.saveFile(new ByteArrayInputStream("test".getBytes()), "test", "text/plain", "admin");
+        Assert.assertNotNull(entity);
+        Assert.assertEquals(entity.getMd5(), "test");
+    }
+
+    interface OAuth2MethodRequest {
+        String getMethod();
+
+        InputStream getResponse();
+    }
+
+    public OAuth2MethodRequest whenRequest(String method, String json) {
+        return whenRequest(method, new ByteArrayInputStream(json.getBytes()));
+    }
+
+    public OAuth2MethodRequest whenRequest(String method, InputStream stream) {
+        return new OAuth2MethodRequest() {
+            @Override
+            public String getMethod() {
+                return method;
+            }
+
+            @Override
+            public InputStream getResponse() {
+                return stream;
+            }
+        };
+    }
+
+    private OAuth2Request createFixedResponseRequest(OAuth2MethodRequest... requests) {
+        return new MockOAuth2Request((method) -> {
+            for (OAuth2MethodRequest request : requests) {
+                if (request.getMethod().equals(method)) {
+                    return new MockOAuth2Response(request.getResponse());
+                }
+            }
+            return new MockOAuth2Response(new ByteArrayInputStream(ResponseMessage.error(404, "not found").toString().getBytes()));
+        });
+    }
+}

+ 1 - 0
hsweb-system/hsweb-system-file/hsweb-system-file-service/pom.xml

@@ -14,6 +14,7 @@
     <modules>
         <module>hsweb-system-file-service-api</module>
         <module>hsweb-system-file-service-simple</module>
+        <module>hsweb-system-file-service-oauth2</module>
     </modules>