记录项目配置,修改配置项的获取方式
- new class ` CommonEnvPostProcessor ` - remove ` @value ` - make JwtUtil's method static
This commit is contained in:
@@ -6,9 +6,9 @@ import cn.celess.common.entity.Response;
|
|||||||
import cn.celess.common.entity.dto.ArticleReq;
|
import cn.celess.common.entity.dto.ArticleReq;
|
||||||
import cn.celess.common.entity.vo.ArticleModel;
|
import cn.celess.common.entity.vo.ArticleModel;
|
||||||
import cn.celess.common.service.ArticleService;
|
import cn.celess.common.service.ArticleService;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import cn.celess.user.util.RedisUserUtil;
|
import cn.celess.user.util.RedisUserUtil;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
@@ -25,8 +25,6 @@ public class ArticleController {
|
|||||||
SitemapGenerateUtil sitemapGenerateUtil;
|
SitemapGenerateUtil sitemapGenerateUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
RedisUserUtil redisUserUtil;
|
RedisUserUtil redisUserUtil;
|
||||||
@Value("${spring.profiles.active}")
|
|
||||||
private String activeModel;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 新建一篇文章
|
* 新建一篇文章
|
||||||
@@ -37,7 +35,7 @@ public class ArticleController {
|
|||||||
@PostMapping("/admin/article/create")
|
@PostMapping("/admin/article/create")
|
||||||
public Response create(@RequestBody ArticleReq body) {
|
public Response create(@RequestBody ArticleReq body) {
|
||||||
ArticleModel articleModel = articleService.create(body);
|
ArticleModel articleModel = articleService.create(body);
|
||||||
if ("prod".equals(activeModel)) {
|
if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
|
||||||
sitemapGenerateUtil.createSitemap();
|
sitemapGenerateUtil.createSitemap();
|
||||||
}
|
}
|
||||||
return Response.success(articleModel);
|
return Response.success(articleModel);
|
||||||
@@ -52,7 +50,7 @@ public class ArticleController {
|
|||||||
@DeleteMapping("/admin/article/del")
|
@DeleteMapping("/admin/article/del")
|
||||||
public Response delete(@RequestParam("articleID") long articleId) {
|
public Response delete(@RequestParam("articleID") long articleId) {
|
||||||
boolean delete = articleService.delete(articleId);
|
boolean delete = articleService.delete(articleId);
|
||||||
if ("prod".equals(activeModel)) {
|
if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
|
||||||
sitemapGenerateUtil.createSitemap();
|
sitemapGenerateUtil.createSitemap();
|
||||||
}
|
}
|
||||||
return Response.success(delete);
|
return Response.success(delete);
|
||||||
@@ -67,7 +65,7 @@ public class ArticleController {
|
|||||||
@PutMapping("/admin/article/update")
|
@PutMapping("/admin/article/update")
|
||||||
public Response update(@RequestBody ArticleReq body) {
|
public Response update(@RequestBody ArticleReq body) {
|
||||||
ArticleModel update = articleService.update(body);
|
ArticleModel update = articleService.update(body);
|
||||||
if ("prod".equals(activeModel)) {
|
if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
|
||||||
sitemapGenerateUtil.createSitemap();
|
sitemapGenerateUtil.createSitemap();
|
||||||
}
|
}
|
||||||
return Response.success(update);
|
return Response.success(update);
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ package cn.celess.article.util;
|
|||||||
import cn.celess.common.entity.Article;
|
import cn.celess.common.entity.Article;
|
||||||
import cn.celess.common.mapper.ArticleMapper;
|
import cn.celess.common.mapper.ArticleMapper;
|
||||||
import cn.celess.common.util.DateFormatUtil;
|
import cn.celess.common.util.DateFormatUtil;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.scheduling.annotation.Async;
|
import org.springframework.scheduling.annotation.Async;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
@@ -38,9 +38,6 @@ public class SitemapGenerateUtil {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
ArticleMapper articleMapper;
|
ArticleMapper articleMapper;
|
||||||
|
|
||||||
@Value("${sitemap.path}")
|
|
||||||
private String path;
|
|
||||||
private Map<String, String> urlList;
|
private Map<String, String> urlList;
|
||||||
|
|
||||||
private static DocumentBuilder getDocumentBuilder() {
|
private static DocumentBuilder getDocumentBuilder() {
|
||||||
@@ -57,7 +54,8 @@ public class SitemapGenerateUtil {
|
|||||||
@Async
|
@Async
|
||||||
public void createSitemap() {
|
public void createSitemap() {
|
||||||
initList();
|
initList();
|
||||||
if ("".equals(path) || "classpath".equals(path)) {
|
String path = EnvironmentUtil.getProperties("sitemap.path", System.getProperty("user.dir"));
|
||||||
|
if ("classpath".equals(path)) {
|
||||||
path = System.getProperty("user.dir") + "/sitemap.xml";
|
path = System.getProperty("user.dir") + "/sitemap.xml";
|
||||||
}
|
}
|
||||||
File file = new File(path);
|
File file = new File(path);
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package cn.celess.common.config;
|
||||||
|
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.env.EnvironmentPostProcessor;
|
||||||
|
import org.springframework.boot.env.OriginTrackedMapPropertySource;
|
||||||
|
import org.springframework.boot.logging.DeferredLog;
|
||||||
|
import org.springframework.context.ApplicationEvent;
|
||||||
|
import org.springframework.context.ApplicationListener;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.env.ConfigurableEnvironment;
|
||||||
|
import org.springframework.core.env.PropertiesPropertySource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CommonEnvPostProcessor implements EnvironmentPostProcessor, ApplicationListener<ApplicationEvent>, Ordered {
|
||||||
|
public static final DeferredLog log = new DeferredLog();
|
||||||
|
|
||||||
|
private static final String CONFIG_PATH = "/config/blog.properties";
|
||||||
|
private static final String SOURCE_NAME = "localize";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
|
||||||
|
configurableEnvironment.getPropertySources().forEach(propertySource -> {
|
||||||
|
if (propertySource.getName().startsWith("applicationConfig") && propertySource instanceof OriginTrackedMapPropertySource) {
|
||||||
|
EnvironmentUtil.addProperties((Map<?, ?>) propertySource.getSource());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
log.info("加载本地配置文件");
|
||||||
|
//获取环境变量
|
||||||
|
String homeEnv = EnvironmentUtil.getEnv("BLOG_HOME", EnvironmentUtil.getEnv("USERPROFILE"));
|
||||||
|
String configPath = (homeEnv + CONFIG_PATH).replaceAll("[\\|/]+", Matcher.quoteReplacement(File.separator));
|
||||||
|
try (InputStream input = new FileInputStream(configPath)) {
|
||||||
|
Properties properties = new Properties();
|
||||||
|
properties.load(input);
|
||||||
|
PropertiesPropertySource propertySource = new PropertiesPropertySource(SOURCE_NAME, properties);
|
||||||
|
configurableEnvironment.getPropertySources().addLast(propertySource);
|
||||||
|
log.info("Load the configuration file under the environment variable,end.");
|
||||||
|
EnvironmentUtil.addProperties(properties);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.info("加载本地[" + configPath + "]的配置文件失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onApplicationEvent(ApplicationEvent event) {
|
||||||
|
log.replayTo(CommonEnvPostProcessor.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getOrder() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,10 @@ import cn.celess.common.constant.ResponseEnum;
|
|||||||
import cn.celess.common.entity.Response;
|
import cn.celess.common.entity.Response;
|
||||||
import cn.celess.common.service.MailService;
|
import cn.celess.common.service.MailService;
|
||||||
import cn.celess.common.util.DateFormatUtil;
|
import cn.celess.common.util.DateFormatUtil;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.mail.SimpleMailMessage;
|
import org.springframework.mail.SimpleMailMessage;
|
||||||
import org.springframework.validation.BindException;
|
import org.springframework.validation.BindException;
|
||||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||||
@@ -31,8 +31,6 @@ public class BlogExceptionHandler {
|
|||||||
MailService mailService;
|
MailService mailService;
|
||||||
@Autowired
|
@Autowired
|
||||||
HttpServletRequest request;
|
HttpServletRequest request;
|
||||||
@Value("${spring.profiles.active:dev}")
|
|
||||||
private String activeModel;
|
|
||||||
|
|
||||||
@ExceptionHandler(value = Exception.class)
|
@ExceptionHandler(value = Exception.class)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
@@ -65,7 +63,7 @@ public class BlogExceptionHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 发送错误信息到邮箱
|
// 发送错误信息到邮箱
|
||||||
if ("prod".equals(activeModel)) {
|
if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
|
||||||
logger.debug("有一个未捕获的bug,已发送到邮箱");
|
logger.debug("有一个未捕获的bug,已发送到邮箱");
|
||||||
sendMessage(e);
|
sendMessage(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package cn.celess.common.util;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class EnvironmentUtil {
|
||||||
|
|
||||||
|
private static final Properties properties = new Properties();
|
||||||
|
|
||||||
|
|
||||||
|
public static String getEnv(String name) {
|
||||||
|
String value = System.getenv(name);
|
||||||
|
if (StringUtils.isBlank(value)) {
|
||||||
|
log.error("没有找到环境变量:" + name);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getEnv(String name, String defaultValue) {
|
||||||
|
String env = getEnv(name);
|
||||||
|
if (env == null) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getProperties(String key) {
|
||||||
|
String value = properties.getProperty(key);
|
||||||
|
if (StringUtils.isBlank(value)) {
|
||||||
|
log.error("没有找到配置项: {}", key);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getProperties(String key, String defaultValue) {
|
||||||
|
return properties.getProperty(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void addProperties(Map<?, ?> map) {
|
||||||
|
properties.putAll(map);
|
||||||
|
}
|
||||||
|
}
|
||||||
2
blog-common/src/main/resources/META-INF/spring.factories
Normal file
2
blog-common/src/main/resources/META-INF/spring.factories
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
org.springframework.boot.env.EnvironmentPostProcessor=cn.celess.common.config.CommonEnvPostProcessor
|
||||||
|
org.springframework.context.ApplicationListener=cn.celess.common.config.CommonEnvPostProcessor
|
||||||
@@ -6,10 +6,14 @@ import org.springframework.boot.Banner;
|
|||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
import org.springframework.core.SpringVersion;
|
import org.springframework.core.SpringVersion;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.FilterType;
|
||||||
import org.springframework.scheduling.annotation.EnableAsync;
|
import org.springframework.scheduling.annotation.EnableAsync;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableAsync
|
@EnableAsync
|
||||||
|
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = "cn.celess.common.test.BaseRedisTest")})
|
||||||
public class BlogApplication {
|
public class BlogApplication {
|
||||||
public static final Logger logger = LoggerFactory.getLogger(BlogApplication.class);
|
public static final Logger logger = LoggerFactory.getLogger(BlogApplication.class);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package cn.celess.configuration;
|
package cn.celess.configuration;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.web.cors.CorsConfiguration;
|
import org.springframework.web.cors.CorsConfiguration;
|
||||||
@@ -14,8 +14,6 @@ import org.springframework.web.filter.CorsFilter;
|
|||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration
|
||||||
public class CorsConfig {
|
public class CorsConfig {
|
||||||
@Value("${spring.profiles.active}")
|
|
||||||
private String activeModel;
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public CorsFilter corsFilter() {
|
public CorsFilter corsFilter() {
|
||||||
@@ -26,7 +24,7 @@ public class CorsConfig {
|
|||||||
config.addAllowedOrigin("https://celess.cn");
|
config.addAllowedOrigin("https://celess.cn");
|
||||||
config.addAllowedOrigin("https://www.celess.cn");
|
config.addAllowedOrigin("https://www.celess.cn");
|
||||||
// 本地调试时的跨域
|
// 本地调试时的跨域
|
||||||
if (!"prod".equals(activeModel)) {
|
if (!"prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
|
||||||
config.addAllowedOrigin("http://localhost:4200");
|
config.addAllowedOrigin("http://localhost:4200");
|
||||||
config.addAllowedOrigin("http://127.0.0.1:4200");
|
config.addAllowedOrigin("http://127.0.0.1:4200");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package cn.celess.configuration;
|
package cn.celess.configuration;
|
||||||
|
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import com.alibaba.druid.pool.DruidDataSource;
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
@@ -11,26 +11,15 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration
|
||||||
public class DruidConfig {
|
public class DruidConfig {
|
||||||
@Value("${spring.datasource.url}")
|
|
||||||
private String dbUrl;
|
|
||||||
|
|
||||||
@Value("${spring.datasource.username}")
|
|
||||||
private String username;
|
|
||||||
|
|
||||||
@Value("${spring.datasource.password}")
|
|
||||||
private String password;
|
|
||||||
|
|
||||||
@Value("${spring.datasource.driver-class-name}")
|
|
||||||
private String driverClassName;
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public DruidDataSource druidDataSource() {
|
public DruidDataSource druidDataSource() {
|
||||||
DruidDataSource dataSource = new DruidDataSource();
|
DruidDataSource dataSource = new DruidDataSource();
|
||||||
dataSource.setDriverClassName(driverClassName);
|
dataSource.setDriverClassName(EnvironmentUtil.getProperties("spring.datasource.driver-class-name"));
|
||||||
// 数据库基本信息
|
// 数据库基本信息
|
||||||
dataSource.setUrl(dbUrl);
|
dataSource.setUrl(EnvironmentUtil.getProperties("spring.datasource.url"));
|
||||||
dataSource.setUsername(username);
|
dataSource.setUsername(EnvironmentUtil.getProperties("spring.datasource.username"));
|
||||||
dataSource.setPassword(password);
|
dataSource.setPassword(EnvironmentUtil.getProperties("spring.datasource.password"));
|
||||||
|
|
||||||
// 数据库连接池配置
|
// 数据库连接池配置
|
||||||
dataSource.setInitialSize(10);
|
dataSource.setInitialSize(10);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package cn.celess.configuration;
|
package cn.celess.configuration;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import springfox.documentation.builders.ApiInfoBuilder;
|
import springfox.documentation.builders.ApiInfoBuilder;
|
||||||
@@ -20,13 +20,10 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
|||||||
@EnableSwagger2
|
@EnableSwagger2
|
||||||
public class SwaggerConfig {
|
public class SwaggerConfig {
|
||||||
|
|
||||||
@Value("${spring.profiles.active}")
|
|
||||||
private String environment;
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public Docket createRestApi() {
|
public Docket createRestApi() {
|
||||||
return new Docket(DocumentationType.SWAGGER_2)
|
return new Docket(DocumentationType.SWAGGER_2)
|
||||||
.enable(!"prod".equals(environment))
|
.enable(!"prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev")))
|
||||||
.apiInfo(apiInfo())
|
.apiInfo(apiInfo())
|
||||||
.select()
|
.select()
|
||||||
.apis(RequestHandlerSelectors.basePackage("cn.celess"))
|
.apis(RequestHandlerSelectors.basePackage("cn.celess"))
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.celess.extension.serviceimpl;
|
|||||||
|
|
||||||
import cn.celess.common.entity.vo.QiniuResponse;
|
import cn.celess.common.entity.vo.QiniuResponse;
|
||||||
import cn.celess.common.service.QiniuService;
|
import cn.celess.common.service.QiniuService;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import com.qiniu.common.QiniuException;
|
import com.qiniu.common.QiniuException;
|
||||||
import com.qiniu.common.Zone;
|
import com.qiniu.common.Zone;
|
||||||
import com.qiniu.http.Response;
|
import com.qiniu.http.Response;
|
||||||
@@ -10,7 +11,6 @@ import com.qiniu.storage.Configuration;
|
|||||||
import com.qiniu.storage.UploadManager;
|
import com.qiniu.storage.UploadManager;
|
||||||
import com.qiniu.storage.model.FileInfo;
|
import com.qiniu.storage.model.FileInfo;
|
||||||
import com.qiniu.util.Auth;
|
import com.qiniu.util.Auth;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -26,14 +26,9 @@ public class QiniuServiceImpl implements QiniuService {
|
|||||||
private static BucketManager bucketManager;
|
private static BucketManager bucketManager;
|
||||||
private static Auth auth;
|
private static Auth auth;
|
||||||
|
|
||||||
@Value("${qiniu.accessKey}")
|
|
||||||
private String accessKey;
|
|
||||||
@Value("${qiniu.secretKey}")
|
|
||||||
private String secretKey;
|
|
||||||
@Value("${qiniu.bucket}")
|
|
||||||
private String bucket;
|
|
||||||
|
|
||||||
private void init() {
|
private void init() {
|
||||||
|
String accessKey = EnvironmentUtil.getProperties("qiniu.accessKey");
|
||||||
|
String secretKey = EnvironmentUtil.getProperties("qiniu.secretKey");
|
||||||
if (auth == null || uploadManager == null || bucketManager == null) {
|
if (auth == null || uploadManager == null || bucketManager == null) {
|
||||||
auth = Auth.create(accessKey, secretKey);
|
auth = Auth.create(accessKey, secretKey);
|
||||||
uploadManager = new UploadManager(cfg);
|
uploadManager = new UploadManager(cfg);
|
||||||
@@ -44,6 +39,7 @@ public class QiniuServiceImpl implements QiniuService {
|
|||||||
@Override
|
@Override
|
||||||
public QiniuResponse uploadFile(InputStream is, String fileName) {
|
public QiniuResponse uploadFile(InputStream is, String fileName) {
|
||||||
init();
|
init();
|
||||||
|
String bucket = EnvironmentUtil.getProperties("qiniu.bucket");
|
||||||
//文件存在则删除文件
|
//文件存在则删除文件
|
||||||
if (continueFile(fileName)) {
|
if (continueFile(fileName)) {
|
||||||
try {
|
try {
|
||||||
@@ -66,6 +62,7 @@ public class QiniuServiceImpl implements QiniuService {
|
|||||||
@Override
|
@Override
|
||||||
public FileInfo[] getFileList() {
|
public FileInfo[] getFileList() {
|
||||||
init();
|
init();
|
||||||
|
String bucket = EnvironmentUtil.getProperties("qiniu.bucket");
|
||||||
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
|
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
|
||||||
FileInfo[] items = null;
|
FileInfo[] items = null;
|
||||||
while (fileListIterator.hasNext()) {
|
while (fileListIterator.hasNext()) {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
spring.profiles.active=prod
|
spring.profiles.active=prod
|
||||||
####七牛的配置
|
####七牛的配置
|
||||||
####cn.celess.blog.service.serviceimpl.QiniuServiceImpl
|
####cn.celess.blog.service.serviceimpl.QiniuServiceImpl
|
||||||
logging.level.cn.celess.blog=debug
|
logging.level.cn.celess=info
|
||||||
logging.level.cn.celess.common.mapper=info
|
logging.level.cn.celess.common.mapper=info
|
||||||
spring.cache.type=redis
|
spring.cache.type=redis
|
||||||
mybatis.mapper-locations=classpath*:mapper/*.xml
|
mybatis.mapper-locations=classpath*:mapper/*.xml
|
||||||
|
|||||||
@@ -28,8 +28,6 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
|||||||
private static final String ROLE_ADMIN = "admin";
|
private static final String ROLE_ADMIN = "admin";
|
||||||
private static final String ROLE_USER = "user";
|
private static final String ROLE_USER = "user";
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtil jwtUtil;
|
|
||||||
@Autowired
|
|
||||||
RedisUtil redisUtil;
|
RedisUtil redisUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
UserService userService;
|
UserService userService;
|
||||||
@@ -41,9 +39,9 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
|||||||
int indexOf = path.indexOf("/", 1);
|
int indexOf = path.indexOf("/", 1);
|
||||||
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf);
|
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf);
|
||||||
String jwtStr = request.getHeader("Authorization");
|
String jwtStr = request.getHeader("Authorization");
|
||||||
if (jwtStr != null && !jwtStr.isEmpty() && !jwtUtil.isTokenExpired(jwtStr)) {
|
if (jwtStr != null && !jwtStr.isEmpty() && !JwtUtil.isTokenExpired(jwtStr)) {
|
||||||
// 已登录 记录当前email
|
// 已登录 记录当前email
|
||||||
request.getSession().setAttribute("email", jwtUtil.getUsernameFromToken(jwtStr));
|
request.getSession().setAttribute("email", JwtUtil.getUsernameFromToken(jwtStr));
|
||||||
}
|
}
|
||||||
// 不需要鉴权的路径
|
// 不需要鉴权的路径
|
||||||
if (!USER_PREFIX.equalsIgnoreCase(rootPath) && !ADMIN_PREFIX.equalsIgnoreCase(rootPath)) {
|
if (!USER_PREFIX.equalsIgnoreCase(rootPath) && !ADMIN_PREFIX.equalsIgnoreCase(rootPath)) {
|
||||||
@@ -53,11 +51,11 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
|||||||
if (jwtStr == null || jwtStr.isEmpty()) {
|
if (jwtStr == null || jwtStr.isEmpty()) {
|
||||||
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
|
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
|
||||||
}
|
}
|
||||||
if (jwtUtil.isTokenExpired(jwtStr)) {
|
if (JwtUtil.isTokenExpired(jwtStr)) {
|
||||||
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
||||||
}
|
}
|
||||||
String email = jwtUtil.getUsernameFromToken(jwtStr);
|
String email = JwtUtil.getUsernameFromToken(jwtStr);
|
||||||
if (jwtUtil.isTokenExpired(jwtStr)) {
|
if (JwtUtil.isTokenExpired(jwtStr)) {
|
||||||
// 登陆过期
|
// 登陆过期
|
||||||
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
||||||
}
|
}
|
||||||
@@ -67,7 +65,7 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
|||||||
String role = userService.getUserRoleByEmail(email);
|
String role = userService.getUserRoleByEmail(email);
|
||||||
if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) {
|
if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) {
|
||||||
// 更新token
|
// 更新token
|
||||||
String token = jwtUtil.updateTokenDate(jwtStr);
|
String token = JwtUtil.updateTokenDate(jwtStr);
|
||||||
response.setHeader("Authorization", token);
|
response.setHeader("Authorization", token);
|
||||||
}
|
}
|
||||||
if (role.equals(ROLE_ADMIN)) {
|
if (role.equals(ROLE_ADMIN)) {
|
||||||
|
|||||||
@@ -55,8 +55,6 @@ public class UserServiceImpl implements UserService {
|
|||||||
@Autowired
|
@Autowired
|
||||||
RedisUtil redisUtil;
|
RedisUtil redisUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtil jwtUtil;
|
|
||||||
@Autowired
|
|
||||||
RedisUserUtil redisUserUtil;
|
RedisUserUtil redisUserUtil;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -131,7 +129,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
|
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
|
||||||
// redis 标记
|
// redis 标记
|
||||||
redisUserUtil.set(user, loginReq.getIsRememberMe());
|
redisUserUtil.set(user, loginReq.getIsRememberMe());
|
||||||
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
|
token = JwtUtil.generateToken(user, loginReq.getIsRememberMe());
|
||||||
} else {
|
} else {
|
||||||
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
|
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
|
||||||
request.getSession().removeAttribute("code");
|
request.getSession().removeAttribute("code");
|
||||||
@@ -160,7 +158,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
if (token == null || token.isEmpty()) {
|
if (token == null || token.isEmpty()) {
|
||||||
return "注销登录成功";
|
return "注销登录成功";
|
||||||
}
|
}
|
||||||
String email = jwtUtil.getUsernameFromToken(token);
|
String email = JwtUtil.getUsernameFromToken(token);
|
||||||
if (redisUtil.hasKey(email + "-login")) {
|
if (redisUtil.hasKey(email + "-login")) {
|
||||||
redisUtil.delete(email + "-login");
|
redisUtil.delete(email + "-login");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,9 @@ package cn.celess.user.util;
|
|||||||
import cn.celess.common.constant.ResponseEnum;
|
import cn.celess.common.constant.ResponseEnum;
|
||||||
import cn.celess.common.entity.User;
|
import cn.celess.common.entity.User;
|
||||||
import cn.celess.common.exception.BlogResponseException;
|
import cn.celess.common.exception.BlogResponseException;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import io.jsonwebtoken.*;
|
import io.jsonwebtoken.*;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
@@ -18,7 +17,6 @@ import java.util.Map;
|
|||||||
* @Date: 2019/11/16 11:26
|
* @Date: 2019/11/16 11:26
|
||||||
* @Description: JWT工具类
|
* @Description: JWT工具类
|
||||||
*/
|
*/
|
||||||
@Component
|
|
||||||
@Log4j2
|
@Log4j2
|
||||||
public class JwtUtil {
|
public class JwtUtil {
|
||||||
/**
|
/**
|
||||||
@@ -32,36 +30,31 @@ public class JwtUtil {
|
|||||||
private static final String CLAIM_KEY_USERNAME = "sub";
|
private static final String CLAIM_KEY_USERNAME = "sub";
|
||||||
private static final String BEARER_PREFIX_UPPER = "Bearer";
|
private static final String BEARER_PREFIX_UPPER = "Bearer";
|
||||||
private static final String BEARER_PREFIX_LOWER = "bearer";
|
private static final String BEARER_PREFIX_LOWER = "bearer";
|
||||||
/**
|
|
||||||
* JWT 秘钥需自行设置不可泄露
|
|
||||||
*/
|
|
||||||
@Value("${jwt.secret}")
|
|
||||||
private String SECRET;
|
|
||||||
|
|
||||||
public String generateToken(User user, boolean isRemember) {
|
public static String generateToken(User user, boolean isRemember) {
|
||||||
Map<String, Object> claims = new HashMap<>(16);
|
Map<String, Object> claims = new HashMap<>(16);
|
||||||
claims.put(CLAIM_KEY_USERNAME, user.getEmail());
|
claims.put(CLAIM_KEY_USERNAME, user.getEmail());
|
||||||
|
|
||||||
return Jwts.builder()
|
return Jwts.builder()
|
||||||
.setClaims(claims)
|
.setClaims(claims)
|
||||||
.setExpiration(new Date(Instant.now().toEpochMilli() + (isRemember ? EXPIRATION_LONG_TIME : EXPIRATION_SHORT_TIME)))
|
.setExpiration(new Date(Instant.now().toEpochMilli() + (isRemember ? EXPIRATION_LONG_TIME : EXPIRATION_SHORT_TIME)))
|
||||||
.signWith(SignatureAlgorithm.HS512, SECRET)
|
.signWith(SignatureAlgorithm.HS512, EnvironmentUtil.getProperties("jwt.secret"))
|
||||||
.compact();
|
.compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String updateTokenDate(String token) {
|
public static String updateTokenDate(String token) {
|
||||||
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(getJwtString(token)).getBody();
|
Claims claims = Jwts.parser().setSigningKey(EnvironmentUtil.getProperties("jwt.secret")).parseClaimsJws(getJwtString(token)).getBody();
|
||||||
return Jwts.builder()
|
return Jwts.builder()
|
||||||
.setClaims(claims)
|
.setClaims(claims)
|
||||||
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
|
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
|
||||||
.signWith(SignatureAlgorithm.HS512, SECRET)
|
.signWith(SignatureAlgorithm.HS512, EnvironmentUtil.getProperties("jwt.secret"))
|
||||||
.compact();
|
.compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取token是否过期
|
* 获取token是否过期
|
||||||
*/
|
*/
|
||||||
public Boolean isTokenExpired(String token) {
|
public static Boolean isTokenExpired(String token) {
|
||||||
Date expiration = getExpirationDateFromToken(getJwtString(token));
|
Date expiration = getExpirationDateFromToken(getJwtString(token));
|
||||||
return expiration == null || expiration.before(new Date());
|
return expiration == null || expiration.before(new Date());
|
||||||
}
|
}
|
||||||
@@ -69,7 +62,7 @@ public class JwtUtil {
|
|||||||
/**
|
/**
|
||||||
* 根据token获取username
|
* 根据token获取username
|
||||||
*/
|
*/
|
||||||
public String getUsernameFromToken(String token) {
|
public static String getUsernameFromToken(String token) {
|
||||||
Claims claims = getClaimsFromToken(getJwtString(token));
|
Claims claims = getClaimsFromToken(getJwtString(token));
|
||||||
return claims == null ? null : claims.getSubject();
|
return claims == null ? null : claims.getSubject();
|
||||||
}
|
}
|
||||||
@@ -77,7 +70,7 @@ public class JwtUtil {
|
|||||||
/**
|
/**
|
||||||
* 获取token的过期时间
|
* 获取token的过期时间
|
||||||
*/
|
*/
|
||||||
public Date getExpirationDateFromToken(String token) {
|
public static Date getExpirationDateFromToken(String token) {
|
||||||
Claims claims = getClaimsFromToken(getJwtString(token));
|
Claims claims = getClaimsFromToken(getJwtString(token));
|
||||||
return claims == null ? null : claims.getExpiration();
|
return claims == null ? null : claims.getExpiration();
|
||||||
}
|
}
|
||||||
@@ -85,11 +78,11 @@ public class JwtUtil {
|
|||||||
/**
|
/**
|
||||||
* 解析JWT
|
* 解析JWT
|
||||||
*/
|
*/
|
||||||
private Claims getClaimsFromToken(String token) {
|
private static Claims getClaimsFromToken(String token) {
|
||||||
Claims claims = null;
|
Claims claims = null;
|
||||||
try {
|
try {
|
||||||
claims = Jwts.parser()
|
claims = Jwts.parser()
|
||||||
.setSigningKey(SECRET)
|
.setSigningKey(EnvironmentUtil.getProperties("jwt.secret"))
|
||||||
.parseClaimsJws(getJwtString(token))
|
.parseClaimsJws(getJwtString(token))
|
||||||
.getBody();
|
.getBody();
|
||||||
} catch (ExpiredJwtException e) {
|
} catch (ExpiredJwtException e) {
|
||||||
@@ -106,7 +99,7 @@ public class JwtUtil {
|
|||||||
return claims;
|
return claims;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getJwtString(String token) {
|
private static String getJwtString(String token) {
|
||||||
if (token == null) return token;
|
if (token == null) return token;
|
||||||
return token.replaceFirst(BEARER_PREFIX_UPPER, "").replace(BEARER_PREFIX_LOWER, "");
|
return token.replaceFirst(BEARER_PREFIX_UPPER, "").replace(BEARER_PREFIX_LOWER, "");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,6 @@ public class RedisUserUtil {
|
|||||||
@Autowired
|
@Autowired
|
||||||
RedisUtil redisUtil;
|
RedisUtil redisUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtil jwtUtil;
|
|
||||||
@Autowired
|
|
||||||
HttpServletRequest request;
|
HttpServletRequest request;
|
||||||
|
|
||||||
public User get() {
|
public User get() {
|
||||||
@@ -39,7 +37,7 @@ public class RedisUserUtil {
|
|||||||
if (token == null || token.isEmpty()) {
|
if (token == null || token.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
String email = jwtUtil.getUsernameFromToken(token);
|
String email = JwtUtil.getUsernameFromToken(token);
|
||||||
return new ObjectMapper().readValue(redisUtil.get(email + "-login"), User.class);
|
return new ObjectMapper().readValue(redisUtil.get(email + "-login"), User.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
package cn.celess.user.util;
|
package cn.celess.user.util;
|
||||||
|
|
||||||
import cn.celess.common.entity.User;
|
import cn.celess.common.entity.User;
|
||||||
|
import cn.celess.common.util.EnvironmentUtil;
|
||||||
import cn.celess.user.UserBaseTest;
|
import cn.celess.user.UserBaseTest;
|
||||||
import io.jsonwebtoken.Jwts;
|
import io.jsonwebtoken.Jwts;
|
||||||
import io.jsonwebtoken.SignatureAlgorithm;
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
import org.junit.FixMethodOrder;
|
import org.junit.FixMethodOrder;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runners.MethodSorters;
|
import org.junit.runners.MethodSorters;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
@@ -18,20 +17,15 @@ import static org.junit.Assert.*;
|
|||||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
public class JwtUtilTest extends UserBaseTest {
|
public class JwtUtilTest extends UserBaseTest {
|
||||||
|
|
||||||
@Resource
|
|
||||||
JwtUtil jwtUtil;
|
|
||||||
@Value("${jwt.secret}")
|
|
||||||
private String secret;
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenerateToken() {
|
public void testGenerateToken() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
user.setEmail("a@celess.cn");
|
||||||
String s = jwtUtil.generateToken(user, false);
|
String s = JwtUtil.generateToken(user, false);
|
||||||
assertNotNull(s);
|
assertNotNull(s);
|
||||||
String str = null;
|
String str = null;
|
||||||
try {
|
try {
|
||||||
str = jwtUtil.generateToken(null, false);
|
str = JwtUtil.generateToken(null, false);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
@@ -43,38 +37,38 @@ public class JwtUtilTest extends UserBaseTest {
|
|||||||
String s = Jwts.builder()
|
String s = Jwts.builder()
|
||||||
.setClaims(null)
|
.setClaims(null)
|
||||||
.setExpiration(new Date(Instant.now().toEpochMilli() + 1000))
|
.setExpiration(new Date(Instant.now().toEpochMilli() + 1000))
|
||||||
.signWith(SignatureAlgorithm.HS512, secret)
|
.signWith(SignatureAlgorithm.HS512, EnvironmentUtil.getProperties("jwt.secret"))
|
||||||
.compact();
|
.compact();
|
||||||
Thread.sleep(1010);
|
Thread.sleep(1010);
|
||||||
assertTrue(jwtUtil.isTokenExpired(s));
|
assertTrue(JwtUtil.isTokenExpired(s));
|
||||||
assertFalse(jwtUtil.isTokenExpired(jwtUtil.generateToken(new User(), false)));
|
assertFalse(JwtUtil.isTokenExpired(JwtUtil.generateToken(new User(), false)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetUsernameFromToken() {
|
public void testGetUsernameFromToken() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
user.setEmail("a@celess.cn");
|
||||||
String s = jwtUtil.generateToken(user, false);
|
String s = JwtUtil.generateToken(user, false);
|
||||||
assertEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
|
assertEquals(user.getEmail(), JwtUtil.getUsernameFromToken(s));
|
||||||
user.setEmail("example@celess.cn");
|
user.setEmail("example@celess.cn");
|
||||||
assertNotEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
|
assertNotEquals(user.getEmail(), JwtUtil.getUsernameFromToken(s));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetExpirationDateFromToken() {
|
public void testGetExpirationDateFromToken() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
user.setEmail("a@celess.cn");
|
||||||
String s = jwtUtil.generateToken(user, false);
|
String s = JwtUtil.generateToken(user, false);
|
||||||
assertNotNull(jwtUtil.getExpirationDateFromToken(s));
|
assertNotNull(JwtUtil.getExpirationDateFromToken(s));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void updateTokenDate() {
|
public void updateTokenDate() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
user.setEmail("a@celess.cn");
|
||||||
String s = jwtUtil.generateToken(user, false);
|
String s = JwtUtil.generateToken(user, false);
|
||||||
Date before = jwtUtil.getExpirationDateFromToken(s);
|
Date before = JwtUtil.getExpirationDateFromToken(s);
|
||||||
String s1 = jwtUtil.updateTokenDate(s);
|
String s1 = JwtUtil.updateTokenDate(s);
|
||||||
assertTrue(jwtUtil.getExpirationDateFromToken(s1).getTime() - jwtUtil.getExpirationDateFromToken(s).getTime() > 0);
|
assertTrue(JwtUtil.getExpirationDateFromToken(s1).getTime() - JwtUtil.getExpirationDateFromToken(s).getTime() > 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user