Unverified Commit e5bdefe6 authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Feature-1641][admin,client] Add Flink row level permissions (#1831)

parent a45fb097
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.controller;
import org.dinky.common.result.ProTableResult;
import org.dinky.common.result.Result;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.service.RoleSelectPermissionsService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/api/roleSelectPermissions")
public class RoleSelectPermissionsController {
@Autowired private RoleSelectPermissionsService roleSelectPermissionsService;
/** create or update roleSelectPermissions */
@PutMapping
public Result saveOrUpdateRole(@RequestBody RoleSelectPermissions roleSelectPermissions) {
if (roleSelectPermissionsService.saveOrUpdate(roleSelectPermissions)) {
return Result.succeed("新增成功");
} else {
return Result.failed("新增失败");
}
}
/** delete roleSelectPermissions by id */
@DeleteMapping
public Result deleteMul(@RequestBody JsonNode para) {
if (para.size() > 0) {
List<Integer> error = new ArrayList<>();
for (final JsonNode item : para) {
Integer id = item.asInt();
if (!roleSelectPermissionsService.removeById(id)) {
error.add(id);
}
}
if (error.size() == 0) {
return Result.succeed("删除成功");
} else {
return Result.succeed(
"删除部分成功,但" + error.toString() + "删除失败,共" + error.size() + "次失败。");
}
} else {
return Result.failed("请选择要删除的记录");
}
}
/** query roleSelectPermissions list */
@PostMapping
public ProTableResult<RoleSelectPermissions> listRoles(@RequestBody JsonNode para) {
return roleSelectPermissionsService.selectForProTable(para);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.mapper;
import org.dinky.db.mapper.SuperMapper;
import org.dinky.model.RoleSelectPermissions;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** role select permissions mapper interface */
@Mapper
public interface RoleSelectPermissionsMapper extends SuperMapper<RoleSelectPermissions> {
/**
* delete user role select permissions by role id
*
* @param roleIds role id
* @return delete status
*/
int deleteByRoleIds(@Param("roleIds") List<Integer> roleIds);
/**
* select user role data permissions by role ids
*
* @param roleIds role ids
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(
@Param("roleIds") List<Integer> roleIds);
}
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.mapper; package org.dinky.mapper;
import org.dinky.db.mapper.SuperMapper; import org.dinky.db.mapper.SuperMapper;
import org.dinky.model.Role;
import org.dinky.model.UserRole; import org.dinky.model.UserRole;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
...@@ -52,4 +53,12 @@ public interface UserRoleMapper extends SuperMapper<UserRole> { ...@@ -52,4 +53,12 @@ public interface UserRoleMapper extends SuperMapper<UserRole> {
* @return delete status * @return delete status
*/ */
int deleteByRoleIds(@Param("roleIds") List<Integer> roleIds); int deleteByRoleIds(@Param("roleIds") List<Integer> roleIds);
/**
* get role list by user id
*
* @param userId userId
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
} }
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("dinky_role_select_permissions")
public class RoleSelectPermissions implements Serializable {
private static final long serialVersionUID = 8676666963206334660L;
/** id */
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** role id */
private Integer roleId;
/** table_name */
private String tableName;
/** expression */
private String expression;
/** create time */
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/** update time */
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/** role code */
@TableField(exist = false)
private String roleCode;
/** role name */
@TableField(exist = false)
private String roleName;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service;
import org.dinky.db.service.ISuperService;
import org.dinky.model.RoleSelectPermissions;
import java.util.List;
public interface RoleSelectPermissionsService extends ISuperService<RoleSelectPermissions> {
/**
* delete user role select permissions by role id
*
* @param roleIds role id
* @return delete status
*/
boolean deleteByRoleIds(List<Integer> roleIds);
/**
* select user role data permissions by role id
*
* @param roleId role id
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listAllByRoleId(Integer roleId);
/**
* select user role data permissions by role ids
*
* @param roleIds role ids
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(List<Integer> roleIds);
}
...@@ -24,6 +24,8 @@ import org.dinky.common.result.Result; ...@@ -24,6 +24,8 @@ import org.dinky.common.result.Result;
import org.dinky.db.service.ISuperService; import org.dinky.db.service.ISuperService;
import org.dinky.model.Role; import org.dinky.model.Role;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
public interface RoleService extends ISuperService<Role> { public interface RoleService extends ISuperService<Role> {
...@@ -66,4 +68,12 @@ public interface RoleService extends ISuperService<Role> { ...@@ -66,4 +68,12 @@ public interface RoleService extends ISuperService<Role> {
* @return {@link Result} of {@link Void} * @return {@link Result} of {@link Void}
*/ */
Result<Void> deleteRoleById(Integer id); Result<Void> deleteRoleById(Integer id);
/**
* get role list by user id
*
* @param userId user id
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
} }
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.service; package org.dinky.service;
import org.dinky.db.service.ISuperService; import org.dinky.db.service.ISuperService;
import org.dinky.model.Role;
import org.dinky.model.UserRole; import org.dinky.model.UserRole;
import java.util.List; import java.util.List;
...@@ -57,4 +58,12 @@ public interface UserRoleService extends ISuperService<UserRole> { ...@@ -57,4 +58,12 @@ public interface UserRoleService extends ISuperService<UserRole> {
* @return * @return
*/ */
boolean deleteByRoleIds(List<Integer> roleIds); boolean deleteByRoleIds(List<Integer> roleIds);
/**
* query roles by user id
*
* @param userId user id
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
} }
...@@ -24,10 +24,14 @@ import org.dinky.db.service.ISuperService; ...@@ -24,10 +24,14 @@ import org.dinky.db.service.ISuperService;
import org.dinky.dto.LoginDTO; import org.dinky.dto.LoginDTO;
import org.dinky.dto.ModifyPasswordDTO; import org.dinky.dto.ModifyPasswordDTO;
import org.dinky.dto.UserDTO; import org.dinky.dto.UserDTO;
import org.dinky.model.Role;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Tenant; import org.dinky.model.Tenant;
import org.dinky.model.User; import org.dinky.model.User;
import org.dinky.params.AssignRoleParams; import org.dinky.params.AssignRoleParams;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
/** /**
...@@ -134,4 +138,18 @@ public interface UserService extends ISuperService<User> { ...@@ -134,4 +138,18 @@ public interface UserService extends ISuperService<User> {
* @return {@link Boolean} * @return {@link Boolean}
*/ */
Boolean checkAdmin(Integer id); Boolean checkAdmin(Integer id);
/**
* get role by current user
*
* @return role list
*/
List<Role> getCurrentRole();
/**
* get role select permissions by current user
*
* @return role select permissions list
*/
List<RoleSelectPermissions> getCurrentRoleSelectPermissions();
} }
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.mapper.RoleSelectPermissionsMapper;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.service.RoleSelectPermissionsService;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@Service
public class RoleSelectPermissionsServiceImpl
extends SuperServiceImpl<RoleSelectPermissionsMapper, RoleSelectPermissions>
implements RoleSelectPermissionsService {
@Override
public boolean deleteByRoleIds(List<Integer> roleIds) {
return baseMapper.deleteByRoleIds(roleIds) > 0;
}
@Override
public List<RoleSelectPermissions> listAllByRoleId(Integer roleId) {
return baseMapper.selectList(
new QueryWrapper<RoleSelectPermissions>().eq("role_id", roleId));
}
@Override
public List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(List<Integer> roleIds) {
return baseMapper.listRoleSelectPermissionsByRoleIds(roleIds);
}
}
...@@ -220,4 +220,9 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen ...@@ -220,4 +220,9 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen
return roleProTableResult; return roleProTableResult;
} }
@Override
public List<Role> getRoleByUserId(Integer userId) {
return userRoleService.getRoleByUserId(userId);
}
} }
...@@ -22,6 +22,7 @@ package org.dinky.service.impl; ...@@ -22,6 +22,7 @@ package org.dinky.service.impl;
import org.dinky.api.FlinkAPI; import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect; import org.dinky.config.Dialect;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.dto.AbstractStatementDTO; import org.dinky.dto.AbstractStatementDTO;
import org.dinky.dto.SqlDTO; import org.dinky.dto.SqlDTO;
import org.dinky.dto.StudioCADTO; import org.dinky.dto.StudioCADTO;
...@@ -41,6 +42,7 @@ import org.dinky.model.Catalog; ...@@ -41,6 +42,7 @@ import org.dinky.model.Catalog;
import org.dinky.model.Cluster; import org.dinky.model.Cluster;
import org.dinky.model.DataBase; import org.dinky.model.DataBase;
import org.dinky.model.FlinkColumn; import org.dinky.model.FlinkColumn;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Savepoints; import org.dinky.model.Savepoints;
import org.dinky.model.Schema; import org.dinky.model.Schema;
import org.dinky.model.Table; import org.dinky.model.Table;
...@@ -59,6 +61,7 @@ import org.dinky.service.FragmentVariableService; ...@@ -59,6 +61,7 @@ import org.dinky.service.FragmentVariableService;
import org.dinky.service.SavepointsService; import org.dinky.service.SavepointsService;
import org.dinky.service.StudioService; import org.dinky.service.StudioService;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.service.UserService;
import org.dinky.sql.FlinkQuery; import org.dinky.sql.FlinkQuery;
import org.dinky.utils.RunTimeUtil; import org.dinky.utils.RunTimeUtil;
...@@ -66,6 +69,7 @@ import java.util.ArrayList; ...@@ -66,6 +69,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -79,12 +83,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -79,12 +83,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
/** /** StudioServiceImpl */
* StudioServiceImpl
*
* @author wenmo
* @since 2021/5/30 11:08
*/
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class StudioServiceImpl implements StudioService { public class StudioServiceImpl implements StudioService {
...@@ -97,6 +96,7 @@ public class StudioServiceImpl implements StudioService { ...@@ -97,6 +96,7 @@ public class StudioServiceImpl implements StudioService {
private final DataBaseService dataBaseService; private final DataBaseService dataBaseService;
private final TaskService taskService; private final TaskService taskService;
private final FragmentVariableService fragmentVariableService; private final FragmentVariableService fragmentVariableService;
private final UserService userService;
private void addFlinkSQLEnv(AbstractStatementDTO statementDTO) { private void addFlinkSQLEnv(AbstractStatementDTO statementDTO) {
ProcessEntity process = ProcessContextHolder.getProcess(); ProcessEntity process = ProcessContextHolder.getProcess();
...@@ -132,6 +132,23 @@ public class StudioServiceImpl implements StudioService { ...@@ -132,6 +132,23 @@ public class StudioServiceImpl implements StudioService {
process.info("No FlinkSQLEnv are loaded."); process.info("No FlinkSQLEnv are loaded.");
} }
} }
process.info("Initializing data permissions...");
List<RoleSelectPermissions> currentRoleSelectPermissions =
userService.getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
ConcurrentHashMap<String, String> permission = new ConcurrentHashMap<>();
for (RoleSelectPermissions roleSelectPermissions : currentRoleSelectPermissions) {
if (Asserts.isAllNotNullString(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression())) {
permission.put(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression());
}
}
RowLevelPermissionsContext.set(permission);
}
process.info("Finish initialize FlinkSQLEnv."); process.info("Finish initialize FlinkSQLEnv.");
} }
......
...@@ -32,6 +32,7 @@ import org.dinky.config.Dialect; ...@@ -32,6 +32,7 @@ import org.dinky.config.Dialect;
import org.dinky.config.Docker; import org.dinky.config.Docker;
import org.dinky.constant.FlinkRestResultConstant; import org.dinky.constant.FlinkRestResultConstant;
import org.dinky.constant.NetConstant; import org.dinky.constant.NetConstant;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.task.DaemonFactory; import org.dinky.daemon.task.DaemonFactory;
import org.dinky.daemon.task.DaemonTaskConfig; import org.dinky.daemon.task.DaemonTaskConfig;
...@@ -73,6 +74,7 @@ import org.dinky.model.JobInfoDetail; ...@@ -73,6 +74,7 @@ import org.dinky.model.JobInfoDetail;
import org.dinky.model.JobInstance; import org.dinky.model.JobInstance;
import org.dinky.model.JobLifeCycle; import org.dinky.model.JobLifeCycle;
import org.dinky.model.JobStatus; import org.dinky.model.JobStatus;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Savepoints; import org.dinky.model.Savepoints;
import org.dinky.model.Statement; import org.dinky.model.Statement;
import org.dinky.model.SystemConfiguration; import org.dinky.model.SystemConfiguration;
...@@ -103,6 +105,7 @@ import org.dinky.service.StatementService; ...@@ -103,6 +105,7 @@ import org.dinky.service.StatementService;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.service.TaskVersionService; import org.dinky.service.TaskVersionService;
import org.dinky.service.UDFTemplateService; import org.dinky.service.UDFTemplateService;
import org.dinky.service.UserService;
import org.dinky.utils.DockerClientUtils; import org.dinky.utils.DockerClientUtils;
import org.dinky.utils.JSONUtil; import org.dinky.utils.JSONUtil;
import org.dinky.utils.UDFUtils; import org.dinky.utils.UDFUtils;
...@@ -127,6 +130,7 @@ import java.util.Date; ...@@ -127,6 +130,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Resource; import javax.annotation.Resource;
...@@ -176,6 +180,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -176,6 +180,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private final FragmentVariableService fragmentVariableService; private final FragmentVariableService fragmentVariableService;
private final UDFTemplateService udfTemplateService; private final UDFTemplateService udfTemplateService;
private final DataSourceProperties dataSourceProperties; private final DataSourceProperties dataSourceProperties;
private final UserService userService;
@Resource @Lazy private CatalogueService catalogueService; @Resource @Lazy private CatalogueService catalogueService;
...@@ -1029,6 +1034,21 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1029,6 +1034,21 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
config.setSavePointPath(null); config.setSavePointPath(null);
} }
config.setVariables(fragmentVariableService.listEnabledVariables()); config.setVariables(fragmentVariableService.listEnabledVariables());
List<RoleSelectPermissions> currentRoleSelectPermissions =
userService.getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
ConcurrentHashMap<String, String> permission = new ConcurrentHashMap<>();
for (RoleSelectPermissions roleSelectPermissions : currentRoleSelectPermissions) {
if (Asserts.isAllNotNullString(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression())) {
permission.put(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression());
}
}
RowLevelPermissionsContext.set(permission);
}
return config; return config;
} }
......
...@@ -21,6 +21,7 @@ package org.dinky.service.impl; ...@@ -21,6 +21,7 @@ package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl; import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.mapper.UserRoleMapper; import org.dinky.mapper.UserRoleMapper;
import org.dinky.model.Role;
import org.dinky.model.UserRole; import org.dinky.model.UserRole;
import org.dinky.service.UserRoleService; import org.dinky.service.UserRoleService;
...@@ -56,4 +57,9 @@ public class UserRoleServiceImpl extends SuperServiceImpl<UserRoleMapper, UserRo ...@@ -56,4 +57,9 @@ public class UserRoleServiceImpl extends SuperServiceImpl<UserRoleMapper, UserRo
public boolean deleteByRoleIds(List<Integer> roleIds) { public boolean deleteByRoleIds(List<Integer> roleIds) {
return baseMapper.deleteByRoleIds(roleIds) > 0; return baseMapper.deleteByRoleIds(roleIds) > 0;
} }
@Override
public List<Role> getRoleByUserId(Integer userId) {
return baseMapper.getRoleByUserId(userId);
}
} }
...@@ -29,11 +29,13 @@ import org.dinky.dto.ModifyPasswordDTO; ...@@ -29,11 +29,13 @@ import org.dinky.dto.ModifyPasswordDTO;
import org.dinky.dto.UserDTO; import org.dinky.dto.UserDTO;
import org.dinky.mapper.UserMapper; import org.dinky.mapper.UserMapper;
import org.dinky.model.Role; import org.dinky.model.Role;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Tenant; import org.dinky.model.Tenant;
import org.dinky.model.User; import org.dinky.model.User;
import org.dinky.model.UserRole; import org.dinky.model.UserRole;
import org.dinky.model.UserTenant; import org.dinky.model.UserTenant;
import org.dinky.params.AssignRoleParams; import org.dinky.params.AssignRoleParams;
import org.dinky.service.RoleSelectPermissionsService;
import org.dinky.service.RoleService; import org.dinky.service.RoleService;
import org.dinky.service.TenantService; import org.dinky.service.TenantService;
import org.dinky.service.UserRoleService; import org.dinky.service.UserRoleService;
...@@ -44,6 +46,7 @@ import org.dinky.utils.MessageResolverUtils; ...@@ -44,6 +46,7 @@ import org.dinky.utils.MessageResolverUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -76,6 +79,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -76,6 +79,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
private final TenantService tenantService; private final TenantService tenantService;
private final RoleSelectPermissionsService roleSelectPermissionsService;
@Override @Override
public Result<Void> registerUser(User user) { public Result<Void> registerUser(User user) {
User userByUsername = getUserByUsername(user.getUsername()); User userByUsername = getUserByUsername(user.getUsername());
...@@ -293,4 +298,19 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -293,4 +298,19 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
User user = getById(id); User user = getById(id);
return "admin".equals(user.getUsername()); return "admin".equals(user.getUsername());
} }
@Override
public List<Role> getCurrentRole() {
return roleService.getRoleByUserId(StpUtil.getLoginIdAsInt());
}
@Override
public List<RoleSelectPermissions> getCurrentRoleSelectPermissions() {
List<Role> currentRole = getCurrentRole();
if (Asserts.isNullCollection(currentRole)) {
return new ArrayList<>();
}
List<Integer> roleIds = currentRole.stream().map(Role::getId).collect(Collectors.toList());
return roleSelectPermissionsService.listRoleSelectPermissionsByRoleIds(roleIds);
}
} }
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dinky.mapper.RoleSelectPermissionsMapper">
<select id="selectForProTable" resultType="org.dinky.model.RoleSelectPermissions">
select
a.*,
b.role_code,
b.role_name
from
dinky_role_select_permissions a
left join dinky_role b on b.id = a.role_id
<where>
1=1
<if test='param.roleId!=null and param.roleId!=""'>
and a.role_id = #{param.roleId}
</if>
<if test='param.tableName!=null and param.tableName!=""'>
and a.table_name like "%${param.tableName}%"
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!="" and !ew.sqlSegment.startsWith(" ORDER BY")'>
and
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!=""'>
${ew.sqlSegment}
</if>
</where>
</select>
<delete id="deleteByRoleIds" parameterType="java.util.List">
DELETE FROM dinky_role_select_permissions
WHERE role_id IN
<foreach collection="roleIds" item="item" open="(" separator="," close=")">
${item}
</foreach>
</delete>
<select id="listRoleSelectPermissionsByRoleIds" resultType="org.dinky.model.RoleSelectPermissions">
select
a.*,
b.role_code,
b.role_name
from
dinky_role_select_permissions a, dinky_role b
WHERE
b.id = a.role_id
and a.role_id IN
<foreach collection="roleIds" item="item" open="(" separator="," close=")">
${item}
</foreach>
order by a.id asc
</select>
</mapper>
\ No newline at end of file
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
<include refid="baseSql"/> <include refid="baseSql"/>
from from
dinky_user_role dinky_user_role
where user_id = (#{userId}) where user_id = #{userId}
</select> </select>
<delete id="deleteBathRelation" parameterType="java.util.List"> <delete id="deleteBathRelation" parameterType="java.util.List">
...@@ -49,4 +49,21 @@ ...@@ -49,4 +49,21 @@
${item} ${item}
</foreach> </foreach>
</delete> </delete>
<select id="getRoleByUserId" resultType="org.dinky.model.Role">
select
distinct
b.id
,b.role_code
,b.role_name
,b.is_delete
,b.note
,b.create_time
,b.update_time
from
dinky_user_role a
inner join dinky_role b on b.id = a.role_id
where a.user_id = #{userId}
and b.is_delete = 0
</select>
</mapper> </mapper>
\ No newline at end of file
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final SqlExprToRexConverterFactory sqlExprToRexConverterFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
SqlExprToRexConverterFactory sqlExprToRexConverterFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.sqlExprToRexConverterFactory = sqlExprToRexConverterFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
SqlNode parsed = parser.parse(statement);
Operation operation =
SqlToOperationConverter.convert(planner, catalogManager, parsed)
.orElseThrow(() -> new TableException("Unsupported query: " + statement));
return Collections.singletonList(operation);
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
final SqlExprToRexConverter sqlExprToRexConverter =
sqlExprToRexConverterFactory.create(inputRowType, outputType);
final RexNode rexNode = sqlExprToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlExprToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final SqlExprToRexConverterFactory sqlExprToRexConverterFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
SqlExprToRexConverterFactory sqlExprToRexConverterFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.sqlExprToRexConverterFactory = sqlExprToRexConverterFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
// use parseSqlList here because we need to support statement end with ';' in sql client.
SqlNodeList sqlNodeList = parser.parseSqlList(statement);
List<SqlNode> parsed = sqlNodeList.getList();
Preconditions.checkArgument(parsed.size() == 1, "only single statement supported");
return Collections.singletonList(
SqlToOperationConverter.convert(planner, catalogManager, parsed.get(0))
.orElseThrow(() -> new TableException("Unsupported query: " + statement)));
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
final SqlExprToRexConverter sqlExprToRexConverter =
sqlExprToRexConverterFactory.create(inputRowType, outputType);
final RexNode rexNode = sqlExprToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlExprToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.RexFactory;
import org.apache.flink.table.planner.calcite.SqlToRexConverter;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final RexFactory rexFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
RexFactory rexFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.rexFactory = rexFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
// use parseSqlList here because we need to support statement end with ';' in sql client.
SqlNodeList sqlNodeList = parser.parseSqlList(statement);
List<SqlNode> parsed = sqlNodeList.getList();
Preconditions.checkArgument(parsed.size() == 1, "only single statement supported");
return Collections.singletonList(
SqlToOperationConverter.convert(planner, catalogManager, parsed.get(0))
.orElseThrow(() -> new TableException("Unsupported query: " + statement)));
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
try {
final SqlToRexConverter sqlToRexConverter =
rexFactory.createSqlToRexConverter(inputRowType, outputType);
final RexNode rexNode = sqlToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
} catch (Throwable t) {
throw new ValidationException(
String.format("Invalid SQL expression: %s", sqlExpression), t);
}
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.executor; package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.catalog.UnresolvedIdentifier; import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser; import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression; import org.apache.flink.table.expressions.ResolvedExpression;
...@@ -64,4 +65,9 @@ public class ParserWrapper implements Parser { ...@@ -64,4 +65,9 @@ public class ParserWrapper implements Parser {
public String[] getCompletionHints(String statement, int position) { public String[] getCompletionHints(String statement, int position) {
return parser.getCompletionHints(statement, position); return parser.getCompletionHints(statement, position);
} }
@Override
public SqlNode parseExpression(String sqlExpression) {
return parser.parseExpression(sqlExpression);
}
} }
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.context;
import org.dinky.executor.CustomTableEnvironment;
/** CustomTableEnvironmentContext */
public class CustomTableEnvironmentContext {
private static final ThreadLocal<CustomTableEnvironment> CUSTOM_TABLE_ENVIRONMENT_CONTEXT =
new ThreadLocal<>();
public static void set(CustomTableEnvironment value) {
CUSTOM_TABLE_ENVIRONMENT_CONTEXT.set(value);
}
public static CustomTableEnvironment get() {
return CUSTOM_TABLE_ENVIRONMENT_CONTEXT.get();
}
public static void clear() {
CUSTOM_TABLE_ENVIRONMENT_CONTEXT.remove();
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.context;
import java.util.concurrent.ConcurrentHashMap;
/** RowLevelPermissionsContext */
public class RowLevelPermissionsContext {
private static final ThreadLocal<ConcurrentHashMap<String, String>>
ROW_LEVEL_PERMISSIONS_CONTEXT = new ThreadLocal<>();
public static void set(ConcurrentHashMap<String, String> value) {
ROW_LEVEL_PERMISSIONS_CONTEXT.set(value);
}
public static ConcurrentHashMap<String, String> get() {
return ROW_LEVEL_PERMISSIONS_CONTEXT.get();
}
public static void clear() {
ROW_LEVEL_PERMISSIONS_CONTEXT.remove();
}
}
...@@ -26,8 +26,10 @@ import static org.dinky.function.util.UDFUtil.YARN; ...@@ -26,8 +26,10 @@ import static org.dinky.function.util.UDFUtil.YARN;
import org.dinky.api.FlinkAPI; import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant; import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder; import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder; import org.dinky.context.JarPathContextHolder;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.executor.EnvironmentSetting; import org.dinky.executor.EnvironmentSetting;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorSetting;
...@@ -361,6 +363,8 @@ public class JobManager { ...@@ -361,6 +363,8 @@ public class JobManager {
public boolean close() { public boolean close() {
JobContextHolder.clear(); JobContextHolder.clear();
CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear();
return false; return false;
} }
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder; import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.interceptor.FlinkInterceptor; import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult; import org.dinky.interceptor.FlinkInterceptorResult;
...@@ -185,6 +186,7 @@ public abstract class Executor { ...@@ -185,6 +186,7 @@ public abstract class Executor {
private void initExecutionEnvironment() { private void initExecutionEnvironment() {
useSqlFragment = executorSetting.isUseSqlFragment(); useSqlFragment = executorSetting.isUseSqlFragment();
tableEnvironment = createCustomTableEnvironment(); tableEnvironment = createCustomTableEnvironment();
CustomTableEnvironmentContext.set(tableEnvironment);
tableEnvironment.injectParser(new CustomParserImpl()); tableEnvironment.injectParser(new CustomParserImpl());
tableEnvironment.injectExtendedExecutor(new CustomExtendedOperationExecutorImpl(this)); tableEnvironment.injectExtendedExecutor(new CustomExtendedOperationExecutorImpl(this));
Configuration configuration = tableEnvironment.getConfig().getConfiguration(); Configuration configuration = tableEnvironment.getConfig().getConfiguration();
......
...@@ -170,6 +170,12 @@ export default [ ...@@ -170,6 +170,12 @@ export default [
icon: 'TeamOutlined', icon: 'TeamOutlined',
component: './AuthenticationCenter/RoleManager', component: './AuthenticationCenter/RoleManager',
}, },
{
path: '/authenticationCenter/roleSelectPermissions',
name: 'roleSelectPermissions',
icon: 'FundViewOutlined',
component: './AuthenticationCenter/RoleSelectPermissions',
},
{ {
path: '/authenticationCenter/namespaceManager', path: '/authenticationCenter/namespaceManager',
name: 'namespaceManager', name: 'namespaceManager',
......
...@@ -51,6 +51,7 @@ export default { ...@@ -51,6 +51,7 @@ export default {
'menu.authenticationCenter.userManager': 'User Management', 'menu.authenticationCenter.userManager': 'User Management',
'menu.authenticationCenter.namespaceManager': 'NameSpace Management', 'menu.authenticationCenter.namespaceManager': 'NameSpace Management',
'menu.authenticationCenter.roleManager': 'Role Management', 'menu.authenticationCenter.roleManager': 'Role Management',
'menu.authenticationCenter.roleSelectPermissions': 'Role Data Permissions',
'menu.authenticationCenter.tenantManager': 'Tenant Management', 'menu.authenticationCenter.tenantManager': 'Tenant Management',
'menu.settings': 'Setting Center', 'menu.settings': 'Setting Center',
......
...@@ -202,11 +202,11 @@ export default { ...@@ -202,11 +202,11 @@ export default {
'pages.user.UserUpdateUser': 'Update User', 'pages.user.UserUpdateUser': 'Update User',
'pages.user.AssignRole': 'Assign Role', 'pages.user.AssignRole': 'Assign Role',
'pages.user.delete': 'Delete User', 'pages.user.delete': 'Delete User',
'pages.user.deleteConfirm': 'Are you sure you want to delete this User?', 'pages.user.deleteConfirm': 'Are you sure you want to delete this User?',
'pages.user.enable': 'Enable User', 'pages.user.enable': 'Enable User',
'pages.user.enableConfirm': 'Are you sure you want to enable this User?', 'pages.user.enableConfirm': 'Are you sure you want to enable this User?',
'pages.user.disable': 'Disable User', 'pages.user.disable': 'Disable User',
'pages.user.disableConfirm': 'Are you sure you want to disable this User?', 'pages.user.disableConfirm': 'Are you sure you want to disable this User?',
'pages.user.UserEnterUserName': 'Please enter user name', 'pages.user.UserEnterUserName': 'Please enter user name',
'pages.user.UserEnterUniqueUserName': 'Please enter unique user name', 'pages.user.UserEnterUniqueUserName': 'Please enter unique user name',
'pages.user.UserEnterJobNumber': 'Please enter job number', 'pages.user.UserEnterJobNumber': 'Please enter job number',
...@@ -231,22 +231,22 @@ export default { ...@@ -231,22 +231,22 @@ export default {
'pages.tenant.EnterTenantCode': 'Please enter Tenant Code!', 'pages.tenant.EnterTenantCode': 'Please enter Tenant Code!',
'pages.tenant.EnterTenantNote': 'Please enter Tenant Note!', 'pages.tenant.EnterTenantNote': 'Please enter Tenant Note!',
'pages.tenant.delete': 'Delete Tenant', 'pages.tenant.delete': 'Delete Tenant',
'pages.tenant.deleteConfirm': 'Are you sure you want to delete this Tenant?', 'pages.tenant.deleteConfirm': 'Are you sure you want to delete this Tenant?',
'pages.tenant.enable': 'Enable Tenant', 'pages.tenant.enable': 'Enable Tenant',
'pages.tenant.enableConfirm': 'Are you sure you want to enable this Tenant?', 'pages.tenant.enableConfirm': 'Are you sure you want to enable this Tenant?',
'pages.tenant.disable': 'Disable Tenant', 'pages.tenant.disable': 'Disable Tenant',
'pages.tenant.disableConfirm': 'Are you sure you want to disable this Tenant?', 'pages.tenant.disableConfirm': 'Are you sure you want to disable this Tenant?',
'pages.nameSpace.NameSpaceManagement': 'NameSpace Management', 'pages.nameSpace.NameSpaceManagement': 'NameSpace Management',
'pages.nameSpace.NameSpaceCode': 'NameSpace Code', 'pages.nameSpace.NameSpaceCode': 'NameSpace Code',
'pages.nameSpace.belongTenant': 'Belong Tenant', 'pages.nameSpace.belongTenant': 'Belong Tenant',
'pages.nameSpace.deleteNameSpace': 'Delete NameSpace', 'pages.nameSpace.deleteNameSpace': 'Delete NameSpace',
'pages.nameSpace.deleteNameSpaceConfirm': 'Are you sure you want to delete this NameSpace?', 'pages.nameSpace.deleteNameSpaceConfirm': 'Are you sure you want to delete this NameSpace?',
'pages.nameSpace.enableNameSpace': 'Enable NameSpace', 'pages.nameSpace.enableNameSpace': 'Enable NameSpace',
'pages.nameSpace.enableNameSpaceConfirm': 'Are you sure you want to enable this NameSpace?', 'pages.nameSpace.enableNameSpaceConfirm': 'Are you sure you want to enable this NameSpace?',
'pages.nameSpace.disableNameSpace': 'Disable NameSpace', 'pages.nameSpace.disableNameSpace': 'Disable NameSpace',
'pages.nameSpace.disableNameSpaceConfirm': 'Are you sure you want to disable this NameSpace?', 'pages.nameSpace.disableNameSpaceConfirm': 'Are you sure you want to disable this NameSpace?',
'pages.nameSpace.create': 'Create NameSpace', 'pages.nameSpace.create': 'Create NameSpace',
'pages.nameSpace.update': 'Update NameSpace', 'pages.nameSpace.update': 'Update NameSpace',
'pages.nameSpace.EnterNameSpaceCode': 'Please enter NameSpace Code!', 'pages.nameSpace.EnterNameSpaceCode': 'Please enter NameSpace Code!',
...@@ -260,16 +260,23 @@ export default { ...@@ -260,16 +260,23 @@ export default {
'pages.role.belongTenant': 'Belong Tenant', 'pages.role.belongTenant': 'Belong Tenant',
'pages.role.create': 'Create Role', 'pages.role.create': 'Create Role',
'pages.role.update': 'Update Role', 'pages.role.update': 'Update Role',
'pages.role.selectRole': 'Please select Role!',
'pages.role.EnterRoleCode': 'Please enter Role Code!', 'pages.role.EnterRoleCode': 'Please enter Role Code!',
'pages.role.EnterRoleName': 'Please enter Role Name!', 'pages.role.EnterRoleName': 'Please enter Role Name!',
'pages.role.selectNameSpace': 'Please select NameSpace!', 'pages.role.selectNameSpace': 'Please select NameSpace!',
'pages.role.EnterNote': 'Please enter Role Note!', 'pages.role.EnterNote': 'Please enter Role Note!',
'pages.role.delete': 'Delete Role', 'pages.role.delete': 'Delete Role',
'pages.role.deleteConfirm': 'Are you sure you want to delete this Role?', 'pages.role.deleteConfirm': 'Are you sure you want to delete this Role?',
'pages.role.enable': 'Enable Role', 'pages.role.enable': 'Enable Role',
'pages.role.enableConfirm': 'Are you sure you want to enable this Role?', 'pages.role.enableConfirm': 'Are you sure you want to enable this Role?',
'pages.role.disable': 'Disable Role', 'pages.role.disable': 'Disable Role',
'pages.role.disableConfirm': 'Are you sure you want to disable this Role?', 'pages.role.disableConfirm': 'Are you sure you want to disable this Role?',
'pages.roleSelectPermissions.roleSelectPermissionsManagement': 'Role select permissions management',
'pages.roleSelectPermissions.tableName': 'Table name',
'pages.roleSelectPermissions.expression': 'Expression',
'pages.roleSelectPermissions.delete': 'Delete role data permissions',
'pages.roleSelectPermissions.deleteConfirm': 'Are you sure you want to delete this role select permissions?',
'pages.regist.openAPI': 'OpenAPI Document', 'pages.regist.openAPI': 'OpenAPI Document',
'pages.regist.BusinessComponent': 'Business Component Document', 'pages.regist.BusinessComponent': 'Business Component Document',
......
...@@ -50,6 +50,7 @@ export default { ...@@ -50,6 +50,7 @@ export default {
'menu.authenticationCenter.userManager': '用户管理', 'menu.authenticationCenter.userManager': '用户管理',
'menu.authenticationCenter.namespaceManager': '命名空间管理', 'menu.authenticationCenter.namespaceManager': '命名空间管理',
'menu.authenticationCenter.roleManager': '角色管理', 'menu.authenticationCenter.roleManager': '角色管理',
'menu.authenticationCenter.roleSelectPermissions': '角色数据权限',
'menu.authenticationCenter.tenantManager': '租户管理', 'menu.authenticationCenter.tenantManager': '租户管理',
'menu.settings': '配置中心', 'menu.settings': '配置中心',
......
...@@ -262,6 +262,7 @@ export default { ...@@ -262,6 +262,7 @@ export default {
'pages.role.update': '修改角色', 'pages.role.update': '修改角色',
'pages.role.EnterRoleCode': '请输入角色编码!', 'pages.role.EnterRoleCode': '请输入角色编码!',
'pages.role.EnterRoleName': '请输入角色名称!', 'pages.role.EnterRoleName': '请输入角色名称!',
'pages.role.selectRole': '请选择角色!',
'pages.role.selectNameSpace': '请选择命名空间!', 'pages.role.selectNameSpace': '请选择命名空间!',
'pages.role.EnterNote': '请输入角色的备注/描述信息!', 'pages.role.EnterNote': '请输入角色的备注/描述信息!',
'pages.role.delete': '删除角色', 'pages.role.delete': '删除角色',
...@@ -271,11 +272,18 @@ export default { ...@@ -271,11 +272,18 @@ export default {
'pages.role.disable': '禁用角色', 'pages.role.disable': '禁用角色',
'pages.role.disableConfirm': '您确定要禁用此角色吗?', 'pages.role.disableConfirm': '您确定要禁用此角色吗?',
'pages.roleSelectPermissions.roleSelectPermissionsManagement': '角色数据权限管理',
'pages.roleSelectPermissions.roleId': '角色 ID',
'pages.roleSelectPermissions.tableName': '表名',
'pages.roleSelectPermissions.expression': '表达式',
'pages.roleSelectPermissions.EnterTableName': '请输入表名称!',
'pages.roleSelectPermissions.EnterExpression': '请输入表达式!',
'pages.roleSelectPermissions.delete': '删除角色数据权限',
'pages.roleSelectPermissions.deleteConfirm': '您确定要删除此角色数据权限吗?',
'pages.regist.openAPI': 'OpenAPI 文档', 'pages.regist.openAPI': 'OpenAPI 文档',
'pages.regist.BusinessComponent': '业务组件文档', 'pages.regist.BusinessComponent': '业务组件文档',
'pages.metadata.NoDatabaseSelected': '未选择数据源', 'pages.metadata.NoDatabaseSelected': '未选择数据源',
'pages.metadata.Application': 'Application', 'pages.metadata.Application': 'Application',
'pages.metadata.TableInfo': '表信息', 'pages.metadata.TableInfo': '表信息',
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React, {useState} from 'react';
import {Button, Form, Input, Modal, Select, Tag} from 'antd';
import {
RoleSelectPermissionsTableListItem,
RoleTableListItem
} from "@/pages/AuthenticationCenter/data.d";
import {connect} from "umi";
import {NameSpaceStateType} from "@/pages/AuthenticationCenter/RoleManager/model";
import {buildFormData, getFormData} from "@/pages/AuthenticationCenter/function";
import {l} from "@/utils/intl";
export type RoleSelectPermissionsFormProps = {
onCancel: (flag?: boolean) => void;
onSubmit: (values: Partial<RoleSelectPermissionsTableListItem>) => void;
modalVisible: boolean;
values: Partial<RoleSelectPermissionsTableListItem>;
role: RoleTableListItem[];
};
const formLayout = {
labelCol: {span: 7},
wrapperCol: {span: 13},
};
const Option = Select.Option;
const RoleSelectPermissionsForm: React.FC<RoleSelectPermissionsFormProps> = (props) => {
const [form] = Form.useForm();
const [formVals, setFormVals] = useState<Partial<RoleSelectPermissionsTableListItem>>({
id: props.values?.id,
roleId: props.values?.roleId,
tableName: props.values?.tableName,
roleName: props.values?.roleName,
expression: props.values?.expression,
createTime: props.values?.createTime,
updateTime: props.values?.updateTime,
});
const {
onSubmit: handleSubmit,
onCancel: handleModalVisible,
modalVisible,
role,
} = props;
const getRoleOptions = () => {
const itemList: JSX.Element[] = [];
for (const item of role) {
const tag = (
<>
<Tag color="processing">
{item.roleName}
</Tag>
</>);
itemList.push(<Option key={item.id} value={item.id} label={tag}>
{tag}
</Option>)
}
return itemList;
};
const submitForm = async () => {
const fieldsValue = await form.validateFields();
if(fieldsValue.roleId.length > 0){
fieldsValue.roleId = fieldsValue.roleId[0];
}else{
fieldsValue.roleId = null;
}
setFormVals(buildFormData(formVals, fieldsValue));
handleSubmit(buildFormData(formVals, fieldsValue));
};
const renderContent = (formVals) => {
return (
<>
<Form.Item
name="roleId"
label={l('pages.role.roleName')}
rules={[{required: true, message: l('pages.role.selectRole')}]}
>
<Select
mode="multiple"
style={{width: '100%'}}
placeholder={l('pages.role.selectRole')}
optionLabelProp="label"
>
{getRoleOptions()}
</Select>
</Form.Item>
<Form.Item
name="tableName"
label={l('pages.roleSelectPermissions.tableName')}
rules={[{required: true, message: l('pages.roleSelectPermissions.EnterTableName')}]}>
<Input placeholder={l('pages.roleSelectPermissions.EnterTableName')}/>
</Form.Item>
<Form.Item
name="expression"
label={l('pages.roleSelectPermissions.expression')}
>
<Input.TextArea placeholder={l('pages.roleSelectPermissions.EnterExpression')} allowClear
autoSize={{minRows: 3, maxRows: 10}}/>
</Form.Item>
</>
);
};
const renderFooter = () => {
return (
<>
<Button onClick={() => handleModalVisible(false)}>{l('button.cancel')}</Button>
<Button type="primary" onClick={() => submitForm()}>
{l('button.finish')}
</Button>
</>
);
};
return (
<Modal
width={"40%"}
bodyStyle={{padding: '32px 40px 48px'}}
destroyOnClose
title={formVals.id ? l('pages.role.update') : l('pages.role.create')}
visible={modalVisible}
footer={renderFooter()}
onCancel={() => handleModalVisible()}
>
<Form
{...formLayout}
form={form}
initialValues={getFormData(formVals)}
>
{renderContent(getFormData(formVals))}
</Form>
</Modal>
);
};
export default connect(({NameSpace}: { NameSpace: NameSpaceStateType }) => ({
role: NameSpace.role,
}))(RoleSelectPermissionsForm);
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React, {useEffect, useRef, useState} from "react";
import {DownOutlined, PlusOutlined} from '@ant-design/icons';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Dropdown, Menu, Modal} from 'antd';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {handleAddOrUpdate, handleRemove, queryData} from "@/components/Common/crud";
import {RoleSelectPermissionsTableListItem} from "@/pages/AuthenticationCenter/data.d";
import RoleSelectPermissionsForm from "@/pages/AuthenticationCenter/RoleSelectPermissions/components/RoleSelectPermissionsForm";
import {getRoleList} from "@/pages/AuthenticationCenter/service";
import {connect} from "umi";
import {l} from "@/utils/intl";
const url = '/api/roleSelectPermissions';
const RoleSelectPermissionsFormList: React.FC<{}> = (props: any) => {
const {dispatch} = props;
const [formValues, setFormValues] = useState<RoleSelectPermissionsTableListItem>();
const [modalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const actionRef = useRef<ActionType>();
const [selectedRowsState, setSelectedRows] = useState<RoleSelectPermissionsTableListItem[]>([]);
useEffect(() => {
getRoleList(dispatch);
}, []);
const editAndDelete = (key: string | number, currentItem: RoleSelectPermissionsTableListItem) => {
if (key === 'edit') {
setFormValues(currentItem);
handleUpdateModalVisible(true);
} else if (key === 'delete') {
Modal.confirm({
title: l('pages.role.delete'),
content: l('pages.role.deleteConfirm'),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
await handleRemove(url, [currentItem]);
actionRef.current?.reloadAndRest?.();
}
});
}
};
const MoreBtn: React.FC<{
item: RoleSelectPermissionsTableListItem;
}> = ({item}) => (
<Dropdown
overlay={
<Menu onClick={({key}) => editAndDelete(key, item)}>
<Menu.Item key="edit">{l('button.edit')}</Menu.Item>
<Menu.Item key="delete">{l('button.delete')}</Menu.Item>
</Menu>
}
>
<a>
{l('button.more')} <DownOutlined/>
</a>
</Dropdown>
);
const columns: ProColumns<RoleSelectPermissionsTableListItem>[] = [
{
title: 'ID',
dataIndex: 'id',
hideInTable: true,
hideInSearch: true,
sorter: true,
},
{
title: l('pages.roleSelectPermissions.roleId'),
dataIndex: 'roleId',
hideInTable: true,
hideInSearch: true,
},
{
title: l('pages.role.roleCode'),
dataIndex: 'roleCode',
},
{
title: l('pages.role.roleName'),
sorter: true,
dataIndex: 'roleName',
},
{
title: l('pages.roleSelectPermissions.tableName'),
sorter: true,
dataIndex: 'tableName',
},
{
title: l('pages.roleSelectPermissions.expression'),
dataIndex: 'expression',
hideInSearch: true,
ellipsis: true,
},
{
title: l('global.table.createTime'),
dataIndex: 'createTime',
sorter: true,
valueType: 'dateTime',
},
{
title: l('global.table.updateTime'),
dataIndex: 'updateTime',
sorter: true,
valueType: 'dateTime',
},
{
title: l('global.table.operate'),
dataIndex: 'option',
valueType: 'option',
render: (_, record) => [
<Button type={"link"}
onClick={() => {
handleUpdateModalVisible(true);
setFormValues(record);
}}
>
{l('button.config')}
</Button>,
<MoreBtn key="more" item={record}/>,
],
},
];
return (
<PageContainer title={false}>
<ProTable<RoleSelectPermissionsTableListItem>
headerTitle={l('pages.roleSelectPermissions.roleSelectPermissionsManagement')}
actionRef={actionRef}
rowKey="id"
search={{
labelWidth: 120,
}}
toolBarRender={() => [
<Button type="primary" onClick={() => handleModalVisible(true)}>
<PlusOutlined/> {l('button.create')}
</Button>,
]}
request={(params, sorter, filter) => queryData(url, {...params, sorter, filter})}
columns={columns}
rowSelection={{
onChange: (_, selectedRows) => setSelectedRows(selectedRows),
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
{selectedRowsState?.length > 0 && (
<FooterToolbar
extra={
<div>
{l('tips.selected', '',
{
total: <a
style={{fontWeight: 600}}>{selectedRowsState.length}</a>
})} &nbsp;&nbsp; </div>
}
>
<Button type="primary" danger
onClick={() => {
Modal.confirm({
title: l('pages.roleSelectPermissions.delete'),
content: l('pages.roleSelectPermissions.deleteConfirm'),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
await handleRemove(url, selectedRowsState);
setSelectedRows([]);
actionRef.current?.reloadAndRest?.();
}
});
}}
>
{l('button.batchDelete')}
</Button>
</FooterToolbar>
)}
<RoleSelectPermissionsForm
onSubmit={async (value) => {
const success = await handleAddOrUpdate(url, value);
if (success) {
handleModalVisible(false);
setFormValues({});
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
onCancel={() => {
handleModalVisible(false);
}}
modalVisible={modalVisible}
values={{}}
/>
{
formValues && Object.keys(formValues).length ? (
<RoleSelectPermissionsForm
onSubmit={async (value) => {
const success = await handleAddOrUpdate(url, value);
if (success) {
handleUpdateModalVisible(false);
setFormValues({});
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
onCancel={() => {
handleUpdateModalVisible(false);
setFormValues({});
}}
modalVisible={updateModalVisible}
values={formValues}
/>
) : undefined
}
</PageContainer>
);
};
export default connect()(RoleSelectPermissionsFormList);
...@@ -64,6 +64,16 @@ export type RoleTableListItem = { ...@@ -64,6 +64,16 @@ export type RoleTableListItem = {
updateTime?: Date; updateTime?: Date;
}; };
export type RoleSelectPermissionsTableListItem = {
id?: number;
roleId?: number;
roleCode?: string;
roleName?: string;
tableName?: string;
expression?: string;
createTime?: Date;
updateTime?: Date;
};
export type NameSpaceTableListItem = { export type NameSpaceTableListItem = {
id?: number; id?: number;
......
...@@ -37,7 +37,7 @@ export function getRoleList(dispatch: any) { ...@@ -37,7 +37,7 @@ export function getRoleList(dispatch: any) {
const res = queryData('/api/role'); const res = queryData('/api/role');
res.then((result) => { res.then((result) => {
result.data && dispatch && dispatch({ result.data && dispatch && dispatch({
type: "Role/getRoleList", type: "NameSpace/saveRole",
payload: result.data, payload: result.data,
}); });
}); });
......
...@@ -1030,5 +1030,19 @@ CREATE TABLE `metadata_table_property` ( ...@@ -1030,5 +1030,19 @@ CREATE TABLE `metadata_table_property` (
-- ---------------------------- -- ----------------------------
-- ----------------------------
-- Table structure for dinky_role_select_permissions
-- ----------------------------
CREATE TABLE dinky_role_select_permissions
(
id int auto_increment comment 'ID'
primary key,
role_id int not null comment '角色ID',
table_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表名',
expression varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表达式',
create_time datetime null comment '创建时间',
update_time datetime null comment '更新时间'
)
COMMENT '角色数据查询权限' COLLATE = utf8mb4_general_ci;
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
-- 0.7.2 2023-2-12
-- ----------------------------
-- ----------------------------
-- Table structure for dlink_role_select_permissions
-- ----------------------------
CREATE TABLE dlink_role_select_permissions
(
id int auto_increment comment 'ID'
primary key,
role_id int not null comment '角色ID',
table_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表名',
expression varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表达式',
create_time datetime null comment '创建时间',
update_time datetime null comment '更新时间'
)
COMMENT '角色数据查询权限' COLLATE = utf8mb4_general_ci;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment