Commit bf7c1eeb authored by dqjdda's avatar dqjdda
Browse files

代码优化完成,去除大量idea警告,代码生成器优化等

parent e3c3ebb1
package me.zhengjie.modules.monitor.service;
import org.springframework.scheduling.annotation.Async;
import javax.servlet.http.HttpServletRequest;
/**
......@@ -17,20 +16,20 @@ public interface VisitsService {
/**
* 新增记录
* @param request
* @param request /
*/
@Async
void count(HttpServletRequest request);
/**
* 获取数据
* @return
* @return /
*/
Object get();
/**
* getChartData
* @return
* @return /
*/
Object getChartData();
}
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.monitor.service.impl;
import me.zhengjie.modules.monitor.domain.vo.RedisVo;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
......@@ -12,6 +11,7 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
......@@ -21,54 +21,58 @@ import java.util.concurrent.TimeUnit;
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
RedisTemplate redisTemplate;
private final RedisTemplate redisTemplate;
@Value("${loginCode.expiration}")
private Long expiration;
public RedisServiceImpl(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
@SuppressWarnings("unchecked")
public Page<RedisVo> findByKey(String key, Pageable pageable){
List<RedisVo> redisVos = new ArrayList<>();
if(!"*".equals(key)){
key = "*" + key + "*";
}
for (Object s : redisTemplate.keys(key)) {
for (Object s : Objects.requireNonNull(redisTemplate.keys(key))) {
// 过滤掉权限的缓存
if (s.toString().indexOf("role::loadPermissionByUser") != -1 || s.toString().indexOf("user::loadUserByUsername") != -1) {
if (s.toString().contains("role::loadPermissionByUser") || s.toString().contains("user::loadUserByUsername")) {
continue;
}
RedisVo redisVo = new RedisVo(s.toString(),redisTemplate.opsForValue().get(s.toString()).toString());
RedisVo redisVo = new RedisVo(s.toString(), Objects.requireNonNull(redisTemplate.opsForValue().get(s.toString())).toString());
redisVos.add(redisVo);
}
Page<RedisVo> page = new PageImpl<RedisVo>(
return new PageImpl<RedisVo>(
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),redisVos),
pageable,
redisVos.size());
return page;
}
@Override
@SuppressWarnings("unchecked")
public void delete(String key) {
redisTemplate.delete(key);
}
@Override
public void flushdb() {
redisTemplate.getConnectionFactory().getConnection().flushDb();
Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection().flushDb();
}
@Override
public String getCodeVal(String key) {
try {
String value = redisTemplate.opsForValue().get(key).toString();
return value;
return Objects.requireNonNull(redisTemplate.opsForValue().get(key)).toString();
}catch (Exception e){
return "";
}
}
@Override
@SuppressWarnings("unchecked")
public void saveCode(String key, Object val) {
redisTemplate.opsForValue().set(key,val);
redisTemplate.expire(key,expiration, TimeUnit.MINUTES);
......
......@@ -26,11 +26,14 @@ import java.util.stream.Collectors;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VisitsServiceImpl implements VisitsService {
@Autowired
private VisitsRepository visitsRepository;
private final VisitsRepository visitsRepository;
@Autowired
private LogRepository logRepository;
private final LogRepository logRepository;
public VisitsServiceImpl(VisitsRepository visitsRepository, LogRepository logRepository) {
this.visitsRepository = visitsRepository;
this.logRepository = logRepository;
}
@Override
public void save() {
......@@ -58,7 +61,7 @@ public class VisitsServiceImpl implements VisitsService {
@Override
public Object get() {
Map map = new HashMap();
Map<String,Object> map = new HashMap<>();
LocalDate localDate = LocalDate.now();
Visits visits = visitsRepository.findByDate(localDate.toString());
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(),localDate.plusDays(1).toString());
......@@ -77,7 +80,7 @@ public class VisitsServiceImpl implements VisitsService {
@Override
public Object getChartData() {
Map map = new HashMap();
Map<String,Object> map = new HashMap<>();
LocalDate localDate = LocalDate.now();
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(),localDate.plusDays(1).toString());
map.put("weekDays",list.stream().map(Visits::getWeekDay).collect(Collectors.toList()));
......
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.quartz.config;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.repository.QuartzJobRepository;
import me.zhengjie.modules.quartz.utils.QuartzManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
......@@ -17,24 +16,24 @@ import java.util.List;
@Component
public class JobRunner implements ApplicationRunner {
@Autowired
private QuartzJobRepository quartzJobRepository;
private final QuartzJobRepository quartzJobRepository;
@Autowired
private QuartzManage quartzManage;
private final QuartzManage quartzManage;
public JobRunner(QuartzJobRepository quartzJobRepository, QuartzManage quartzManage) {
this.quartzJobRepository = quartzJobRepository;
this.quartzManage = quartzManage;
}
/**
* 项目启动时重新激活启用的定时任务
* @param applicationArguments
* @throws Exception
* @param applicationArguments /
*/
@Override
public void run(ApplicationArguments applicationArguments){
System.out.println("--------------------注入定时任务---------------------");
List<QuartzJob> quartzJobs = quartzJobRepository.findByIsPauseIsFalse();
quartzJobs.forEach(quartzJob -> {
quartzManage.addJob(quartzJob);
});
quartzJobs.forEach(quartzManage::addJob);
System.out.println("--------------------定时任务注入完成---------------------");
}
}
......@@ -2,7 +2,6 @@ package me.zhengjie.modules.quartz.config;
import org.quartz.Scheduler;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -12,7 +11,7 @@ import org.springframework.stereotype.Component;
/**
* 定时任务配置
* @author
* @author /
* @date 2019-01-07
*/
@Configuration
......@@ -22,10 +21,13 @@ public class QuartzConfig {
* 解决Job中注入Spring Bean为null的问题
*/
@Component("quartzJobFactory")
public class QuartzJobFactory extends AdaptableJobFactory {
public static class QuartzJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
private final AutowireCapableBeanFactory capableBeanFactory;
public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) {
this.capableBeanFactory = capableBeanFactory;
}
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
......@@ -39,9 +41,9 @@ public class QuartzConfig {
/**
* 注入scheduler到spring
* @param quartzJobFactory
* @return
* @throws Exception
* @param quartzJobFactory /
* @return Scheduler
* @throws Exception /
*/
@Bean(name = "scheduler")
public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception {
......
......@@ -25,55 +25,39 @@ public class QuartzJob implements Serializable {
@NotNull(groups = {Update.class})
private Long id;
/**
* 定时器名称
*/
// 定时器名称
@Column(name = "job_name")
private String jobName;
/**
* Bean名称
*/
// Bean名称
@Column(name = "bean_name")
@NotBlank
private String beanName;
/**
* 方法名称
*/
// 方法名称
@Column(name = "method_name")
@NotBlank
private String methodName;
/**
* 参数
*/
// 参数
@Column(name = "params")
private String params;
/**
* cron表达式
*/
// cron表达式
@Column(name = "cron_expression")
@NotBlank
private String cronExpression;
/**
* 状态
*/
// 状态
@Column(name = "is_pause")
private Boolean isPause = false;
/**
* 备注
*/
// 备注
@Column(name = "remark")
@NotBlank
private String remark;
/**
* 创建日期
*/
// 创建日期
@UpdateTimestamp
@Column(name = "update_time")
private Timestamp updateTime;
......
......@@ -20,56 +20,38 @@ public class QuartzLog implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 任务名称
*/
// 任务名称
@Column(name = "job_name")
private String jobName;
/**
* Bean名称
*/
// Bean名称
@Column(name = "baen_name")
private String beanName;
/**
* 方法名称
*/
// 方法名称
@Column(name = "method_name")
private String methodName;
/**
* 参数
*/
// 参数
@Column(name = "params")
private String params;
/**
* cron表达式
*/
// cron表达式
@Column(name = "cron_expression")
private String cronExpression;
/**
* 状态
*/
// 状态
@Column(name = "is_success")
private Boolean isSuccess;
/**
* 异常详细
*/
// 异常详细
@Column(name = "exception_detail",columnDefinition = "text")
private String exceptionDetail;
/**
* 耗时(毫秒)
*/
// 耗时(毫秒)
private Long time;
/**
* 创建日期
*/
// 创建日期
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;
......
......@@ -9,11 +9,11 @@ import java.util.List;
* @author Zheng Jie
* @date 2019-01-07
*/
public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor {
public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor<QuartzJob> {
/**
* 查询启用的任务
* @return
* @return List
*/
List<QuartzJob> findByIsPauseIsFalse();
}
......@@ -8,6 +8,6 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-01-07
*/
public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor {
public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor<QuartzLog> {
}
package me.zhengjie.modules.quartz.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.service.QuartzJobService;
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -20,39 +21,47 @@ import org.springframework.web.bind.annotation.*;
*/
@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "系统:定时任务管理")
@RequestMapping("/api/jobs")
public class QuartzJobController {
private static final String ENTITY_NAME = "quartzJob";
@Autowired
private QuartzJobService quartzJobService;
private final QuartzJobService quartzJobService;
public QuartzJobController(QuartzJobService quartzJobService) {
this.quartzJobService = quartzJobService;
}
@Log("查询定时任务")
@GetMapping(value = "/jobs")
@ApiOperation("查询定时任务")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_SELECT')")
public ResponseEntity getJobs(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/jobLogs")
@ApiOperation("查询任务执行日志")
@GetMapping(value = "/logs")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_SELECT')")
public ResponseEntity getJobLogs(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
}
@Log("新增定时任务")
@PostMapping(value = "/jobs")
@ApiOperation("新增定时任务")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_CREATE')")
public ResponseEntity create(@Validated @RequestBody QuartzJob resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(quartzJobService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(quartzJobService.create(resources),HttpStatus.CREATED);
}
@Log("修改定时任务")
@PutMapping(value = "/jobs")
@ApiOperation("修改定时任务")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity update(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){
quartzJobService.update(resources);
......@@ -60,7 +69,8 @@ public class QuartzJobController {
}
@Log("更改定时任务状态")
@PutMapping(value = "/jobs/{id}")
@ApiOperation("更改定时任务状态")
@PutMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity updateIsPause(@PathVariable Long id){
quartzJobService.updateIsPause(quartzJobService.findById(id));
......@@ -68,7 +78,8 @@ public class QuartzJobController {
}
@Log("执行定时任务")
@PutMapping(value = "/jobs/exec/{id}")
@ApiOperation("执行定时任务")
@PutMapping(value = "/exec/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity execution(@PathVariable Long id){
quartzJobService.execution(quartzJobService.findById(id));
......@@ -76,7 +87,8 @@ public class QuartzJobController {
}
@Log("删除定时任务")
@DeleteMapping(value = "/jobs/{id}")
@ApiOperation("删除定时任务")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
quartzJobService.delete(quartzJobService.findById(id));
......
package me.zhengjie.modules.quartz.service;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.domain.QuartzLog;
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
/**
* @author Zheng Jie
* @date 2019-01-07
*/
@CacheConfig(cacheNames = "quartzJob")
public interface QuartzJobService {
/**
* queryAll quartzJob
* @param criteria
* @param pageable
* @return
*/
@Cacheable
Object queryAll(JobQueryCriteria criteria, Pageable pageable);
/**
* queryAll quartzLog
* @param criteria
* @param pageable
* @return
*/
Object queryAllLog(JobQueryCriteria criteria, Pageable pageable);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
QuartzJob create(QuartzJob resources);
/**
* update
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
void update(QuartzJob resources);
/**
* del
* @param quartzJob
*/
@CacheEvict(allEntries = true)
void delete(QuartzJob quartzJob);
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
QuartzJob findById(Long id);
/**
* 更改定时任务状态
* @param quartzJob
* @param quartzJob /
*/
@CacheEvict(allEntries = true)
void updateIsPause(QuartzJob quartzJob);
/**
* 立即执行定时任务
* @param quartzJob
* @param quartzJob /
*/
void execution(QuartzJob quartzJob);
}
......@@ -11,31 +11,37 @@ import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* @author Zheng Jie
* @date 2019-01-07
*/
@Service(value = "quartzJobService")
@CacheConfig(cacheNames = "quartzJob")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QuartzJobServiceImpl implements QuartzJobService {
@Autowired
private QuartzJobRepository quartzJobRepository;
private final QuartzJobRepository quartzJobRepository;
@Autowired
private QuartzLogRepository quartzLogRepository;
private final QuartzLogRepository quartzLogRepository;
@Autowired
private QuartzManage quartzManage;
private final QuartzManage quartzManage;
public QuartzJobServiceImpl(QuartzJobRepository quartzJobRepository, QuartzLogRepository quartzLogRepository, QuartzManage quartzManage) {
this.quartzJobRepository = quartzJobRepository;
this.quartzLogRepository = quartzLogRepository;
this.quartzManage = quartzManage;
}
@Override
@Cacheable
public Object queryAll(JobQueryCriteria criteria, Pageable pageable){
return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
}
......@@ -46,13 +52,15 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@Cacheable(key = "#p0")
public QuartzJob findById(Long id) {
Optional<QuartzJob> quartzJob = quartzJobRepository.findById(id);
ValidationUtil.isNull(quartzJob,"QuartzJob","id",id);
return quartzJob.get();
QuartzJob quartzJob = quartzJobRepository.findById(id).orElseGet(QuartzJob::new);
ValidationUtil.isNull(quartzJob.getId(),"QuartzJob","id",id);
return quartzJob;
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public QuartzJob create(QuartzJob resources) {
if (!CronExpression.isValidExpression(resources.getCronExpression())){
......@@ -64,6 +72,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(QuartzJob resources) {
if(resources.getId().equals(1L)){
......@@ -77,6 +86,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
public void updateIsPause(QuartzJob quartzJob) {
if(quartzJob.getId().equals(1L)){
throw new BadRequestException("该任务不可操作");
......@@ -100,6 +110,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void delete(QuartzJob quartzJob) {
if(quartzJob.getId().equals(1L)){
......
package me.zhengjie.modules.quartz.task;
import me.zhengjie.modules.monitor.service.VisitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
......@@ -11,8 +10,11 @@ import org.springframework.stereotype.Component;
@Component
public class VisitsTask {
@Autowired
private VisitsService visitsService;
private final VisitsService visitsService;
public VisitsTask(VisitsService visitsService) {
this.visitsService = visitsService;
}
public void run(){
visitsService.save();
......
......@@ -17,7 +17,7 @@ import java.util.concurrent.Future;
/**
* 参考人人开源,https://gitee.com/renrenio/renren-security
* @author
* @author /
* @date 2019-01-07
*/
@Async
......@@ -32,9 +32,8 @@ public class ExecutionJob extends QuartzJobBean {
protected void executeInternal(JobExecutionContext context) {
QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
// 获取spring bean
QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean("quartzLogRepository");
QuartzJobService quartzJobService = SpringContextHolder.getBean("quartzJobService");
QuartzManage quartzManage = SpringContextHolder.getBean("quartzManage");
QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class);
QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class);
QuartzLog log = new QuartzLog();
log.setJobName(quartzJob.getJobName());
......
......@@ -56,8 +56,7 @@ public class QuartzManage {
/**
* 更新job cron表达式
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void updateJobCron(QuartzJob quartzJob){
try {
......@@ -88,8 +87,7 @@ public class QuartzManage {
/**
* 删除一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void deleteJob(QuartzJob quartzJob){
try {
......@@ -104,8 +102,7 @@ public class QuartzManage {
/**
* 恢复一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void resumeJob(QuartzJob quartzJob){
try {
......@@ -124,8 +121,7 @@ public class QuartzManage {
/**
* 立即执行job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void runAJobNow(QuartzJob quartzJob){
try {
......@@ -146,8 +142,7 @@ public class QuartzManage {
/**
* 暂停一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void pauseJob(QuartzJob quartzJob){
try {
......
package me.zhengjie.modules.quartz.utils;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
......@@ -10,7 +9,7 @@ import java.util.concurrent.Callable;
/**
* 执行定时任务
* @author
* @author /
*/
@Slf4j
public class QuartzRunnable implements Callable {
......
......@@ -25,23 +25,21 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
private final JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
private final JwtUserDetailsService jwtUserDetailsService;
/**
* 自定义基于JWT的安全过滤器
*/
@Autowired
JwtAuthorizationTokenFilter authenticationTokenFilter;
// 自定义基于JWT的安全过滤器
private final JwtAuthorizationTokenFilter authenticationTokenFilter;
@Value("${jwt.header}")
private String tokenHeader;
@Value("${jwt.auth.path}")
private String loginPath;
public SecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler, JwtUserDetailsService jwtUserDetailsService, JwtAuthorizationTokenFilter authenticationTokenFilter) {
this.unauthorizedHandler = unauthorizedHandler;
this.jwtUserDetailsService = jwtUserDetailsService;
this.authenticationTokenFilter = authenticationTokenFilter;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
......@@ -70,6 +68,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
String loginPath = "login";
httpSecurity
// 禁用 CSRF
......@@ -91,7 +90,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/**/*.js"
).anonymous()
.antMatchers( HttpMethod.POST,"/auth/"+loginPath).anonymous()
.antMatchers( HttpMethod.POST,"/auth/"+ loginPath).anonymous()
.antMatchers("/auth/vCode").anonymous()
// 支付宝回调
.antMatchers("/api/aliPay/return").anonymous()
......
......@@ -2,6 +2,8 @@ package me.zhengjie.modules.security.rest;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
......@@ -15,7 +17,6 @@ import me.zhengjie.utils.EncryptUtils;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
......@@ -23,7 +24,6 @@ import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
......@@ -34,29 +34,28 @@ import java.io.IOException;
*/
@Slf4j
@RestController
@RequestMapping("auth")
@RequestMapping("/auth")
@Api(tags = "系统:系统授权接口")
public class AuthenticationController {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private JwtTokenUtil jwtTokenUtil;
private final JwtTokenUtil jwtTokenUtil;
@Autowired
private RedisService redisService;
private final RedisService redisService;
@Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService;
private final UserDetailsService userDetailsService;
public AuthenticationController(JwtTokenUtil jwtTokenUtil, RedisService redisService, @Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService) {
this.jwtTokenUtil = jwtTokenUtil;
this.redisService = redisService;
this.userDetailsService = userDetailsService;
}
/**
* 登录授权
* @param authorizationUser
* @return
*/
@Log("用户登录")
@PostMapping(value = "${jwt.auth.path}")
@ApiOperation("登录授权")
@PostMapping(value = "/login")
public ResponseEntity login(@Validated @RequestBody AuthorizationUser authorizationUser){
// 查询验证码
......@@ -86,21 +85,16 @@ public class AuthenticationController {
return ResponseEntity.ok(new AuthenticationInfo(token,jwtUser));
}
/**
* 获取用户信息
* @return
*/
@GetMapping(value = "${jwt.auth.account}")
@ApiOperation("获取用户信息")
@GetMapping(value = "/info")
public ResponseEntity getUserInfo(){
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
return ResponseEntity.ok(jwtUser);
}
/**
* 获取验证码
*/
@GetMapping(value = "vCode")
public ImgResult getCode(HttpServletResponse response) throws IOException {
@ApiOperation("获取验证码")
@GetMapping(value = "/vCode")
public ImgResult getCode() throws IOException {
//生成随机字串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
......
......@@ -18,9 +18,7 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Se
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
/**
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
*/
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.security.service;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.service.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
......@@ -17,13 +16,16 @@ import java.util.stream.Collectors;
@CacheConfig(cacheNames = "role")
public class JwtPermissionService {
@Autowired
private RoleRepository roleRepository;
private final RoleRepository roleRepository;
public JwtPermissionService(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
/**
* key的名称如有修改,请同步修改 UserServiceImpl 中的 update 方法
* @param user
* @return
* @param user 用户信息
* @return Collection
*/
@Cacheable(key = "'loadPermissionByUser:' + #p0.username")
public Collection<GrantedAuthority> mapToGrantedAuthorities(UserDTO user) {
......
Supports Markdown
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