Explorar el Código

对接Oauth2平台

jtoms hace 4 años
padre
commit
f15d3e524a

+ 5 - 0
src/main/java/com/zhiqiyun/open/config/RedisKeys.java

@@ -23,4 +23,9 @@ public interface RedisKeys {
      * AppKey获取Key
      */
     String APP_KEY_INFO = "APP_KEY_INFO:%s";
+
+    /**
+     * 系统配置
+     */
+    String SYSTEM_CONFIG_KEY = "SYSTEM_CONFIG_KEY:%s";
 }

+ 9 - 0
src/main/java/com/zhiqiyun/open/core/mapper/SystemConfigItemMapper.java

@@ -0,0 +1,9 @@
+package com.zhiqiyun.open.core.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.zhiqiyun.open.core.models.settings.SystemConfigItem;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface SystemConfigItemMapper extends BaseMapper<SystemConfigItem> {
+}

+ 9 - 0
src/main/java/com/zhiqiyun/open/core/mapper/SystemConfigMapper.java

@@ -0,0 +1,9 @@
+package com.zhiqiyun.open.core.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.zhiqiyun.open.core.models.settings.SystemConfig;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface SystemConfigMapper extends BaseMapper<SystemConfig> {
+}

+ 6 - 1
src/main/java/com/zhiqiyun/open/core/models/SystemConfig.java → src/main/java/com/zhiqiyun/open/core/models/settings/SystemConfig.java

@@ -1,5 +1,6 @@
-package com.zhiqiyun.open.core.models;
+package com.zhiqiyun.open.core.models.settings;
 
+import com.baomidou.mybatisplus.annotation.*;
 import lombok.Data;
 
 import java.io.Serializable;
@@ -9,12 +10,16 @@ import java.util.List;
  * @author jtoms
  */
 @Data
+@TableName("setting_system_config")
 public class SystemConfig implements Serializable {
     private static final long serialVersionUID = 5044998314209760622L;
+    @TableId(type = IdType.INPUT)
     private String id;
+    @TableField(updateStrategy = FieldStrategy.NEVER)
     private String configKey;
     private String name;
     private String remark;
 
+    @TableField(exist = false)
     private List<SystemConfigItem> items;
 }

+ 8 - 1
src/main/java/com/zhiqiyun/open/core/models/SystemConfigItem.java → src/main/java/com/zhiqiyun/open/core/models/settings/SystemConfigItem.java

@@ -1,5 +1,6 @@
-package com.zhiqiyun.open.core.models;
+package com.zhiqiyun.open.core.models.settings;
 
+import com.baomidou.mybatisplus.annotation.*;
 import com.zhiqiyun.open.core.enmus.ConfigItemType;
 import lombok.Data;
 
@@ -9,14 +10,20 @@ import java.io.Serializable;
  * @author jtoms
  */
 @Data
+@TableName("setting_system_config_item")
 public class SystemConfigItem implements Serializable {
     private static final long serialVersionUID = 2803996695489090243L;
+    @TableId(type = IdType.INPUT)
     private String id;
+    @TableField(updateStrategy = FieldStrategy.NEVER)
     private String configKey;
     private String itemName;
+    @TableField(updateStrategy = FieldStrategy.NEVER)
     private String itemKey;
+    @TableField(updateStrategy = FieldStrategy.NEVER)
     private ConfigItemType itemValueType;
     private String itemValue;
     private String inputRemark;
+    @TableField(updateStrategy = FieldStrategy.NEVER)
     private Integer sortValue;
 }

+ 55 - 0
src/main/java/com/zhiqiyun/open/core/service/SystemConfigService.java

@@ -0,0 +1,55 @@
+package com.zhiqiyun.open.core.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.zhiqiyun.open.core.models.settings.SystemConfig;
+import com.zhiqiyun.open.core.models.settings.SystemConfigItem;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public interface SystemConfigService extends IService<SystemConfig> {
+    /**
+     * 查询配置项
+     *
+     * @param configKey
+     * @return
+     */
+    List<SystemConfigItem> findAllItems(String configKey);
+
+    /**
+     * 保存配置
+     *
+     * @param config
+     * @param listItems
+     */
+    void updateConfig(SystemConfig config, List<SystemConfigItem> listItems);
+
+
+
+    /**
+     * 查询一个Boolean配置
+     *
+     * @param configKey
+     * @param itemKey
+     * @return
+     */
+    boolean getBoolValue(String configKey, String itemKey);
+
+    /**
+     * 查询数字配置
+     *
+     * @param configKey
+     * @param itemKey
+     * @return
+     */
+    BigDecimal getNumberValue(String configKey, String itemKey);
+
+    /**
+     * 查询字符配置
+     *
+     * @param configKey
+     * @param itemKey
+     * @return
+     */
+    String getStringValue(String configKey, String itemKey);
+}

+ 93 - 0
src/main/java/com/zhiqiyun/open/core/service/impl/SystemConfigServiceImpl.java

