Skip to content

Commit

Permalink
feat-config-去掉debug模式,改用系统默认:PROD\TEST\DEV
Browse files Browse the repository at this point in the history
  • Loading branch information
aruis committed Oct 23, 2024
1 parent b68276f commit 9a66929
Show file tree
Hide file tree
Showing 20 changed files with 137 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ public String dictDataAuthToCondition(String userID, String module, String dictD
.collect(Collectors.joining(",")));
case "department" -> "%s='%s'".formatted(departmentColumn, departmentID);
case "department_and_subordinates" -> "%s in (%s)"
.formatted(departmentColumn, departmentAndSubordinates(organizationID)
.formatted(departmentColumn, departmentAndSubordinates(departmentID)
.stream().map("'%s'"::formatted)
.collect(Collectors.joining(",")));
case "supervision_region" -> "%s in (%s)"
Expand Down Expand Up @@ -481,7 +481,7 @@ public Map getModuleByID(String moduleID) {

@Override
public Set<String> getUserAvailableRoles(String userID) {
if (config.debug()) {
if (config.isTestMode()) {
return loadRoles(userID);
} else {
return userToRoles.get(userID);
Expand Down
6 changes: 1 addition & 5 deletions muyun-boot/src/main/java/net/ximatai/muyun/MainApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import io.quarkus.runtime.annotations.QuarkusMain;
import jakarta.inject.Inject;
import net.ximatai.muyun.core.config.MuYunConfig;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -17,12 +16,9 @@ public class MainApp implements QuarkusApplication {
@Inject
MuYunConfig config;

@ConfigProperty(name = "quarkus.http.port")
int port;

@Override
public int run(String... args) {
logger.info("MuYun started successfully! Running on port: {}. Debug mode is {}", port, config.debug() ? "OPEN" : "CLOSE");
logger.info("PROFILE ON {}", config.profile());
Quarkus.waitForExit();
return 0;
}
Expand Down
1 change: 0 additions & 1 deletion muyun-boot/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
muyun:
debug: true
super-user-id: 1 # 可以在环境变量里预先设置 MUYUN_USERNAME、MUYUN_PASSWORD 来确定初始化的用户名和密码
file-server:
upload-path: /Users/liurui/Downloads/uploads
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@QuarkusTest
Expand Down Expand Up @@ -164,6 +165,39 @@ void testDictCategoryAdd() {
});

assertEquals(response.size(), 3);
DictTreeNode node = response.get(0);
assertNotNull(node.getValue());

given()
.header("userID", config.superUserId())
.contentType("application/json")
.body(
Map.of(
"v_value", "031",
"v_name", "name31",
"pid", node.getId()
)
)
.when()
.post("%s/dict/update/%s/child/app_dict/create".formatted(base, "root1"))
.then()
.statusCode(200)
.extract()
.asString();

given()
.header("userID", config.superUserId())
.get("%s/dict/tree/%s".formatted(base, "root1"))
.then()
.statusCode(200)
.extract()
.as(new TypeRef<>() {
});

// assertEquals(response.size(), 3);
// node = response.get(0);
// assertEquals(node.getChildren().size(), 1);
// assertNotNull(node.getValue());

List<DictTreeNode> response2 = given()
.header("userID", config.superUserId())
Expand Down
1 change: 0 additions & 1 deletion muyun-boot/src/test/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
muyun:
debug: true
super-user-id: 1

quarkus:
Expand Down
1 change: 0 additions & 1 deletion muyun-core/src/main/java/net/ximatai/muyun/MuYunConst.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

public class MuYunConst {
public static final String API_REQUEST_CONTEXT_KEY = "apiRequest";
public static final String DEBUG_MODE_CONTEXT_KEY = "debug";
public static final String SESSION_USER_KEY = "user";
public static final String SSO_MODULE_NAME = "SSO";
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import net.ximatai.muyun.MuYunConst;
import net.ximatai.muyun.core.config.MuYunConfig;
import net.ximatai.muyun.model.ApiRequest;
import net.ximatai.muyun.model.IRuntimeUser;

import static net.ximatai.muyun.MuYunConst.DEBUG_MODE_CONTEXT_KEY;

/**
* 获取运行时上下文的能力
*/
public interface IRuntimeAbility {

RoutingContext getRoutingContext();

MuYunConfig getConfig();

default ApiRequest getApiRequest() {
try {
return getRoutingContext().get(MuYunConst.API_REQUEST_CONTEXT_KEY);
Expand All @@ -28,7 +29,7 @@ default IRuntimeUser getUser() {
Session session = getRoutingContext().session();
if (session != null && session.get(MuYunConst.SESSION_USER_KEY) != null) {
return session.get(MuYunConst.SESSION_USER_KEY);
} else if (getRoutingContext().<Boolean>get(DEBUG_MODE_CONTEXT_KEY)
} else if (getConfig().isTestMode() // 只有测试模式需要手动提供 userID 放在 Header里
&& getRoutingContext().request().getHeader("userID") != null) {
String userID = getRoutingContext().request().getHeader("userID");
return IRuntimeUser.build(userID);
Expand Down
12 changes: 12 additions & 0 deletions muyun-core/src/main/java/net/ximatai/muyun/core/Scaffold.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import net.ximatai.muyun.ability.IDatabaseAbility;
import net.ximatai.muyun.ability.IRuntimeAbility;
import net.ximatai.muyun.ability.ITableCreateAbility;
import net.ximatai.muyun.core.config.MuYunConfig;
import net.ximatai.muyun.database.IDatabaseOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -18,6 +19,17 @@ public abstract class Scaffold implements IDatabaseAbility, IRuntimeAbility {
private IDatabaseOperations databaseOperations;
private EventBus eventBus;
private RoutingContext routingContext;
private MuYunConfig config;

@Override
public MuYunConfig getConfig() {
return config;
}

@Inject
public void setConfig(MuYunConfig config) {
this.config = config;
}

@Inject
public void setRoutingContext(RoutingContext routingContext) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
package net.ximatai.muyun.core.config;

import io.smallrye.config.ConfigMapping;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;

import java.util.Objects;

@ConfigMapping(prefix = "muyun")
public interface MuYunConfig {
Boolean debug();

default ProfileMode profile() {
Config config = ConfigProvider.getConfig();
String upperCase = config.getValue("quarkus.profile", String.class).toUpperCase();
return ProfileMode.valueOf(upperCase);
}

default boolean isTestMode() {
return profile().equals(ProfileMode.TEST);
}

default boolean isProdMode() {
return profile().equals(ProfileMode.PROD);
}

default boolean isDevMode() {
return profile().equals(ProfileMode.DEV);
}

String superUserId();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package net.ximatai.muyun.core.config;

public enum ProfileMode {
DEV, PROD, TEST
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public Response toResponse(Exception e) {

String message = "服务器错误,请检查";

if (config.debug() && e.getMessage() != null) {
if (!config.isProdMode() && e.getMessage() != null) { // 非生产环境可以访问原始错误信息
message = e.getMessage();
}

Expand Down Expand Up @@ -74,4 +74,9 @@ public Response toResponse(Exception e) {
public RoutingContext getRoutingContext() {
return routingContext;
}

@Override
public MuYunConfig getConfig() {
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@

import java.io.IOException;

import static net.ximatai.muyun.MuYunConst.DEBUG_MODE_CONTEXT_KEY;

@Provider
@Priority(Priorities.AUTHENTICATION)
@ApplicationScoped
Expand All @@ -43,10 +41,6 @@ public void filter(ContainerRequestContext requestContext) throws IOException {
// 获取请求的路径
String path = requestContext.getUriInfo().getRequestUri().getPath();

if (config.debug()) {
routingContext.put(DEBUG_MODE_CONTEXT_KEY, true);
}

if (path.startsWith(restPath)) { //仅对 /api开头的请求做权限拦截
IRuntimeUser runtimeUser = this.getUser();
if ("/".equals(restPath)) {
Expand All @@ -69,4 +63,9 @@ public void filter(ContainerRequestContext requestContext) throws IOException {
public RoutingContext getRoutingContext() {
return routingContext;
}

@Override
public MuYunConfig getConfig() {
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import jakarta.ws.rs.ext.Provider;
import net.ximatai.muyun.MuYunConst;
import net.ximatai.muyun.ability.IRuntimeAbility;
import net.ximatai.muyun.core.config.MuYunConfig;
import net.ximatai.muyun.model.ApiRequest;
import net.ximatai.muyun.model.IRuntimeUser;
import net.ximatai.muyun.model.log.LogItem;
Expand Down Expand Up @@ -41,6 +42,9 @@ public class LogFilter implements ContainerRequestFilter, ContainerResponseFilte
@Inject
Instance<ILogLogin> iLogLogin;

@Inject
MuYunConfig config;

private static final Logger LOG = LoggerFactory.getLogger(LogFilter.class);

// 定义一个常量用于存储开始时间的键
Expand Down Expand Up @@ -144,4 +148,9 @@ private String getHost(ContainerRequestContext requestContext) {
public RoutingContext getRoutingContext() {
return routingContext;
}

@Override
public MuYunConfig getConfig() {
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public TreeNode setData(Map<String, Object> data) {
return this;
}

public TreeNode setChildren(List<TreeNode> children) {
this.children = children;
public TreeNode setChildren(List<? extends TreeNode> children) {
this.children = (List<TreeNode>) children;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,19 @@ public List<ChildTableInfo> getChildren() {
@Path("/tree/{id}")
public List<DictTreeNode> tree(@PathParam("id") String id) {
List<TreeNode> list = dictController.tree(id, false, null, null);
return list.stream().map(it -> DictTreeNode.from(it)
.setValue(it.getData().get("v_value").toString())).toList();
return nodeToDictNode(list);
}

private List<DictTreeNode> nodeToDictNode(List<? extends TreeNode> list) {
return list.stream().map(it -> {
DictTreeNode node = DictTreeNode.from(it)
.setValue(it.getData().get("v_value").toString());
List<TreeNode> children = node.getChildren();
if (children != null && !children.isEmpty()) {
node.setChildren(nodeToDictNode(children));
}
return node;
}).toList();
}

@GET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ public void fitOut(TableWrapper wrapper) {

@Override
protected void afterInit() {
if (muYunConfig.debug()) {
initData();
}
initData();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ public RoutingContext getRoutingContext() {
return routingContext;
}

@Override
public MuYunConfig getConfig() {
return config;
}

private List<TreeNode> filterMenuByAuth(List<TreeNode> list) {
String userID = getUser().getId();
Map<String, Set<String>> authorizedResources = authorizationService.getAuthorizedResources(userID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ public IRuntimeUser login(@QueryParam("username") String username, @QueryParam("
Map userInDB = (Map) pageResult.getList().getFirst();
String vPassword = userInDB.get("v_password").toString();
String encryptedPassword = encryptPassword(vPassword, code);
if ((config.debug() && password.equals(vPassword)) || password.equals(encryptedPassword)) {
if (password.equals(encryptedPassword)
|| (!config.isProdMode() && password.equals(vPassword))) { // 非生产环境允许使用非加密密码
if ((boolean) userInDB.get("b_enabled")) {
Map<String, ?> user = userInfoController.view((String) userInDB.get("id"));
IRuntimeUser runtimeUser = mapToUser(user);
Expand All @@ -121,7 +122,7 @@ private String encryptPassword(String password, String code) {
}

private RuntimeException verificationCode(String code) {
if (config.debug() && ALL_PURPOSE_CODE_FOR_DEBUG.equals(code)) {
if (!config.isDevMode() && ALL_PURPOSE_CODE_FOR_DEBUG.equals(code)) { // 非生产环境允许万能验证码
return null;
}

Expand Down Expand Up @@ -209,6 +210,11 @@ public RoutingContext getRoutingContext() {
return routingContext;
}

@Override
public MuYunConfig getConfig() {
return config;
}

private IRuntimeUser mapToUser(Map user) {
return new RuntimeUser()
.setUsername((String) user.get("v_username"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,16 @@ public ModuleConfig getModuleConfig() {
.addAction(new ModuleAction("setRoles", "设置角色", ModuleAction.TypeLike.UPDATE));
}

private static String promptForInput(Scanner scanner, String promptMessage) {
private String promptForInput(Scanner scanner, String promptMessage) {
if (config.isTestMode()) { // 单元测试模式,锁定用户名密码
return "admin";
}

String input;
do {
System.out.print(promptMessage);
input = scanner.nextLine().trim(); // 去掉输入前后的空格

if (input.isEmpty()) {
System.out.println("Input cannot be empty. Please try again.");
}
Expand Down
Loading

0 comments on commit 9a66929

Please sign in to comment.