Skip to content

Commit

Permalink
Merge pull request #156 from jamebal/i18n
Browse files Browse the repository at this point in the history
feat: add i18n config
  • Loading branch information
jamebal authored Sep 26, 2024
2 parents 058989a + 17e3814 commit 1001516
Show file tree
Hide file tree
Showing 14 changed files with 413 additions and 90 deletions.
19 changes: 19 additions & 0 deletions src/main/java/com/jmal/clouddisk/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,20 @@

import com.jmal.clouddisk.interceptor.AuthInterceptor;
import com.jmal.clouddisk.interceptor.FileInterceptor;
import com.jmal.clouddisk.interceptor.HeaderLocaleChangeInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import java.io.File;
import java.util.Locale;

/**
* WebConfig
Expand All @@ -33,6 +38,7 @@ public class WebConfig implements WebMvcConfigurer {
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(authInterceptor).addPathPatterns("/**").
excludePathPatterns("/login/**", "/public/**", "/articles/**", "/error/**", "/file/**" , "/files/**","/swagger-ui/**");
registry.addInterceptor(fileInterceptor).addPathPatterns("/file/**").addPathPatterns("/files/**");
Expand Down Expand Up @@ -69,4 +75,17 @@ public void configureAsyncSupport(@NotNull AsyncSupportConfigurer configurer) {
// configurer.setDefaultTimeout(3000);
WebMvcConfigurer.super.configureAsyncSupport(configurer);
}

@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver resolver = new CookieLocaleResolver("locale");
resolver.setDefaultLocale(Locale.US);
return resolver;
}

@Bean
public HeaderLocaleChangeInterceptor localeChangeInterceptor() {
return new HeaderLocaleChangeInterceptor();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public void heartbeat() {
emitters.forEach((uuid, emitter) -> {
try {
emitter.send("h");
} catch (IOException ignored) {
} catch (IOException | IllegalStateException ignored) {
}
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.jmal.clouddisk.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.Locale;

public class HeaderLocaleChangeInterceptor extends LocaleChangeInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
String lang = request.getHeader("lang");
if (StrUtil.isNotBlank(lang) && lang.indexOf("_") > 0) {
Locale locale = Locale.forLanguageTag(lang.replace("_", "-"));
LocaleContextHolder.setLocale(locale);
} else {
LocaleContextHolder.setLocale(Locale.US);
}
return true;
}
}
8 changes: 4 additions & 4 deletions src/main/java/com/jmal/clouddisk/model/rbac/MenuDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class MenuDTO implements Comparable<MenuDTO>{
@Schema(name = "parentId", title = "父级菜单Id")
String parentId;
@NotNull(message = "菜单名称不能为空")
@Schema(name = "name", title = "菜单名称", required = true)
@Schema(name = "name", title = "菜单名称", requiredMode = Schema.RequiredMode.REQUIRED)
String name;
@Schema(name = "authority", title = "权限标识")
String authority;
Expand All @@ -37,13 +37,13 @@ public class MenuDTO implements Comparable<MenuDTO>{
@Schema(name = "icon", title = "菜单图标")
String icon;
@NotNull(message = "排序号不能为空")
@Schema(name = "sortNumber", title = "排序号", required = true)
@Schema(name = "sortNumber", title = "排序号", requiredMode = Schema.RequiredMode.REQUIRED)
Integer sortNumber;
@NotNull(message = "菜单类型不能为空")
@Schema(name = "menuType", title = "菜单类型 0:菜单,1:按钮", required = true)
@Schema(name = "menuType", title = "菜单类型 0:菜单,1:按钮", requiredMode = Schema.RequiredMode.REQUIRED)
Integer menuType;
@NotNull(message = "是否隐藏不能为空")
@Schema(name = "hide", title = "是否隐藏", required = true)
@Schema(name = "hide", title = "是否隐藏", requiredMode = Schema.RequiredMode.REQUIRED)
Boolean hide;
/***
* 子菜单
Expand Down
23 changes: 12 additions & 11 deletions src/main/java/com/jmal/clouddisk/service/impl/AuthServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@
import com.jmal.clouddisk.model.rbac.ConsumerDTO;
import com.jmal.clouddisk.service.IAuthService;
import com.jmal.clouddisk.service.IUserService;
import com.jmal.clouddisk.util.CaffeineUtil;
import com.jmal.clouddisk.util.PasswordHash;
import com.jmal.clouddisk.util.ResponseResult;
import com.jmal.clouddisk.util.ResultUtil;
import com.jmal.clouddisk.util.*;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -54,7 +51,11 @@ public class AuthServiceImpl implements IAuthService {

private final IUserService userService;

private static final String LOGIN_ERROR = "用户名或密码错误";
private final MessageUtil messageUtil;

public String loginError() {
return messageUtil.getMessage("login.error");
}

@PostConstruct
private void init() {
Expand Down Expand Up @@ -94,14 +95,14 @@ public ResponseResult<Object> login(HttpServletResponse response, ConsumerDTO co
// ldap登录
return ldapLogin(response, consumerDTO);
}
return ResultUtil.error(LOGIN_ERROR);
return ResultUtil.error(loginError());
} else {
String hashPassword = consumerDO.getPassword();
if (!CharSequenceUtil.isBlank(password) && PasswordHash.validatePassword(password, hashPassword)) {
return loginValidSuccess(response, consumerDTO, consumerDO);
}
}
return ResultUtil.error(LOGIN_ERROR);
return ResultUtil.error(loginError());
}

private static ResponseResult<Object> loginValidSuccess(HttpServletResponse response, ConsumerDTO userDTO, ConsumerDO consumerDO) {
Expand All @@ -122,7 +123,7 @@ private ResponseResult<Object> ldapLogin(HttpServletResponse response, ConsumerD
LdapQuery query = LdapQueryBuilder.query().where(ldapLoginName).is(consumerDTO.getUsername());
ldapTemplate.authenticate(query, consumerDTO.getPassword());
} catch (Exception e) {
return ResultUtil.error(LOGIN_ERROR);
return ResultUtil.error(loginError());
}
LdapConfigDO ldapConfigDO = mongoTemplate.findOne(new Query(), LdapConfigDO.class);
if (ldapConfigDO != null) {
Expand All @@ -132,7 +133,7 @@ private ResponseResult<Object> ldapLogin(HttpServletResponse response, ConsumerD
ConsumerDO consumerDO = userService.add(consumerDTO);
return loginValidSuccess(response, consumerDTO, consumerDO);
}
return ResultUtil.error(LOGIN_ERROR);
return ResultUtil.error(loginError());
}

/**
Expand Down Expand Up @@ -163,14 +164,14 @@ public ResponseResult<Object> logout(String token, HttpServletResponse response)
public ResponseResult<Object> validOldPass(String userId, String password) {
ConsumerDO user = mongoTemplate.findById(userId, ConsumerDO.class, UserServiceImpl.COLLECTION_NAME);
if (user == null) {
return ResultUtil.warning(LOGIN_ERROR);
return ResultUtil.warning(loginError());
} else {
String userPassword = user.getPassword();
if (!CharSequenceUtil.isBlank(password) && PasswordHash.validatePassword(password, userPassword)) {
return ResultUtil.success();
}
}
return ResultUtil.warning(LOGIN_ERROR);
return ResultUtil.warning(loginError());
}

@Override
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/jmal/clouddisk/service/impl/MenuService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@
import com.jmal.clouddisk.model.rbac.MenuDO;
import com.jmal.clouddisk.model.rbac.MenuDTO;
import com.jmal.clouddisk.service.IUserService;
import com.jmal.clouddisk.util.MongoUtil;
import com.jmal.clouddisk.util.ResponseResult;
import com.jmal.clouddisk.util.ResultUtil;
import com.jmal.clouddisk.util.TimeUntils;
import com.jmal.clouddisk.util.*;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
Expand All @@ -29,6 +27,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
* @Description 菜单管理
Expand All @@ -50,6 +49,9 @@ public class MenuService {
@Autowired
private MongoTemplate mongoTemplate;

@Autowired
private MessageUtil messageUtil;

@PostConstruct
public void init() {
// 启动时更新菜单
Expand Down Expand Up @@ -98,9 +100,11 @@ public List<MenuDTO> tree(QueryMenuDTO queryDTO) {
query.addCriteria(Criteria.where("component").regex(queryDTO.getPath(), "i"));
}
List<MenuDO> menuDOList = mongoTemplate.find(query, MenuDO.class, COLLECTION_NAME);
Locale locale = LocaleContextHolder.getLocale();
List<MenuDTO> menuDTOList = menuDOList.parallelStream().map(menuDO -> {
MenuDTO menuDTO = new MenuDTO();
BeanUtils.copyProperties(menuDO, menuDTO);
menuDTO.setName(messageUtil.getMessage(menuDO.getName(), locale));
return menuDTO;
}).toList();
return getSubMenu(null, menuDTOList);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public class RoleService {
@Autowired
private IUserService userService;

@Autowired
private MessageUtil messageUtil;

/***
* 角色列表
* @param queryDTO 角色查询条件
Expand All @@ -68,6 +71,11 @@ public ResponseResult<List<RoleDTO>> list(QueryRoleDTO queryDTO) {
query.addCriteria(Criteria.where("remarks").regex(queryDTO.getRemarks(), "i"));
}
List<RoleDTO> roleDTOList = mongoTemplate.find(query, RoleDTO.class, COLLECTION_NAME);
// to i18n
roleDTOList = roleDTOList.stream().peek(roleDTO -> {
roleDTO.setName(messageUtil.getMessage(roleDTO.getName()));
roleDTO.setRemarks(messageUtil.getMessage(roleDTO.getRemarks()));
}).collect(Collectors.toList());
return ResultUtil.success(roleDTOList).setCount(count);
}

Expand Down
41 changes: 41 additions & 0 deletions src/main/java/com/jmal/clouddisk/util/MessageUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.jmal.clouddisk.util;

import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
@RequiredArgsConstructor
public class MessageUtil {

private final MessageSource messageSource;

/**
* 获取国际化消息
* @param messageKey 消息的键
* @return 国际化消息
*/
public String getMessage(String messageKey) {
return getMessage(messageKey, LocaleContextHolder.getLocale());
}

/**
* 获取国际化消息
* @param messageKey 消息的键
* @param locale 语言
* @return 国际化消息
*/
public String getMessage(String messageKey, Locale locale) {
String result = messageKey;
try {
result = messageSource.getMessage(messageKey, null, locale);
} catch (NoSuchMessageException ignored) {
}
return result;
}

}
3 changes: 3 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ spring:
type: caffeine
caffeine:
spec: initialCapacity=100,maximumSize=500,expireAfterWrite=3600s
messages:
basename: i18n/messages
encoding: UTF-8
springdoc:
packages-to-scan: com.jmal.clouddisk.controller,com.jmal.clouddisk.oss
api-docs:
Expand Down
Loading

0 comments on commit 1001516

Please sign in to comment.