@@ -0,0 +1,93 @@
+package com.zhiqiyun.open.core.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.zhiqiyun.open.config.RedisKeys;
+import com.zhiqiyun.open.core.mapper.SystemConfigItemMapper;
+import com.zhiqiyun.open.core.mapper.SystemConfigMapper;
+import com.zhiqiyun.open.core.models.settings.SystemConfig;
+import com.zhiqiyun.open.core.models.settings.SystemConfigItem;
+import com.zhiqiyun.open.core.service.SystemConfigService;
+import com.zhiqiyun.open.exception.ServiceException;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Service
+public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements SystemConfigService {
+    @Autowired
+    private SystemConfigItemMapper systemConfigItemMapper;
+
+    @Resource
+    private StringRedisTemplate stringRedisTemplate;
+
+    @Override
+    public List<SystemConfigItem> findAllItems(String configKey) {
+        QueryWrapper<SystemConfigItem> queryWrapper = new QueryWrapper<>();
+        return this.systemConfigItemMapper.selectList(queryWrapper);
+    }
+
+    @Override
+    @Transactional(rollbackFor = ServiceException.class)
+    public void updateConfig(SystemConfig config, List<SystemConfigItem> listItems) {
+        try {
+            this.baseMapper.updateById(config);
+            for (SystemConfigItem item : listItems) {
+                String redisKey = String.format(RedisKeys.SYSTEM_CONFIG_KEY, item.getId());
+                this.stringRedisTemplate.delete(redisKey);
+                this.systemConfigItemMapper.updateById(item);
+            }
+        } catch (Exception e) {
+            throw new ServiceException(e);
+        }
+    }
+
+
+    @Override
+    public boolean getBoolValue(String configKey, String itemKey) {
+        String itemValue = this.getStringValue(configKey, itemKey);
+        try {
+            return Boolean.parseBoolean(itemValue);
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    @Override
+    public BigDecimal getNumberValue(String configKey, String itemKey) {
+        String itemValue = this.getStringValue(configKey, itemKey);
+        try {
+            return new BigDecimal(itemValue);
+        } catch (Exception e) {
+            return BigDecimal.ZERO;
+        }
+    }
+
+    @Override
+    public String getStringValue(String configKey, String itemKey) {
+        String id = DigestUtils.md5Hex(String.format("%s@%s", configKey, itemKey));
+        String redisKey = String.format(RedisKeys.SYSTEM_CONFIG_KEY, id);
+        String itemValue = this.stringRedisTemplate.opsForValue().get(redisKey);
+
+        if (StringUtils.isBlank(itemValue)) {
+
+            SystemConfigItem item = this.systemConfigItemMapper.selectById(id);
+            if (item == null) {
+                itemValue = "";
+            } else {
+                itemValue = item.getItemValue();
+            }
+            this.stringRedisTemplate.opsForValue().set(redisKey, itemValue, 30, TimeUnit.MINUTES);
+        }
+
+        return itemValue;
+    }
+}

+ 64 - 0
src/main/java/com/zhiqiyun/open/mvc/manager/controller/SystemConfigController.java

@@ -0,0 +1,64 @@
+package com.zhiqiyun.open.mvc.manager.controller;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.zhiqiyun.open.annotation.Permission;
+import com.zhiqiyun.open.core.models.settings.SystemConfig;
+import com.zhiqiyun.open.core.models.settings.SystemConfigItem;
+import com.zhiqiyun.open.core.service.SystemConfigService;
+import com.zhiqiyun.open.mvc.Result;
+import com.zhiqiyun.open.mvc.manager.params.QuerySystemConfigParam;
+import com.zhiqiyun.open.mvc.manager.params.SaveSystemConfigParam;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.validation.Valid;
+import java.util.ArrayList;
+import java.util.List;
+
+@RestController
+@RequestMapping("/setting/systemConfig")
+public class SystemConfigController {
+
+    @Autowired
+    private SystemConfigService systemConfigService;
+
+    @Permission(value = "system.config.find", tags = "系统参数查询")
+    @PostMapping("/findPage")
+    public Result findSettingPage(@RequestBody QuerySystemConfigParam params) {
+        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("config_key", params.getConfigKey());
+        Page<SystemConfig> resultData = this.systemConfigService.page(params.getPage());
+        for (SystemConfig config : resultData.getRecords()) {
+            List<SystemConfigItem> items = this.systemConfigService.findAllItems(config.getConfigKey());
+            config.setItems(items);
+        }
+        return Result.instance(Result.Code.SUCCESS).setData(resultData);
+    }
+
+
+    @PostMapping("/updateById")
+    @Permission(value = "system.config.edit", tags = "修改系统参数")
+    public Result updateSettingById(String id, @Valid @RequestBody SaveSystemConfigParam param) throws Exception {
+        if (StringUtils.isBlank(id)) {
+            return Result.instance("数据异常,请刷新页面后再试");
+        }
+        SystemConfig config = new SystemConfig();
+        config.setId(id);
+        config.setName(param.getName());
+        config.setRemark(param.getRemark());
+        List<SystemConfigItem> listData = new ArrayList<>();
+        for (SaveSystemConfigParam.SaveSystemConfigItemParam itemParam : param.getItems()) {
+            SystemConfigItem configItem = new SystemConfigItem();
+            configItem.setId(itemParam.getId());
+            configItem.setItemValue(itemParam.getItemValue());
+            listData.add(configItem);
+        }
+        this.systemConfigService.updateConfig(config, listData);
+        return Result.instance(Result.Code.MESSAGE_SUCCESS);
+    }
+}

+ 14 - 0
src/main/java/com/zhiqiyun/open/mvc/manager/params/QuerySystemConfigParam.java

@@ -0,0 +1,14 @@
+package com.zhiqiyun.open.mvc.manager.params;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * @author jtoms
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class QuerySystemConfigParam extends QueryPageParams {
+
+    private String configKey;
+}

+ 22 - 0
src/main/java/com/zhiqiyun/open/mvc/manager/params/SaveSystemConfigParam.java

@@ -0,0 +1,22 @@
+package com.zhiqiyun.open.mvc.manager.params;
+
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * @author jtoms
+ */
+@Data
+public class SaveSystemConfigParam {
+    private String name;
+    private String remark;
+    private List<SaveSystemConfigItemParam> items;
+
+    @Data
+    public static class SaveSystemConfigItemParam {
+        private String id;
+        private String itemValue;
+    }
+
+}

+ 40 - 19
src/main/java/com/zhiqiyun/open/router/apis/Oauth2Api.java

@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.dliyun.oap.framework.annotation.ServiceMethod;
 import com.dliyun.oap.framework.annotation.ServiceMethodBean;
 import com.dliyun.oap.framework.response.OapResponse;
+import com.zhiqiyun.open.core.service.SystemConfigService;
 import com.zhiqiyun.open.router.request.Oauth2LoginRequest;
 import com.zhiqiyun.open.router.request.Oauth2RefreshTokenRequest;
 import com.zhiqiyun.open.router.request.Oauth2UserInfoRequest;
@@ -26,79 +27,99 @@ public class Oauth2Api {
     @Autowired
     private OkHttpClient okHttpClient;
 
+    @Autowired
+    private SystemConfigService systemConfigService;
+
     @ServiceMethod(method = "oauth2.login", title = "用户登录")
     public OapResponse login(Oauth2LoginRequest request) throws IOException {
 
+        String hostAddress = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "hostAddress");
+        String tenantId = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "tenantId");
+        String clientSecret = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "clientSecret");
+
         Map<String, String> paramValues = new HashMap<>();
         paramValues.put("grant_type", "password");
         paramValues.put("username", request.getUserName());
         paramValues.put("password", DigestUtils.md5Hex(request.getPassword()));
         paramValues.put("scope", "all");
-        paramValues.put("tenantId", "222712");
+        paramValues.put("tenantId", tenantId);
         FormBody.Builder formBuilder = new FormBody.Builder();
         paramValues.forEach(formBuilder::add);
 
 
         Request.Builder builder = new Request.Builder();
-        builder.url("http://apis-dev.smartcity.123cx.com/blade-auth/oauth/token");
-        builder.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
+        builder.url(String.format("%s/blade-auth/oauth/token", hostAddress));
+        builder.header("Authorization", "Basic " + clientSecret);
         builder.header("Content-Type", "application/x-www-form-urlencoded");
-        builder.header("Tenant-Id", "222712");
+        builder.header("Tenant-Id", tenantId);
         builder.post(formBuilder.build());
 
         Response resp = this.okHttpClient.newCall(builder.build()).execute();
         if (resp.isSuccessful()) {
             String result = Objects.requireNonNull(resp.body()).string();
             JSONObject jsonObject = JSON.parseObject(result);
-            if (jsonObject.containsKey("error")) {
-                return OapResponse.fail(jsonObject.getString("jsonObject"), jsonObject.getString("error_description"));
-            }
             return OapResponse.success().setBody(jsonObject);
         } else {
-            return OapResponse.fail("NETWORK_ERROR", "网络异常" + resp.message());
+            try {
+                String result = Objects.requireNonNull(resp.body()).string();
+                JSONObject jsonObject = JSON.parseObject(result);
+                return OapResponse.fail(jsonObject.getString("error"), jsonObject.getString("error_description"));
+            } catch (Exception e) {
+                return OapResponse.fail("NETWORK_ERROR", "网络异常" + resp.message());
+            }
         }
     }
 
     @ServiceMethod(method = "oauth2.refresh.token", title = "刷新Token")
     public OapResponse refreshToken(Oauth2RefreshTokenRequest request) throws IOException {
 
+        String hostAddress = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "hostAddress");
+        String tenantId = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "tenantId");
+        String clientSecret = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "clientSecret");
+
+        FormBody.Builder formBuilder = new FormBody.Builder();
         Map<String, String> paramValues = new HashMap<>();
         paramValues.put("grant_type", "refresh_token");
         paramValues.put("scope", "all");
         paramValues.put("refresh_token", request.getRefreshToken());
