Explorar o código

feat:用户登录后封装数据源信息到token,调用不同的引擎后台通过token解析当前登录用户的数据源信息。生成代码优化启用swagger

韩帛霖 hai 1 ano
pai
achega
77a2c60ea4

+ 12 - 8
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/DataSourceController.java

@@ -5,6 +5,7 @@ import com.alibaba.fastjson2.JSONObject;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.AjaxResult;
 import com.ruoyi.common.core.domain.entity.DataSource;
+import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.system.service.IDataSourceService;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.*;
@@ -50,26 +51,29 @@ public class DataSourceController extends BaseController {
      * 新增数据源
      */
     @PostMapping("/save")
-    public AjaxResult addDataSource(@RequestBody Map<String,Object> map){
+    public AjaxResult addDataSource(@RequestBody Map<String, Object> map) {
 
         DataSource dataSource = JSON.parseObject(JSON.toJSONString(map.get("dataSource")), DataSource.class);
-        Integer tenantId = (Integer)map.get("tenantId");
-        if(dataSourceService.selectDatabaseExist(dataSource)>0){
+        Integer tenantId = (Integer) map.get("tenantId");
+        if (dataSourceService.selectDatabaseExist(dataSource) > 0) {
             return AjaxResult.error("数据库已存在");
         }
         //return toAjax(dataSourceService.insertDataSource(dataSource,tenantId.longValue()));
-        return dataSourceService.insertDataSource(dataSource,tenantId.longValue());
+        return dataSourceService.insertDataSource(dataSource, tenantId.longValue());
     }
 
     /**
      * 调用(数据引擎、流程引擎、表单引擎)切换数据源接口
      */
     @PostMapping("/changeDatasource")
-    public AjaxResult changeDatasource(@RequestBody DataSource dataSource){
+    public AjaxResult changeDatasource() {
+        // admin 没有数据源
+        if (SecurityUtils.isAdmin(getUserId())) return AjaxResult.success();
+        DataSource dataSource = SecurityUtils.getDatasourceInfo();
         //调用数据引擎服务切换数据源接口
-//        restTemplate.postForEntity(DATA_ENGINE_IP, dataSource, DataSource.class);
-//        //调用表单引擎服务切换数据源接口
-//        restTemplate.postForEntity(DRAG_FORM_IP, dataSource, DataSource.class);
+        restTemplate.postForEntity(DATA_ENGINE_IP, dataSource, DataSource.class);
+        //调用表单引擎服务切换数据源接口
+        restTemplate.postForEntity(DRAG_FORM_IP, dataSource, DataSource.class);
         //调用流程引擎服务切换数据源接口
         restTemplate.postForEntity(PROCESS_ENGINE_IP, dataSource, DataSource.class);
         return AjaxResult.success();

+ 37 - 53
ruoyi-common/src/main/java/com/ruoyi/common/utils/SecurityUtils.java

@@ -1,5 +1,6 @@
 package com.ruoyi.common.utils;
 
+import com.ruoyi.common.core.domain.entity.DataSource;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@@ -9,22 +10,17 @@ import com.ruoyi.common.exception.ServiceException;
 
 /**
  * 安全服务工具类
- * 
+ *
  * @author ruoyi
  */
-public class SecurityUtils
-{
+public class SecurityUtils {
     /**
      * 用户ID
      **/
-    public static Long getUserId()
-    {
-        try
-        {
+    public static Long getUserId() {
+        try {
             return getLoginUser().getUserId();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -32,51 +28,37 @@ public class SecurityUtils
     /**
      * 获取部门ID
      **/
-    public static Long getDeptId()
-    {
-        try
-        {
+    public static Long getDeptId() {
+        try {
             return getLoginUser().getDeptId();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
         }
     }
-    
+
     /**
      * 获取用户账户
      **/
-    public static String getUsername()
-    {
-        try
-        {
+    public static String getUsername() {
+        try {
             return getLoginUser().getUsername();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
         }
     }
 
     public static String getUserType() {
-        try
-        {
+        try {
             return getLoginUser().getUserType();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
         }
     }
 
     public static Long getTenantId() {
-        try
-        {
+        try {
             return getLoginUser().getTenantId();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取租户ID异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -84,14 +66,10 @@ public class SecurityUtils
     /**
      * 获取用户
      **/
-    public static LoginUser getLoginUser()
-    {
-        try
-        {
+    public static LoginUser getLoginUser() {
+        try {
             return (LoginUser) getAuthentication().getPrincipal();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -99,8 +77,7 @@ public class SecurityUtils
     /**
      * 获取Authentication
      */
-    public static Authentication getAuthentication()
-    {
+    public static Authentication getAuthentication() {
         return SecurityContextHolder.getContext().getAuthentication();
     }
 
@@ -110,8 +87,7 @@ public class SecurityUtils
      * @param password 密码
      * @return 加密字符串
      */
-    public static String encryptPassword(String password)
-    {
+    public static String encryptPassword(String password) {
         BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         return passwordEncoder.encode(password);
     }
@@ -119,24 +95,22 @@ public class SecurityUtils
     /**
      * 判断密码是否相同
      *
-     * @param rawPassword 真实密码
+     * @param rawPassword     真实密码
      * @param encodedPassword 加密后字符
      * @return 结果
      */
-    public static boolean matchesPassword(String rawPassword, String encodedPassword)
-    {
+    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
         BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         return passwordEncoder.matches(rawPassword, encodedPassword);
     }
 
     /**
      * 是否为管理员
-     * 
+     *
      * @param userId 用户ID
      * @return 结果
      */
-    public static boolean isAdmin(Long userId)
-    {
+    public static boolean isAdmin(Long userId) {
         return userId != null && 1L == userId;
     }
 
@@ -144,7 +118,7 @@ public class SecurityUtils
         return tenantId != null && "01".equals(userType);
     }
 
-    public static  boolean isLoginUserTenantAdmin() {
+    public static boolean isLoginUserTenantAdmin() {
         LoginUser loginUser = SecurityUtils.getLoginUser();
         if (loginUser == null) {
             return false;
@@ -152,4 +126,14 @@ public class SecurityUtils
             return loginUser.isTenantAdmin();
         }
     }
+
+    /**
+     * 获取当前登录用户的数据源信息
+     *
+     * @return
+     */
+    public static DataSource getDatasourceInfo() {
+        LoginUser loginUser = SecurityUtils.getLoginUser();
+        return loginUser.getUser().getTenant().getDataSource();
+    }
 }

+ 24 - 15
ruoyi-generator/src/main/resources/vm/java/controller.java.vm

@@ -2,6 +2,8 @@ package ${packageName}.controller;
 
 import java.util.List;
 import javax.servlet.http.HttpServletResponse;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -26,36 +28,38 @@ import com.ruoyi.common.core.page.TableDataInfo;
 
 /**
  * ${functionName}Controller
- * 
+ *
  * @author ${author}
  * @date ${datetime}
  */
 @RestController
 @RequestMapping("/${moduleName}/${businessName}")
+@Api(value = "/${moduleName}/${businessName}", description = "${functionName}-接口")
 public class ${ClassName}Controller extends BaseController
 {
     @Autowired
     private I${ClassName}Service ${className}Service;
 
-    /**
-     * 查询${functionName}列表
-     */
-    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')")
-    @GetMapping("/list")
-#if($table.crud || $table.sub)
+/**
+ * 查询${functionName}列表
+ */
+@PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')")
+@GetMapping("/list")
+@ApiOperation(value = "查询${functionName}列表")
+    #if($table.crud || $table.sub)
     public TableDataInfo list(${ClassName} ${className})
     {
         startPage();
         List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
         return getDataTable(list);
     }
-#elseif($table.tree)
-    public AjaxResult list(${ClassName} ${className})
-    {
-        List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
-        return success(list);
-    }
-#end
+    #elseif($table.tree)
+        public AjaxResult list(${ClassName} ${className})
+        {
+            List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
+            return success(list);
+        }
+    #end
 
     /**
      * 导出${functionName}列表
@@ -63,6 +67,7 @@ public class ${ClassName}Controller extends BaseController
     @PreAuthorize("@ss.hasPermi('${permissionPrefix}:export')")
     @Log(title = "${functionName}", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
+    @ApiOperation(value = "导出${functionName}列表")
     public void export(HttpServletResponse response, ${ClassName} ${className})
     {
         List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
@@ -75,6 +80,7 @@ public class ${ClassName}Controller extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('${permissionPrefix}:query')")
     @GetMapping(value = "/{${pkColumn.javaField}}")
+    @ApiOperation(value = "获取${functionName}详细信息")
     public AjaxResult getInfo(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField})
     {
         return success(${className}Service.select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField}));
@@ -86,6 +92,7 @@ public class ${ClassName}Controller extends BaseController
     @PreAuthorize("@ss.hasPermi('${permissionPrefix}:add')")
     @Log(title = "${functionName}", businessType = BusinessType.INSERT)
     @PostMapping
+    @ApiOperation(value = "新增${functionName}")
     public AjaxResult add(@RequestBody ${ClassName} ${className})
     {
         return toAjax(${className}Service.insert${ClassName}(${className}));
@@ -97,6 +104,7 @@ public class ${ClassName}Controller extends BaseController
     @PreAuthorize("@ss.hasPermi('${permissionPrefix}:edit')")
     @Log(title = "${functionName}", businessType = BusinessType.UPDATE)
     @PutMapping
+    @ApiOperation(value = "修改${functionName}")
     public AjaxResult edit(@RequestBody ${ClassName} ${className})
     {
         return toAjax(${className}Service.update${ClassName}(${className}));
@@ -107,7 +115,8 @@ public class ${ClassName}Controller extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('${permissionPrefix}:remove')")
     @Log(title = "${functionName}", businessType = BusinessType.DELETE)
-	@DeleteMapping("/{${pkColumn.javaField}s}")
+    @DeleteMapping("/{${pkColumn.javaField}s}")
+    @ApiOperation(value = "删除${functionName}")
     public AjaxResult remove(@PathVariable ${pkColumn.javaType}[] ${pkColumn.javaField}s)
     {
         return toAjax(${className}Service.delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaField}s));

+ 5 - 1
ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml

@@ -76,6 +76,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 		<id     property="id"    column="id"     />
 		<result property="databaseType"  column="database_type"   />
 		<result property="databaseName"  column="database_name"   />
+		<result property="databaseIp"  column="database_ip"   />
+		<result property="username"  column="dsusername"   />
+		<result property="password"  column="dspassword"   />
+		<result property="portNumber"  column="port_number"   />
 	</resultMap>
 	
     <resultMap id="RoleResult" type="SysRole">
@@ -92,7 +96,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.status as dept_status,
 		te.tenant_id, te.tenant_name, te.tenant_code, te.owner,
         r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status,
-			   ds.id,ds.database_type,ds.database_name
+			   ds.id,ds.database_type,ds.database_name,ds.username as dsusername, ds.password as dspassword,ds.port_number,ds.database_ip
         from sys_user u
 		    left join sys_dept d on u.dept_id = d.dept_id
 		    left join sys_tenant te on u.tenant_id = te.tenant_id

+ 44 - 24
ruoyi-ui/src/views/tool/gen/index.vue

@@ -41,10 +41,12 @@
           icon="el-icon-search"
           size="mini"
           @click="handleQuery"
-          >搜索</el-button
+        >搜索
+        </el-button
         >
         <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
-          >重置</el-button
+        >重置
+        </el-button
         >
       </el-form-item>
     </el-form>
@@ -58,7 +60,8 @@
           size="mini"
           @click="handleGenTable"
           v-hasPermi="['tool:gen:code']"
-          >生成</el-button
+        >生成
+        </el-button
         >
       </el-col>
       <el-col :span="1.5">
@@ -69,7 +72,8 @@
           size="mini"
           @click="openImportTable"
           v-hasPermi="['tool:gen:import']"
-          >导入</el-button
+        >导入
+        </el-button
         >
       </el-col>
       <!-- <el-col :span="1.5">
@@ -92,7 +96,8 @@
           :disabled="multiple"
           @click="handleDelete"
           v-hasPermi="['tool:gen:remove']"
-          >删除</el-button
+        >删除
+        </el-button
         >
       </el-col>
       <right-toolbar
@@ -114,8 +119,8 @@
       <el-table-column label="序号" type="index" width="50" align="center">
         <template slot-scope="scope">
           <span>{{
-            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
-          }}</span>
+              (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
+            }}</span>
         </template>
       </el-table-column>
       <el-table-column
@@ -163,53 +168,64 @@
             </el-button>
             <el-dropdown-menu slot="dropdown">
               <el-dropdown-item
-                ><el-button
+              >
+                <el-button
                   type="text"
                   size="small"
                   icon="el-icon-view"
                   @click="handlePreview(scope.row)"
                   v-hasPermi="['tool:gen:preview']"
-                  >预览</el-button
-                ></el-dropdown-item
+                >预览
+                </el-button
+                >
+              </el-dropdown-item
               >
               <el-dropdown-item
-                ><el-button
+              >
+                <el-button
                   type="text"
                   size="small"
                   icon="el-icon-edit"
                   @click="handleEditTable(scope.row)"
                   v-hasPermi="['tool:gen:edit']"
-                  >编辑</el-button
+                >编辑
+                </el-button
                 >
               </el-dropdown-item>
               <el-dropdown-item
-                ><el-button
+              >
+                <el-button
                   type="text"
                   size="small"
                   icon="el-icon-delete"
                   @click="handleDelete(scope.row)"
                   v-hasPermi="['tool:gen:remove']"
-                  >删除</el-button
+                >删除
+                </el-button
                 >
               </el-dropdown-item>
               <el-dropdown-item
-                ><el-button
+              >
+                <el-button
                   type="text"
                   size="small"
                   icon="el-icon-refresh"
                   @click="handleSynchDb(scope.row)"
                   v-hasPermi="['tool:gen:edit']"
-                  >同步</el-button
+                >同步
+                </el-button
                 >
               </el-dropdown-item>
               <el-dropdown-item
-                ><el-button
+              >
+                <el-button
                   type="text"
                   size="small"
                   icon="el-icon-download"
                   @click="handleGenTable(scope.row)"
                   v-hasPermi="['tool:gen:code']"
-                  >生成代码</el-button
+                >生成代码
+                </el-button
                 >
               </el-dropdown-item>
             </el-dropdown-menu>
@@ -282,13 +298,14 @@
             v-clipboard:copy="value"
             v-clipboard:success="clipboardSuccess"
             style="float: right"
-            >复制</el-link
+          >复制
+          </el-link
           >
           <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
         </el-tab-pane>
       </el-tabs>
     </el-dialog>
-    <import-table ref="import" @ok="handleQuery" />
+    <import-table ref="import" @ok="handleQuery"/>
   </div>
 </template>
 
@@ -303,6 +320,7 @@ import {
 import importTable from "./importTable";
 import hljs from "highlight.js/lib/core";
 import "highlight.js/styles/github-gist.css";
+
 hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
 hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
 hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
@@ -315,7 +333,7 @@ hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
 
 export default {
   name: "Gen",
-  components: { importTable },
+  components: {importTable},
   data() {
     return {
       // 遮罩层
@@ -411,7 +429,8 @@ export default {
         .then(() => {
           this.$modal.msgSuccess("同步成功");
         })
-        .catch(() => {});
+        .catch(() => {
+        });
     },
     /** 打开导入表弹窗 */
     openImportTable() {
@@ -456,7 +475,7 @@ export default {
     handleEditTable(row) {
       const tableId = row.tableId || this.ids[0];
       const tableName = row.tableName || this.tableNames[0];
-      const params = { pageNum: this.queryParams.pageNum };
+      const params = {pageNum: this.queryParams.pageNum};
       this.$tab.openPage(
         "修改[" + tableName + "]生成配置",
         "/tool/gen-edit/index/" + tableId,
@@ -475,7 +494,8 @@ export default {
           this.getList();
           this.$modal.msgSuccess("删除成功");
         })
-        .catch(() => {});
+        .catch(() => {
+        });
     },
   },
 };