Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE t_user
ADD COLUMN use_tenant_id INT AFTER private_key ;
2 changes: 0 additions & 2 deletions app/src/main/resources/sql/h2/init_data_for_test_v1.0.0.sql

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE t_user
ADD COLUMN use_tenant_id INT AFTER private_key ;

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,17 @@ public enum ExceptionEnum implements IBaseError {
/**
* Cm 339 exception enum.
*/
CM339("CM339", "token检验失败,请重新登录");
CM339("CM339", "token检验失败,请重新登录"),

/**
* Cm 340 exception enum.
*/
CM340("CM340", "请求资源不存在"),

/**
* Cm 341 exception enum.
*/
CM341("CM341", "组织在当前用户组织列表中匹配不到");
/**
* 错误码
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public class AiChatController {
@SystemControllerLog(description = "AI chat")
@PostMapping("/ai/chat")
public ResponseEntity<?> aiChat(@RequestBody ChatRequest request,
@RequestHeader(value = "Authorization", required = false) String authorization) throws Exception {
@RequestHeader(value = "Authorization", required = true) String authorization) throws Exception {

if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.replace("Bearer ", "");
Expand Down Expand Up @@ -117,7 +117,7 @@ public ResponseEntity<?> aiChat(@RequestBody ChatRequest request,
@SystemControllerLog(description = "AI completions")
@PostMapping("/chat/completions")
public ResponseEntity<?> completions(@RequestBody ChatRequest request,
@RequestHeader(value = "Authorization", required = false) String authorization) throws Exception {
@RequestHeader(value = "Authorization", required = true) String authorization) throws Exception {
if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.replace("Bearer ", "");
request.setApiKey(token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ public Result<User> me() {
user.setUsername(loginUserContext.getLoginUserId());
}
user.setTenant(tenants);

user.setPassword(null);
user.setPrivateKey(null);
user.setPublicKey(null);
user.setSalt(null);
return Result.success(user);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ public void addInterceptors(InterceptorRegistry registry) {
// 登录相关
"/platform-center/api/user/login",
// 忘记密码
"/platform-center/api/user/forgot-password"
"/platform-center/api/user/forgot-password",
// AI
"/app-center/api/ai/chat",
"/app-center/api/chat/completions"
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.tinyengine.it.login.utils.JwtUtil;
import com.tinyengine.it.login.config.context.DefaultLoginUserContext;
import com.tinyengine.it.login.model.UserInfo;
import com.tinyengine.it.mapper.AuthUsersUnitsRolesMapper;
import com.tinyengine.it.model.entity.Tenant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -36,12 +37,14 @@ public class SSOInterceptor implements HandlerInterceptor {

@Autowired
private JwtUtil jwtUtil;

@Autowired
AuthUsersUnitsRolesMapper authUsersUnitsRolesMapper;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {

String authorization = request.getHeader("Authorization");
String org = request.getHeader("X-Lowcode-Org");
// 如果没有token,重定向到登录页
if (authorization == null || authorization.isEmpty()) {
log.info("No token");
Expand All @@ -62,7 +65,6 @@ public boolean preHandle(HttpServletRequest request,
// 从token中获取用户信息
String username = jwtUtil.getUsernameFromToken(token);
String userId = jwtUtil.getUserIdFromToken(token);
List<Tenant> tenants = jwtUtil.getTenantIdFromToken(token);
String roles = jwtUtil.getRolesFromToken(token);
Integer platformId = jwtUtil.getPlatformIdFromToken(token);

Expand All @@ -72,7 +74,21 @@ public boolean preHandle(HttpServletRequest request,
log.warn("User information is incomplete - username: {}, userId: {}", username, userId);
throw new ServiceException(ExceptionEnum.CM339.getResultCode(), ExceptionEnum.CM339.getResultMsg());
}

List<Tenant> tenants= authUsersUnitsRolesMapper.queryAllTenantByUserId(Integer.valueOf(userId));

if(!"null".equals(org) && org != null){
boolean findOrg = false;
for (Tenant tenant : tenants) {
tenant.setIsInUse(tenant.getId().equals(org));
if(tenant.getIsInUse()){
findOrg = true;
}
}
if(!findOrg){
log.warn("X-Lowcode-Org not found in user's tenants - X-Lowcode-Org: {}", org);
throw new ServiceException(ExceptionEnum.CM341.getResultCode(), ExceptionEnum.CM341.getResultMsg());
}
}
// 存储用户信息到LoginUserContext
UserInfo userInfo = new UserInfo(userId, username, tenants);

Expand All @@ -88,7 +104,7 @@ public boolean preHandle(HttpServletRequest request,
} catch (Exception e) {
log.error("Token validation exception: {}", e.getMessage(), e);
DefaultLoginUserContext.clear();
throw new ServiceException(ExceptionEnum.CM339.getResultCode(), ExceptionEnum.CM339.getResultMsg());
throw new ServiceException(ExceptionEnum.CM339.getResultCode(), e.getMessage());
}
}

Expand All @@ -97,6 +113,7 @@ public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// 请求完成后清理用户上下文
DefaultLoginUserContext.clear();

log.debug("Cleared user context for request completion");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public class DefaultLoginUserContext implements LoginUserContext {
private static final int DEFAULT_PLATFORM = 1;
private static final String DEFAULT_TENANT = "1";



/**
* 返回当前用户所在的业务租户id
*
Expand All @@ -31,11 +33,15 @@ public String getTenantId() {
return DEFAULT_TENANT;
}
for (Tenant tenant : tenantList) {
if (tenant.getIsInUse()) {
return tenant.getId();
if(tenant.getIsInUse()!=null){
if (tenant.getIsInUse()) {
return tenant.getId();
}
}else{
return tenantList.get(0).getId();
}
}

}
return DEFAULT_TENANT;
}

Expand Down Expand Up @@ -69,6 +75,7 @@ public void setTenants(List<Tenant> tenants) {
CURRENT_USER.set(userInfo);
}


/**
* 设置当前用户信息
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@
import com.tinyengine.it.common.context.LoginUserContext;
import com.tinyengine.it.common.exception.ExceptionEnum;
import com.tinyengine.it.common.log.SystemControllerLog;
import com.tinyengine.it.login.model.*;
import com.tinyengine.it.login.utils.JwtUtil;
import com.tinyengine.it.login.utils.SM3PasswordUtil;
import com.tinyengine.it.login.config.context.DefaultLoginUserContext;
import com.tinyengine.it.login.model.PasswordResult;
import com.tinyengine.it.login.model.PasswordValidationResult;
import com.tinyengine.it.login.model.SSOTicket;
import com.tinyengine.it.login.model.ValidationResult;
import com.tinyengine.it.login.service.ConfigurablePasswordValidator;
import com.tinyengine.it.login.service.LoginService;
import com.tinyengine.it.login.service.TokenBlacklistService;
Expand All @@ -31,8 +28,6 @@
import com.tinyengine.it.model.entity.Tenant;
import com.tinyengine.it.model.entity.User;
import com.tinyengine.it.service.app.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
Expand Down Expand Up @@ -238,10 +233,12 @@ public Result<ValidationResult> validateToken(@RequestParam String token) {
@SystemControllerLog(description = "设置当前组织")
@GetMapping("/user/tenant")
public Result<SSOTicket> setTenant(@RequestParam Integer tenantId) {
List<Tenant> tenants = loginUserContext.getTenants();
List<Tenant> tenants = authUsersUnitsRolesMapper.queryAllTenantByUserId(Integer.valueOf(loginUserContext.getLoginUserId()));

if (tenantId == null) {
return Result.failed(ExceptionEnum.CM320);
}

if (tenants == null || tenants.isEmpty()) {
return Result.failed(ExceptionEnum.CM337);
}
Expand All @@ -259,30 +256,25 @@ public Result<SSOTicket> setTenant(@RequestParam Integer tenantId) {
}

if (!found) {
return Result.failed(ExceptionEnum.CM337);
return Result.failed(ExceptionEnum.CM341);
}
//存储当前组织到LoginUserContext
UserInfo currentUser = DefaultLoginUserContext.getCurrentUser();
currentUser.setTenants(tenantList);
DefaultLoginUserContext.setCurrentUser(currentUser);

// 通过 RequestContextHolder 获取请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
String authHeader = request.getHeader("Authorization");
String headerToken = jwtUtil.getTokenFromRequest(authHeader);
String headerToken = jwtUtil.getTokenFromRequest(authHeader);
if (headerToken == null || headerToken.isEmpty()) {
return Result.failed(ExceptionEnum.CM336);
}
String token = jwtUtil.generateTokenWithSelectedTenant(headerToken, tenantList);
// 将原 token 加入黑名单
Claims claims = Jwts.parser()
.verifyWith(JwtUtil.getSecretKey())
.build()
.parseSignedClaims(headerToken)
.getPayload();

long expiryTime = claims.getExpiration().getTime();
tokenBlacklistService.blacklistToken(headerToken, expiryTime);
// 创建SSO票据
SSOTicket ticket = new SSOTicket();
ticket.setToken(token);
ticket.setToken(headerToken);
ticket.setUsername(DefaultLoginUserContext.getCurrentUser().getUsername());
ticket.setExpireTime(System.currentTimeMillis() + 3600000);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinyengine.it.common.base.Result;
import com.tinyengine.it.common.context.LoginUserContext;
import com.tinyengine.it.common.exception.ExceptionEnum;
import com.tinyengine.it.common.exception.ServiceException;
import com.tinyengine.it.login.service.LoginService;
Expand Down Expand Up @@ -42,6 +43,9 @@ public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements L
@Autowired
AuthUsersUnitsRolesMapper authUsersUnitsRolesMapper;

@Autowired
LoginUserContext loginUserContext;

/**
* 新增表t_user数据
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,11 @@ public AppDto queryAllAppByPage(Integer currentPage, Integer pageSize, String or
pageSize = 1000; // 限制最大页大小
}
int offset = (currentPage - 1) * pageSize;
String tenantId = loginUserContext.getTenantId();
List<App> apps = this.baseMapper.queryAllAppByPage(pageSize, offset, app.getName(),
app.getIndustryId(), app.getSceneId(), app.getFramework(), orderBy, app.getCreatedBy(),
loginUserContext.getTenantId());
Integer total = this.baseMapper.queryAppTotal(loginUserContext.getTenantId());
tenantId);
Integer total = this.baseMapper.queryAppTotal(tenantId);
AppDto appDto = new AppDto();
appDto.setApps(apps);
appDto.setTotal(total);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,18 +495,16 @@ public Page addIsHome(Page pageInfo) {
* @return the app home page id
*/
public int getAppHomePageId(int appId) {
log.info("Getting home page ID for appId: {}, TenantId: {}", appId, loginUserContext.getTenantId());
App appInfo = appMapper.queryAppById(appId, loginUserContext.getTenantId());
// appHomePageId 存在为null的情况,即app没有设置首页
Integer homePage = appInfo.getHomePage();

// 将 homePage 转换为整数,如果为空则默认为 0
int id;
if (homePage == null) {
id = 0;
return id;
if (appInfo == null) {
throw new ServiceException(ExceptionEnum.CM340.getResultCode(), "App not found for ID: " + appId+",TenantId:"+loginUserContext.getTenantId());
}
id = homePage;
return id;
// 将 homePage 转换为整数,如果为空则默认为 0
Integer homePage = appInfo.getHomePage();
log.info("Retrieved home page ID: {} for appId: {}", homePage, appId);
return homePage != null ? homePage : 0;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,9 @@ private List<PackagesDto> getPackages() {
* @return the meta
*/
public MetaDto getMetaDto(Integer id) {
App app = appMapper.queryAppById(id, loginUserContext.getTenantId());
String tenantId = loginUserContext.getTenantId();
log.info("Getting login user tenant id: {}", tenantId);
App app = appMapper.queryAppById(id, tenantId);
if (app == null) {
throw new ServiceException(ExceptionEnum.CM009.getResultCode(), ExceptionEnum.CM009.getResultMsg());
}
Expand Down
7 changes: 6 additions & 1 deletion base/src/main/resources/mappers/UserMapper.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
<!-- 通用查询列 -->
<sql id="Base_Column_List">
id
, username, password, email, salt, public_key, private_key, enable, created_time, last_updated_time,
, username, password, email, salt, public_key, private_key,enable, created_time, last_updated_time,
is_admin, is_public
</sql>

<!-- 通用条件列 -->
<sql id="UserByCondition">
<if test="id!=null and id!=''">
AND id = #{id}
</if>
<if test="username!=null and username!=''">
AND username = #{username}
</if>
Expand Down Expand Up @@ -77,6 +80,7 @@
<if test="isPublic!=null">
is_public = #{isPublic},
</if>

</sql>


Expand All @@ -93,6 +97,7 @@
<result column="last_updated_time" property="lastUpdatedTime"/>
<result column="is_admin" property="isAdmin"/>
<result column="is_public" property="isPublic"/>

</resultMap>

<!-- 查询表t_user所有数据 -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE t_user
ADD COLUMN use_tenant_id INT AFTER private_key ;
Loading
Loading