-        FormBody.Builder formBuilder = new FormBody.Builder();
         paramValues.forEach(formBuilder::add);
 
 
         Request.Builder builder = new Request.Builder();
-        builder.url("http://apis-dev.smartcity.123cx.com/blade-auth/oauth/token");
-        builder.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
+        builder.url(String.format("%s/blade-auth/oauth/token", hostAddress));
+        builder.header("Authorization", "Basic " + clientSecret);
         builder.header("Content-Type", "application/x-www-form-urlencoded");
-        builder.header("Tenant-Id", "222712");
+        builder.header("Tenant-Id", tenantId);
         builder.post(formBuilder.build());
 
         Response resp = this.okHttpClient.newCall(builder.build()).execute();
         if (resp.isSuccessful()) {
             String result = Objects.requireNonNull(resp.body()).string();
             JSONObject jsonObject = JSON.parseObject(result);
-            if (jsonObject.containsKey("error")) {
-                return OapResponse.fail(jsonObject.getString("jsonObject"), jsonObject.getString("error_description"));
-            }
             return OapResponse.success().setBody(jsonObject);
         } else {
-            return OapResponse.fail("NETWORK_ERROR", "网络异常" + resp.message());
+            try {
+                String result = Objects.requireNonNull(resp.body()).string();
+                JSONObject jsonObject = JSON.parseObject(result);
+                return OapResponse.fail(jsonObject.getString("error"), jsonObject.getString("error_description"));
+            } catch (Exception e) {
+                return OapResponse.fail("NETWORK_ERROR", "网络异常" + resp.message());
+            }
         }
     }
 
     @ServiceMethod(method = "oauth2.user.info", title = "获取用户信息")
     public OapResponse userInfo(Oauth2UserInfoRequest request) throws IOException {
 
+
+        String hostAddress = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "hostAddress");
+        String tenantId = this.systemConfigService.getStringValue("OAUTH2_API_CONFIG", "tenantId");
+
         Request.Builder builder = new Request.Builder();
