添加权限校验

main
吴顺杰 5 months ago
parent 37af50a6bf
commit 83a557e166

@ -14,6 +14,18 @@
<spring-boot.version>2.7.6</spring-boot.version>
</properties>
<dependencies>
<!-- Sa-Token 权限认证在线文档https://sa-token.cc -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.37.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

@ -1,7 +1,7 @@
package com.yingji.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yingji.base.controller.BaseController;
import com.yingji.base.domain.AjaxResult;
@ -10,7 +10,6 @@ import com.yingji.entity.dto.request.AlarmFindRequest;
import com.yingji.service.AlarmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -44,13 +43,14 @@ public class AlarmController extends BaseController {
/**
*
*
* @param page
* @param req
* @param page
* @param req
* @return
*/
@GetMapping
@ApiOperation(value = "分页条件查询报警事件", response = Alarm.class)
public AjaxResult page(Page<Alarm> page, AlarmFindRequest req) {
StpUtil.checkLogin();
return success(alarmService.page(page, req));
}
@ -63,6 +63,8 @@ public class AlarmController extends BaseController {
@GetMapping("/findAll")
@ApiOperation(value = "条件查询所有报警事件", response = Alarm.class)
public AjaxResult findAll(AlarmFindRequest req) {
StpUtil.checkLogin();
// StpUtil.renewTimeout(100);
return success(alarmService.findAll(req));
}
@ -75,6 +77,7 @@ public class AlarmController extends BaseController {
@GetMapping("{id}")
@ApiOperation(value = "通过主键查询单条报警事件", response = Alarm.class)
public AjaxResult getById(@PathVariable Serializable id) {
StpUtil.checkLogin();
return success(alarmService.getById(id));
}
@ -87,6 +90,7 @@ public class AlarmController extends BaseController {
@PostMapping
@ApiOperation(value = "新增报警事件", response = Alarm.class)
public AjaxResult insert(@RequestBody Alarm alarm) {
StpUtil.checkLogin();
return success(alarmService.save(alarm));
}
@ -99,6 +103,7 @@ public class AlarmController extends BaseController {
@PutMapping
@ApiOperation(value = "修改报警事件")
public AjaxResult update(@RequestBody Alarm alarm) {
StpUtil.checkLogin();
return success(alarmService.updateById(alarm));
}
@ -111,6 +116,7 @@ public class AlarmController extends BaseController {
@DeleteMapping
@ApiOperation(value = "删除报警事件")
public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
StpUtil.checkLogin();
return success(alarmService.removeByIds(idList));
}
@ -118,14 +124,46 @@ public class AlarmController extends BaseController {
*
*
* @param startTime
* @param size
* @param size
* @return
*/
@GetMapping("/synchronous")
@ApiOperation(value = "同步数据")
public AjaxResult synchronous(String startTime, Integer size) {
alarmService.synchronous(startTime,size);
StpUtil.checkLogin();
alarmService.synchronous(startTime, size);
return success();
}
@ApiOperation(value = "登录")
@GetMapping("doLogin")
public AjaxResult doLogin(String clientId, String clientSecret) {
// 此处仅作模拟示例,真实项目需要从数据库中查询数据进行比对
if ("9219a5c1612c398c".equals(clientId) && "88aba31a35e3a713".equals(clientSecret)) {
StpUtil.login(10001);
return success((Object)StpUtil.getTokenValue());
}
return error("错误的授权码");
}
@ApiOperation(value = "查询登录状态")
@GetMapping("isLogin")
public String isLogin() {
return "当前会话是否登录:" + StpUtil.isLogin();
}
// public static void main(String[] args) {
// String encode = Base64.encode("123QWQAVA1314543");
// System.err.println(encode);
// MD5 md5 = MD5.create();
// String s = md5.digestHex16(encode);
// System.err.println(s);
//
// String encode2 = Base64.encode("321123QWQAVAORZ");
// System.err.println(encode2);
// MD5 md52 = MD5.create();
// String s2 = md5.digestHex16(encode2);
// System.err.println(s2);
// }
}

@ -0,0 +1,84 @@
package com.yingji.exception;
import cn.dev33.satoken.exception.NotLoginException;
import com.yingji.base.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
*
*
* @author wu
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
*
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
return AjaxResult.error(e.getMessage());
}
/**
*
*/
@ExceptionHandler(RuntimeException.class)
public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生未知异常.", requestURI, e);
return AjaxResult.error(e.getMessage());
}
/**
*
*/
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return AjaxResult.error(e.getMessage());
}
/**
*
*/
@ExceptionHandler(BindException.class)
public AjaxResult handleBindException(BindException e) {
log.error(e.getMessage(), e);
String message = e.getAllErrors().get(0).getDefaultMessage();
return AjaxResult.error(message);
}
/**
*
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error(message);
}
/**
*
*/
@ExceptionHandler(NotLoginException.class)
public AjaxResult handleDemoModeException(NotLoginException e) {
return AjaxResult.error(e.getMessage());
}
}

@ -2,6 +2,7 @@ package com.yingji.quartz;
import cn.hutool.core.util.StrUtil;
import com.yingji.entity.dto.request.AlarmRequest;
import com.yingji.redis.RedisCache;
import com.yingji.service.AlarmService;
import com.yingji.service.SourceService;
import org.slf4j.Logger;
@ -33,6 +34,9 @@ public class AlarmQuartz {
@Resource
private SourceService sourceService;
@Resource
private RedisCache redisCache;
/**
* id
*/
@ -43,10 +47,17 @@ public class AlarmQuartz {
if (StrUtil.isEmpty(token)) {
return;
}
// 获取五分钟前的时间
LocalDateTime yesterday = LocalDateTime.now().minusMinutes(5);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
String yesterdayStr = yesterday.format(formatter) + "00";
String yesterdayStr;
String effectiveTimeStr = redisCache.getCacheObject("effectiveTimeStr");
log.info("redis的缓存时间是==========================" + effectiveTimeStr );
if (StrUtil.isNotEmpty(effectiveTimeStr)) {
yesterdayStr = effectiveTimeStr;
} else {
// 获取五分钟前的时间
LocalDateTime yesterday = LocalDateTime.now().minusMinutes(5);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
yesterdayStr = yesterday.format(formatter) + "00";
}
// 定义起始页
int pageIndex = 1;
// 定义每页显示条数
@ -64,6 +75,7 @@ public class AlarmQuartz {
while (true) {
List<String> data = alarmService.findDataIdList(req, token);
if (data == null) {
redisCache.setCacheObject("effectiveTimeStr", yesterdayStr);
return;
}
sourceService.addList(data);
@ -72,6 +84,7 @@ public class AlarmQuartz {
req.setPageIndex(pageIndex++);
log.info("第" + pageIndex + "页==========================" + size + "条数据");
} else {
redisCache.deleteObject("effectiveTimeStr");
break;
}
}

@ -63,10 +63,11 @@ public class SaveAlarmQuartz {
Alarm alarm = alarmService.findDataList(alarmRequest, token);
if (alarm != null) {
alarm.setSourceId(x);
// todo 暂时不做去重操作
list.add(alarm);
sourceService.delBySourceId(x);
successNum++;
Thread.sleep(2000);
Thread.sleep(1000);
}
} catch (Exception e) {
failuresNum++;

@ -0,0 +1,248 @@
package com.yingji.redis;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* spring redis
*
* @author wu
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
@Resource
public RedisTemplate redisTemplate;
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject(final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
*
*
* @param key Redis
* @param timeout
* @return true=false=
*/
public boolean expire(final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
*
*
* @param key Redis
* @param timeout
* @param unit
* @return true=false=
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
*
*
* @param key Redis
* @return
*/
public long getExpire(final String key) {
return redisTemplate.getExpire(key);
}
/**
* key
*
* @param key
* @return true false
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
*
*
* @param key
* @return
*/
public <T> T getCacheObject(final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
*
*
* @param key
*/
public boolean deleteObject(final String key) {
return redisTemplate.delete(key);
}
/**
*
*
* @param collection
* @return
*/
public boolean deleteObject(final Collection collection) {
return redisTemplate.delete(collection) > 0;
}
/**
* List
*
* @param key
* @param dataList List
* @return
*/
public <T> long setCacheList(final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* list
*
* @param key
* @return
*/
public <T> List<T> getCacheList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* Set
*
* @param key
* @param dataSet
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
setOperation.add(it.next());
}
return setOperation;
}
/**
* set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @param value
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @return Hash
*/
public <T> T getCacheMapValue(final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* Hash
*
* @param key Redis
* @param hKeys Hash
* @return Hash
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @return
*/
public boolean deleteCacheMapValue(final String key, final String hKey) {
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
/**
*
*
* @param pattern
* @return
*/
public Collection<String> keys(final String pattern) {
return redisTemplate.keys(pattern);
}
}

@ -22,7 +22,6 @@ import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -211,13 +210,13 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
/**
*
*
* @param page
* @param req
* @param page
* @param req
* @return
*/
@Override
public Page<Alarm> page(Page<Alarm> page, AlarmFindRequest req) {
return baseMapper.page(page,req);
return baseMapper.page(page, req);
}
/**

@ -4,10 +4,37 @@ spring:
profiles:
active: dev
redis:
host: localhost
port: 6379
password:
database: 1
jedis:
pool:
max-active: 8 # 最大连接数
max-wait: 1ms # 最大阻塞时间
max-idle: 4
min-idle: 0
# 日志配置
logging:
level:
com.yingji: error
org.springframework: error
com.yingji: info
org.springframework: info
sa-token:
# token 名称(同时也是 cookie 名称)
token-name: token
# token 有效期(单位:秒) 默认30天-1 代表永久有效
timeout: 86400
# token 最低活跃频率(单位:秒),如果 token 超过此时间没有访问系统就会被冻结,默认-1 代表不限制,永不冻结
active-timeout: -1
# 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)
is-concurrent: true
# 在多人登录同一账号时,是否共用一个 token (为 true 时所有登录共用一个 token, 为 false 时每次登录新建一个 token
is-share: true
# token 风格默认可取值uuid、simple-uuid、random-32、random-64、random-128、tik
token-style: uuid
# 是否输出操作日志
is-log: true

Loading…
Cancel
Save