-        builder.url("http://apis-dev.smartcity.123cx.com/blade-auth/oauth/user-info");
+        builder.url(String.format("%s/blade-auth/oauth/user-info", hostAddress));
         builder.header("Authorization", "bearer " + request.getAccessToken());
         builder.header("Content-Type", "application/x-www-form-urlencoded");
-        builder.header("Tenant-Id", "222712");
-//        builder.post(RequestBody.create(null));
+        builder.header("Tenant-Id", tenantId);
 
         Response resp = this.okHttpClient.newCall(builder.build()).execute();
         if (resp.isSuccessful()) {

+ 39 - 0
src/main/resources/db/migration/V1.0.2__system_config.sql

@@ -0,0 +1,39 @@
+DROP TABLE IF EXISTS `setting_system_config_item`;
+CREATE TABLE `setting_system_config_item`
+(
+    `id`              VARCHAR(32)  NOT NULL,
+    `config_key`      VARCHAR(50)  NOT NULL COMMENT '参数值Key',
+    `item_name`       VARCHAR(500) NOT NULL COMMENT '参数名字',
+    `item_key`        VARCHAR(50)  NOT NULL COMMENT '参数值Key',
+    `item_value_type` INT(2) NOT NULL COMMENT '参数值类型',
+    `item_value`      VARCHAR(500) NOT NULL COMMENT '参数值',
+    `input_remark`    VARCHAR(200) NOT NULL COMMENT '填写说明',
+    `sort_value`      INT(11) NOT NULL DEFAULT '0' COMMENT '排序值',
+    PRIMARY KEY (`id`),
+    INDEX             `config_key_index` (`config_key`),
+    INDEX             `item_key_index` (`item_key`)
+) COMMENT='系统参数值' ENGINE=InnoDB;
+
+DROP TABLE IF EXISTS `setting_system_config`;
+CREATE TABLE `setting_system_config`
+(
+    `id`         VARCHAR(32)  NOT NULL,
+    `config_key` VARCHAR(50)  NOT NULL COMMENT '参数Key',
+    `name`       VARCHAR(32)  NOT NULL COMMENT '参数名称',
+    `remark`     VARCHAR(255) NOT NULL COMMENT '参数说明',
+    PRIMARY KEY (`id`),
+    INDEX        `config_key_index` (`config_key`)
+) COMMENT='系统参数设置' ENGINE=InnoDB;
+
+
+REPLACE
+INTO `setting_system_config` (`id`, `config_key`, `name`, `remark`)
+VALUES (md5('OAUTH2_API_CONFIG'), 'OAUTH2_API_CONFIG', 'Oauth2认证', '第三方Oauth2认证配置');
+
+
+REPLACE
+INTO `setting_system_config_item` (`id`, `config_key`, `item_name`, `item_key`, `item_value_type`, `item_value`, `input_remark`, `sort_value`)
+VALUES (md5('OAUTH2_API_CONFIG@hostAddress'), 'OAUTH2_API_CONFIG', '域名地址', 'hostAddress', 1, 'http://apis-dev.smartcity.123cx.com/blade-auth', '', 1),
+       (md5('OAUTH2_API_CONFIG@tenantId'), 'OAUTH2_API_CONFIG', '租户ID', 'tenantId', 1, '222712', '', 2),
+       (md5('OAUTH2_API_CONFIG@clientSecret'), 'OAUTH2_API_CONFIG', '租户密钥', 'clientSecret', 1, 'c2FiZXI6c2FiZXJfc2VjcmV0', '', 3);
+