用户权限调整,及用户token刷新,日志记录

This commit is contained in:
tiger_zhou 2024-10-18 10:46:39 +08:00
parent 11ae9ea755
commit 615b83a681
33 changed files with 389 additions and 190 deletions

View File

@ -1,37 +1,32 @@
package club.joylink.xiannccda.aop;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.EventLogType.SubEventType;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.constants.SystemContext;
import club.joylink.xiannccda.event.OperateEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriTemplate;
@Aspect
@Slf4j
@ -41,85 +36,71 @@ public class SystemEventAspect {
@Autowired
private JwtDecoder jwtDecoder;
@AfterReturning(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", returning = "obj")
public void watchRequest(JoinPoint joinPoint, Object obj) {
OperateEvent oe = this.parseOperateEvent(joinPoint);
if (Objects.nonNull(oe)) {
oe.setRequestSuccess(1);
if (oe.getType() == EventLogType.LOGIN && oe.getSubType() == SubEventType.LOGIN) {
Jwt jwt = jwtDecoder.decode(obj.toString());
@AfterReturning(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", returning = "returnObj")
public void watchRequest(JoinPoint joinPoint, Object returnObj) {
OperateEvent obj = this.parseRequestParameter(joinPoint);
if (Objects.nonNull(obj)) {
obj.setRequestSuccess(1);
if (obj.getType() == CommonLogTypeEnum.LOGIN && obj.getSubType() == SubEventType.LOGIN) {
Jwt jwt = jwtDecoder.decode(returnObj.toString());
String userId = jwt.getClaimAsString("sub");
oe.setUserId(Long.parseLong(userId));
obj.setUserId(Long.parseLong(userId));
SystemContext.publishEvent(obj);
}
}
}
@AfterThrowing(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", throwing = "e")
public void watchRequest(JoinPoint joinPoint, Exception e) {
OperateEvent oe = this.parseRequestParameter(joinPoint);
if (Objects.nonNull(oe)) {
oe.setRequestSuccess(0);
SystemContext.publishEvent(oe);
}
}
@AfterThrowing(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", throwing = "e")
public void watchRequest(JoinPoint joinPoint, Exception e) {
OperateEvent oe = this.parseOperateEvent(joinPoint);
if (Objects.nonNull(oe)) {
oe.setRequestSuccess(0);
}
SystemContext.publishEvent(oe);
}
private OperateEvent parseOperateEvent(JoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
Object[] args = joinPoint.getArgs();
Map<String, Object> params = new HashMap<>();
request.getParameterNames().asIterator().forEachRemaining(d -> params.put(d, request.getParameter(d)));
if (ArrayUtils.isNotEmpty(args) && StringUtils.equalsAnyIgnoreCase(method, HttpMethod.POST.name(), HttpMethod.PUT.name())) {
JSONObject jo = JSONObject.from(args[0]);
for (String key : jo.keySet()) {
params.put(key, jo.get(key));
private OperateEvent parseRequestParameter(JoinPoint joinPoint) {
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
CommonLogAnno commonLogAnno = ms.getMethod().getDeclaredAnnotation(CommonLogAnno.class);
if (Objects.nonNull(commonLogAnno)) {
GetMapping getMapping = ms.getMethod().getDeclaredAnnotation(GetMapping.class);
PostMapping postMapping = ms.getMethod().getDeclaredAnnotation(PostMapping.class);
Map<String, Object> params = null;
if (Objects.nonNull(getMapping)) {
params = getRequestParam(getMapping.value(), joinPoint.getArgs());
} else if (Objects.nonNull(postMapping)) {
params = getRequestParam(postMapping.value(), joinPoint.getArgs());
}
}
EventLogType type = this.logType(uri);
SubEventType subType = this.logSubType(uri, method);
if (type == null) {
log.error("uri: {}, method: {} ,queryStr:{}", uri, method, JSONObject.toJSONString(params));
return null;
} else {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long userId = null;
if (type != EventLogType.LOGIN) {
if (commonLogAnno.logType() != CommonLogTypeEnum.LOGIN) {
userId = Long.valueOf(authentication.getName());
}
return new OperateEvent(type, subType, uri, method, params, userId);
}
}
static String[] OPERATE_URI_ARR = new String[]{
"/api/alertRecord", "/api/alertTip", "/api/alert/tip/time", "/api/config/device/area", "/api/config/device",
"/api/log", "/api/role/", "/api/user/", "/api/publishedGi/publish/lineNetwork/info"
};
private EventLogType logType(String uri) {
if (StringUtils.contains(uri, "/api/user/login")) {
return EventLogType.LOGIN;
} else if (StringUtils.containsAny(uri, OPERATE_URI_ARR)) {
return EventLogType.OPERATE;
} else if (StringUtils.contains(uri, "")) {
return EventLogType.WARN;
return new OperateEvent(commonLogAnno.name(), commonLogAnno.logType(), commonLogAnno.subLogType(), uri, method, params, userId);
}
return null;
}
private SubEventType logSubType(String uri, String method) {
if (StringUtils.containsAny(uri, "/api/user/login") && StringUtils.equalsIgnoreCase(method, HttpMethod.POST.name())) {
return SubEventType.LOGIN;
} else if (StringUtils.equalsIgnoreCase(method, HttpMethod.GET.name())) {
return SubEventType.QUERY;
} else if (StringUtils.equalsAnyIgnoreCase(method, HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.DELETE.name())) {
return SubEventType.SAVE_OR_UPDATE;
} else if (StringUtils.equalsAnyIgnoreCase(HttpMethod.DELETE.name())) {
return SubEventType.DELETE;
private Map<String, Object> getRequestParam(String[] mappingUri, Object[] args) {
Map<String, Object> params = new HashMap<>();
int argsIndex = 0;
if (ArrayUtils.isNotEmpty(mappingUri)) {
Map<String, Object> uriParamMap = new HashMap<>();
UriTemplate ut = new UriTemplate(mappingUri[0]);
for (String vn : ut.getVariableNames()) {
uriParamMap.put(vn, args[argsIndex]);
argsIndex++;
}
params.put("uriParam", uriParamMap);
}
return SubEventType.NONE;
for (; argsIndex < args.length; argsIndex++) {
params.put("param", args[argsIndex]);
}
return params;
}
}

View File

@ -1,10 +1,9 @@
package club.joylink.xiannccda.configuration;
import club.joylink.xiannccda.constants.LoginUserAttr;
import club.joylink.xiannccda.constants.common.LoginUserAttr;
import club.joylink.xiannccda.dto.auth.ApiPathCacheDTO;
import club.joylink.xiannccda.service.AuthService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@ -12,24 +11,18 @@ import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.text.ParseException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
@Component
//@Component
@Slf4j
public class AuthFilter implements Filter {

View File

@ -51,8 +51,8 @@ public class SpringSecurityConfiguration {
@Autowired
CorsConfigurationSource corsConfigurationSource;
@Autowired
private AuthFilter authFilter;
/*@Autowired
private AuthFilter authFilter;*/
static List<RequestMatcher> AuthWhiteList = new ArrayList<>();
static {
@ -86,8 +86,8 @@ public class SpringSecurityConfiguration {
// .httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(this.jwtDecoder())))
// .addFilterAfter(authFilter,BearerTokenAuthenticationFilter.class)
.addFilterAfter(authFilter,FilterSecurityInterceptor.class)
// .addFilterAfter(authFilter,FilterSecurityInterceptor.class)
.sessionManagement(
(session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling((exceptions) -> exceptions

View File

@ -1,6 +0,0 @@
package club.joylink.xiannccda.constants;
public enum DefaultUserRule {
ADMIN, USER
}

View File

@ -1,16 +0,0 @@
package club.joylink.xiannccda.constants;
import club.joylink.xiannccda.ats.message.line3.device.ScheduleSubIdType;
import java.util.Arrays;
public enum EventLogType {
//登录
LOGIN,
OPERATE,
WARN,
;
public enum SubEventType {
LOGIN, LOGOUT, QUERY, SAVE_OR_UPDATE, DELETE, WARN, NONE
}
}

View File

@ -0,0 +1,22 @@
package club.joylink.xiannccda.constants.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Indexed;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface CommonLogAnno {
String name() default "";
CommonLogTypeEnum logType();
CommonLogTypeEnum.SubEventType subLogType();
}

View File

@ -0,0 +1,13 @@
package club.joylink.xiannccda.constants.common;
public enum CommonLogTypeEnum {
//登录
LOGIN,
OPERATE,
WARN,
;
public enum SubEventType {
LOGIN, LOGOUT, QUERY, SAVE_OR_UPDATE, DELETE, WARN, NONE
}
}

View File

@ -0,0 +1,5 @@
package club.joylink.xiannccda.constants.common;
public enum LineTypeEnum {
NCC, OCC;
}

View File

@ -1,8 +1,13 @@
package club.joylink.xiannccda.constants;
package club.joylink.xiannccda.constants.common;
public class LoginUserAttr {
public static final String DEFAULTS = "default";
public static final String ROLES = "roles";
public enum DefaultUserRuleEnum {
ADMIN, USER
}
}

View File

@ -2,6 +2,9 @@ package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.alert.NccAlertInfo;
import club.joylink.xiannccda.alert.NccAlertInfo.AlertStatus;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.record.AlertRecordQueryDTO;
import club.joylink.xiannccda.dto.record.AlertRecordReportDTO;
import club.joylink.xiannccda.dto.record.AlertRecordReportResponseDTO;
@ -15,7 +18,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@ -48,6 +50,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "报警信息确认")
@ApiResponse(description = "报警信息确认")
@CommonLogAnno(name = "报警信息确认", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public AlertTip confirm(@PathVariable("recordId") Long recordId, @PathVariable("tipType") String tipType, @RequestParam(value = "alertLocationId", required = false) Long locationId) {
return this.alertRecordService.confirm(recordId, tipType, locationId);
}
@ -56,6 +59,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "错误报警")
@ApiResponse(description = "错误报警")
@CommonLogAnno(name = "报警信息-人工确认", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void batchAlarmWarn(@RequestBody List<Long> recordId) {
this.alertRecordService.failAlarm(recordId, AlertStatus.PERSON_WARN_DO);
}
@ -64,6 +68,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "错误报警")
@ApiResponse(description = "错误报警")
@CommonLogAnno(name = "报警信息-误报", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void failAlarm(@PathVariable("recordId") Long recordId) {
this.alertRecordService.failAlarm(List.of(recordId), AlertStatus.FAIL_DO);
}
@ -72,15 +77,17 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "分页查询报警记录")
@ApiResponse(description = "报警记录")
@CommonLogAnno(name = "报警信息-列表数据", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<AlertRecord> pageQuery(@RequestBody AlertRecordQueryDTO queryDTO) {
return alertRecordRepository.page(queryDTO);
}
@PostMapping("/page/detail")
@SecurityRequirement(name = "jwt")
@Operation(summary = "分页查询报警记录详情")
@ApiResponse(description = "报警记录详情")
@CommonLogAnno(name = "报警信息-列表数据2", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<NccAlertInfo> pageQueryAlertDetail(@RequestBody AlertRecordQueryDTO queryDTO) {
return alertRecordService.pageQueryAlertDetail(queryDTO);
}
@ -90,6 +97,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "报警统计")
@ApiResponse(description = "报警统计")
@CommonLogAnno(name = "报警信息-统计", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public List<AlertRecordReportResponseDTO> reportStatistics(@PathVariable("lineId") Integer lineId, @RequestBody AlertRecordReportDTO reportDTO) {
return this.alertRecordRepository.report(lineId, reportDTO);
}

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.alertTip.AlertTipInfoDto;
import club.joylink.xiannccda.dto.alertTip.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipSaveDTO;
@ -9,8 +12,6 @@ import club.joylink.xiannccda.service.AlertTipService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService.AreaFinder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -21,14 +22,13 @@ import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 报警时的提示信息 前端控制器
* 决策信息
* </p>
*
* @author walker-sheng
@ -52,6 +52,7 @@ public class AlertTipController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "插入报警提示信息")
@PostMapping()
@CommonLogAnno(name = "决策信息-保存修改", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void save(@RequestBody @Validated AlertTipSaveDTO saveDTO) {
alertTipService.save(saveDTO);
}
@ -60,6 +61,7 @@ public class AlertTipController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "根据id查询数据")
@GetMapping("/id/{id}")
@CommonLogAnno(name = "决策信息-查看", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public AlertTip getById(@PathVariable int id) {
return alertTipRepository.getById(id);
}
@ -68,6 +70,7 @@ public class AlertTipController {
@Operation(summary = "分页查询报警提示信息")
@ApiResponse(description = "报警提示信息分页")
@GetMapping("/page")
@CommonLogAnno(name = "决策信息-分页列表", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public IPage<AlertTipInfoDto> pageAlertTips(AlertTipQueryDTO alertTipQueryDTO) {
return this.alertTipService.page(alertTipQueryDTO);
}
@ -77,13 +80,15 @@ public class AlertTipController {
@Operation(summary = "根据id删除数据")
@ApiResponse(description = "是否确实删除掉了一条数据")
@DeleteMapping("/id/{id}")
@CommonLogAnno(name = "决策信息-删除", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.DELETE)
public boolean deleteById(@PathVariable int id) {
return this.alertTipRepository.removeById(id);
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/find/type/{lineId}/{alertType}")
@PostMapping(value = "/find/type/{lineId}/{alertType}")
@CommonLogAnno(name = "决策信息-类型绑定查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public List<AreaFinder> findAlertType(@PathVariable("lineId") Integer lineId, @PathVariable("alertType") String alertType) {
return this.areaConfigService.findAlertType(lineId, alertType);

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.alertTip.AlertTipTimeQueryDTO;
import club.joylink.xiannccda.entity.AlertTipTimeConfig;
import club.joylink.xiannccda.repository.impl.AlertTipTimeConfigRepository;
@ -8,7 +11,10 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.web.bind.annotation.GetMapping;
import java.security.Principal;
import java.time.Instant;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -16,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* 决策信息时间类型配置
* </p>
*
* @author walker-sheng
@ -37,15 +43,24 @@ public class AlertTipTimeConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("")
@CommonLogAnno(name = "决策信息时间-类型保存", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void save(@RequestBody AlertTipTimeConfig dto) {
this.timeConfigService.saveOrUpdate(dto);
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@GetMapping("page")
public IPage<AlertTipTimeConfig> page(AlertTipTimeQueryDTO dto) {
@PostMapping("page")
@CommonLogAnno(name = "决策信息时间-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public IPage<AlertTipTimeConfig> page(Principal user, AlertTipTimeQueryDTO dto) {
JwtAuthenticationToken authToken = (JwtAuthenticationToken) user;
System.out.println(authToken.getPrincipal());
System.out.println(authToken.getTokenAttributes());
Object exp = authToken.getTokenAttributes().get(JwtClaimNames.EXP);
Instant time = (Instant) exp;
System.out.println(time.getEpochSecond());
System.out.println(authToken.getCredentials());
System.out.println(authToken.getAuthorities());
return this.configRepository.page(dto, Wrappers.lambdaQuery(AlertTipTimeConfig.class).eq(AlertTipTimeConfig::getListShower, 1));
}

View File

@ -1,15 +1,12 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigDto;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigPageDto;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigQueryDto;
import club.joylink.xiannccda.entity.DeviceAreaConfig;
import club.joylink.xiannccda.repository.impl.DeviceAreaConfigRepository;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService.AreaFinder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -25,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* 设备区域配置
* </p>
*
* @author walker-sheng
@ -45,6 +42,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("/save")
@CommonLogAnno(name = "决策信息设备区域配置-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String save(@RequestBody DeviceAreaConfigDto dto) {
this.areaConfigService.saveOrUpdate(dto);
return "ok";
@ -53,23 +51,17 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/bind/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-信息绑定", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String bindAlertType(@PathVariable("id") Long id, @RequestBody List<String> alertTypes) {
this.areaConfigService.bindAlertType(id, alertTypes);
return "ok";
}
/* @SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/find/type/{lineId}/{alertType}")
public List<AreaFinder> findAlertType(@PathVariable("lineId") Integer lineId, @PathVariable("alertType") String alertType) {
return this.areaConfigService.findAlertType(lineId, alertType);
}*/
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@GetMapping("/page/{lineId}")
@CommonLogAnno(name = "决策信息设备区域配置-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<DeviceAreaConfigPageDto> page(@PathVariable("lineId") Integer lineId, DeviceAreaConfigQueryDto queryDto) {
return this.areaConfigService.page(queryDto, lineId);
}
@ -77,6 +69,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@GetMapping("/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public DeviceAreaConfigDto findById(@PathVariable("id") Long id) {
return this.areaConfigService.findInfo(id);
}
@ -84,6 +77,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@DeleteMapping("/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-删除", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.DELETE)
public String delete(@PathVariable("id") Long id) {
this.areaConfigService.delete(id);
return "ok";

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.entity.DeviceGuardConfig;
import club.joylink.xiannccda.repository.IDeviceGuardConfigRepository;
import club.joylink.xiannccda.service.config.DeviceGuardConfigService;
@ -8,7 +11,6 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -17,7 +19,10 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "设备保护配置接口")
/**
* 决策信息阈值管理
*/
@Tag(name = "决策信息阈值管理")
@RestController
@RequestMapping("/api/config/device")
public class DeviceGuardConfigController {
@ -32,6 +37,7 @@ public class DeviceGuardConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "initData")
@GetMapping("/initData/{lineId}")
@CommonLogAnno(name = "决策信息阈值管理-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public DeviceGuardConfig initData(@PathVariable("lineId") Integer lineId) {
LambdaQueryWrapper<DeviceGuardConfig> qw = Wrappers.lambdaQuery(DeviceGuardConfig.class);
qw.eq(DeviceGuardConfig::getLineId, lineId);
@ -41,6 +47,7 @@ public class DeviceGuardConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("/save")
@CommonLogAnno(name = "决策信息阈值管理-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String saveOrUpdate(@RequestBody DeviceGuardConfig dto) {
this.configService.saveOrUpdate(dto);
return "ok";

View File

@ -1,9 +1,14 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.LoginInfoDTO;
import club.joylink.xiannccda.dto.user.UserDetailDTO;
import club.joylink.xiannccda.dto.user.UserEditDTO;
import club.joylink.xiannccda.dto.user.UserInfoAuthDTO;
import club.joylink.xiannccda.dto.user.UserQueryDTO;
import club.joylink.xiannccda.dto.user.UserTokenDTO;
import club.joylink.xiannccda.entity.User;
import club.joylink.xiannccda.entity.User.Register;
import club.joylink.xiannccda.repository.IUserRepository;
@ -13,6 +18,8 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.Principal;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@ -39,23 +46,47 @@ public class UserController {
this.userRepository = userRepository;
}
@PostMapping("/register")
/* @PostMapping("/register")
@Operation(summary = "用户注册")
@ApiResponse(description = "用户注册结果")
public String register(@RequestBody @Validated(Register.class) User user) {
return this.userService.register(user);
}*/
@PostMapping("/info")
@Operation(summary = "用户信息")
@ApiResponse(description = "用户信息")
public UserInfoAuthDTO userInfo(Principal user) {
return this.userService.userInfo((JwtAuthenticationToken) user);
}
@PostMapping("/login")
@Operation(summary = "用户登录")
@ApiResponse(description = "授权的jwt")
@CommonLogAnno(name = "用户登录", logType = CommonLogTypeEnum.LOGIN, subLogType = SubEventType.LOGIN)
public String login(@RequestBody LoginInfoDTO loginInfo) {
return this.userService.login(loginInfo);
}
@PostMapping("/logout")
@Operation(summary = "用户登出")
@ApiResponse(description = "授权的jwt")
@CommonLogAnno(name = "用户登出", logType = CommonLogTypeEnum.LOGIN, subLogType = SubEventType.LOGOUT)
public String logout() {
return "";
}
@PostMapping("/refresh/token")
@SecurityRequirement(name = "jwt")
@Operation(summary = "用户刷新token")
@ApiResponse(description = "刷新jwt")
public UserTokenDTO refreshToken(Principal user) {
return this.userService.refreshToken((JwtAuthenticationToken) user);
}
@PostMapping("/edit")
@Operation(summary = "用户修改")
@SecurityRequirement(name = "jwt")
@ApiResponse(description = "用户修改")
public void editUser(@RequestBody UserEditDTO dto) {
this.userService.editUser(dto);

View File

@ -1,6 +1,7 @@
package club.joylink.xiannccda.dto.event;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import java.time.LocalDateTime;
import lombok.Data;
@ -8,7 +9,7 @@ import lombok.Data;
public class EventLogPageDTO {
private Long id;
private EventLogType eventType;
private CommonLogTypeEnum eventType;
private String userName;
private Long fromUserId;
private String mobile;

View File

@ -1,13 +1,14 @@
package club.joylink.xiannccda.dto.user;
import club.joylink.xiannccda.constants.DefaultUserRule;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDateTime;
import java.util.List;
import lombok.Data;
import lombok.experimental.Accessors;
@Deprecated
@Data
public class UserDetailDTO {
private Long id;
@ -16,7 +17,7 @@ public class UserDetailDTO {
private LocalDateTime registerTime;
private List<UserRoleDetail> roleList;
@JsonIgnore
private DefaultUserRule defaultRole;
private DefaultUserRuleEnum defaultRole;
@JsonIgnore
private String userRoles;

View File

@ -0,0 +1,24 @@
package club.joylink.xiannccda.dto.user;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import club.joylink.xiannccda.entity.AuthRole;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.Data;
@Data
public class UserInfoAuthDTO {
@Schema(name = "token剩余时间 (秒)")
private Long remainingSecond;
@Schema(name = "用户角色")
private List<AuthRole> roles;
@Schema(name = "用户默认角色")
private DefaultUserRuleEnum defaultRole;
public UserInfoAuthDTO(Long remainingSecond, List<AuthRole> roles, DefaultUserRuleEnum defaultRole) {
this.remainingSecond = remainingSecond;
this.roles = roles;
this.defaultRole = defaultRole;
}
}

View File

@ -0,0 +1,12 @@
package club.joylink.xiannccda.dto.user;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class UserTokenDTO {
private String token;
private long remainingSecond;
}

View File

@ -1,17 +1,23 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.constants.common.LineTypeEnum;
import club.joylink.xiannccda.entity.AuthApiPath.AuthApi;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
@Data
@Setter
@Getter
@Accessors(chain = true)
@TableName("auth_role")
@Schema(name = "authRole", description = "用户角色")
@ -24,7 +30,31 @@ public class AuthRole {
@NotBlank(message = "名字不能为空", groups = {AuthApi.class})
private String name;
@Schema(description = "角色配置")
@JsonIgnore
private String roleConfigStr;
@Schema(description = "角色配置")
@TableField(exist = false)
private RoleConfig roleConfig;
public RoleConfig getRoleConfig() {
if (StringUtils.isNotEmpty(this.roleConfigStr)) {
return JSON.parseObject(this.roleConfigStr, RoleConfig.class);
}
return null;
}
public static final String ID = "id";
public static final String NAME = "name";
@Data
public static class RoleConfig {
private Integer lineId;
private LineTypeEnum lineType;
}
}

View File

@ -1,8 +1,6 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.alert.core.AlertDeviceType;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.EventLogType.SubEventType;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@ -31,8 +29,9 @@ public class EventLog {
private Long id;
@Schema(description = "设备类型")
private EventLogType eventType;
private SubEventType subEventType;
private CommonLogTypeEnum eventType;
private CommonLogTypeEnum.SubEventType subEventType;
private String faceName;
private String uri;
private String method;
private String parameters;

View File

@ -1,8 +1,9 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema.RequiredMode;
import jakarta.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import io.swagger.v3.oas.annotations.media.Schema;
@ -41,9 +42,10 @@ public class User {
@Schema(description = "注册时间")
private LocalDateTime registerTime;
@Schema(description = "用户默认角色")
private String defaultRole;
private DefaultUserRuleEnum defaultRole;
public static final String ID = "id";
public static final String NAME = "name";

View File

@ -1,7 +1,6 @@
package club.joylink.xiannccda.event;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.EventLogType.SubEventType;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
@ -12,8 +11,9 @@ import org.springframework.context.ApplicationEvent;
@Accessors(chain = true)
public class OperateEvent extends ApplicationEvent {
private EventLogType type;
private SubEventType subType;
private String faceName;
private CommonLogTypeEnum type;
private CommonLogTypeEnum.SubEventType subType;
private String uri;
private String method;
@ -21,8 +21,10 @@ public class OperateEvent extends ApplicationEvent {
private Long userId;
private Integer requestSuccess;
public OperateEvent(EventLogType type, SubEventType subType, String uri, String method, Object source, Long userId) {
public OperateEvent(String faceName, CommonLogTypeEnum type, CommonLogTypeEnum.SubEventType subType, String uri, String method, Object source, Long userId) {
super(source);
this.faceName = faceName;
this.type = type;
this.subType = subType;
this.uri = uri;

View File

@ -21,7 +21,8 @@ public class OperateEventHandle {
@EventListener
public void eventHandle(OperateEvent event) {
EventLog eventLog = new EventLog();
eventLog.setEventType(event.getType()).setSubEventType(event.getSubType()).setUri(event.getUri()).setMethod(event.getMethod()).setRequestSuccess(event.getRequestSuccess())
eventLog.setFaceName(event.getFaceName()).setEventType(event.getType()).setSubEventType(event.getSubType()).setUri(event.getUri()).setMethod(event.getMethod())
.setRequestSuccess(event.getRequestSuccess())
.setFromUserId(event.getUserId()).setParameters(JSON.toJSONString(event.getSource())).setCreateDateTime(LocalDateTime.now());
eventLogRepository.save(eventLog);
}

View File

@ -4,9 +4,12 @@ import club.joylink.xiannccda.dto.auth.AuthRoleDTO;
import club.joylink.xiannccda.dto.auth.AuthRoleQueryDTO;
import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.AuthRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -20,4 +23,6 @@ import org.apache.ibatis.annotations.Mapper;
public interface AuthRoleMapper extends BaseMapper<AuthRole> {
Page<AuthRoleDTO> queryRole(AuthRoleQueryDTO dto);
List<AuthRole> getAuthRoleByUserId(@Param("userId") String userId);
}

View File

@ -2,8 +2,11 @@ package club.joylink.xiannccda.mapper;
import club.joylink.xiannccda.entity.AuthRoleApiPathRef;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -16,4 +19,5 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AuthRoleUserRefMapper extends BaseMapper<AuthRoleUserRef> {
}

View File

@ -7,6 +7,7 @@ import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.AuthRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
@ -19,4 +20,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
public interface IAuthRoleRepository extends IService<AuthRole> {
Page<AuthRoleDTO> roleApiPage(AuthRoleQueryDTO role);
List<AuthRole> getAuthRoleByUserId(String userId);
}

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.repository;
import club.joylink.xiannccda.entity.AuthRoleApiPathRef;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>

View File

@ -35,4 +35,9 @@ public class AuthRoleRepository extends ServiceImpl<AuthRoleMapper, AuthRole> im
});
return page;
}
@Override
public List<AuthRole> getAuthRoleByUserId(String userId) {
return this.baseMapper.getAuthRoleByUserId(userId);
}
}

View File

@ -7,6 +7,7 @@ import club.joylink.xiannccda.mapper.AuthRoleUserRefMapper;
import club.joylink.xiannccda.repository.IAuthRoleApiRefRepository;
import club.joylink.xiannccda.repository.IAuthRoleUserRefRepository;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
/**
@ -20,4 +21,5 @@ import org.springframework.stereotype.Service;
@Service
public class AuthRoleUserRefRepository extends ServiceImpl<AuthRoleUserRefMapper, AuthRoleUserRef> implements IAuthRoleUserRefRepository {
}

View File

@ -11,6 +11,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@ -30,11 +31,14 @@ public class UserRepository extends ServiceImpl<UserMapper, User> implements IUs
Page<UserDetailDTO> page = this.baseMapper.detailQuery(dto);
for (UserDetailDTO record : page.getRecords()) {
List<UserRoleDetail> userRoleList = Lists.newArrayList();
Arrays.stream(StringUtils.split(record.getUserRoles(), ',')).forEach(d -> {
String[] idName = StringUtils.split(d, '|');
userRoleList.add(new UserRoleDetail(Long.valueOf(idName[0]), idName[1]));
});
record.setRoleList(userRoleList);
if (StringUtils.isNotEmpty(record.getUserRoles())) {
Arrays.stream(StringUtils.split(record.getUserRoles(), ',')).forEach(d -> {
String[] idName = StringUtils.split(d, '|');
userRoleList.add(new UserRoleDetail(Long.valueOf(idName[0]), idName[1]));
});
record.setRoleList(userRoleList);
}
record.setUserRoles(null);
}
return page;

View File

@ -1,33 +1,31 @@
package club.joylink.xiannccda.service;
import club.joylink.xiannccda.constants.DefaultUserRule;
import club.joylink.xiannccda.constants.LoginUserAttr;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import club.joylink.xiannccda.constants.common.LoginUserAttr;
import club.joylink.xiannccda.dto.LoginInfoDTO;
import club.joylink.xiannccda.dto.user.UserDetailDTO;
import club.joylink.xiannccda.dto.user.UserDetailDTO.UserRoleDetail;
import club.joylink.xiannccda.dto.user.UserEditDTO;
import club.joylink.xiannccda.dto.user.UserQueryDTO;
import club.joylink.xiannccda.dto.user.UserInfoAuthDTO;
import club.joylink.xiannccda.dto.user.UserTokenDTO;
import club.joylink.xiannccda.entity.AuthRole;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import club.joylink.xiannccda.entity.User;
import club.joylink.xiannccda.exception.BusinessExceptionAssertEnum;
import club.joylink.xiannccda.repository.IAuthRoleRepository;
import club.joylink.xiannccda.repository.IAuthRoleUserRefRepository;
import club.joylink.xiannccda.repository.IUserRepository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.collect.Maps;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -37,11 +35,14 @@ public class UserService {
final IUserRepository userRepository;
final JwtEncoder jwtEncoder;
final IAuthRoleUserRefRepository authRoleUserRefRepository;
final IAuthRoleRepository authRoleRepository;
private final static long EXPIRY = 3 * 24 * 60 * 60;//3天过期时间
public UserService(IUserRepository userRepository, JwtEncoder jwtEncoder, IAuthRoleUserRefRepository authRoleUserRefRepository) {
public UserService(IUserRepository userRepository, JwtEncoder jwtEncoder, IAuthRoleUserRefRepository authRoleUserRefRepository, IAuthRoleRepository authRoleRepository) {
this.userRepository = userRepository;
this.jwtEncoder = jwtEncoder;
this.authRoleUserRefRepository = authRoleUserRefRepository;
this.authRoleRepository = authRoleRepository;
}
public String register(User user) {
@ -57,33 +58,43 @@ public class UserService {
public String login(LoginInfoDTO loginInfo) {
UserQueryDTO dto = UserQueryDTO.builder().mobile(loginInfo.getAccount()).password(loginInfo.getPassword()).build();
/* UserQueryDTO dto = UserQueryDTO.builder().mobile(loginInfo.getAccount()).password(loginInfo.getPassword()).build();
dto.setCurrent(0);
dto.setSize(1);
Page<UserDetailDTO> page = this.userRepository.userRolePage(dto);
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(CollectionUtils.isNotEmpty(page.getRecords()), "账号或密码错误");
UserDetailDTO dd = page.getRecords().get(0);
List<Long> ruleList = dd.getRoleList().stream().map(UserRoleDetail::getRoleId).collect(Collectors.toList());
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(CollectionUtils.isNotEmpty(page.getRecords()), "账号或密码错误");*/
long expiry = 3 * 24 * 60 * 60;
// UserDetailDTO dd = page.getRecords().get(0);
// List<Long> ruleList = dd.getRoleList().stream().map(UserRoleDetail::getRoleId).collect(Collectors.toList());
User user = this.userRepository.getOne(
Wrappers.<User>lambdaQuery().eq(User::getMobile, loginInfo.getAccount())
.eq(User::getPassword, loginInfo.getPassword()));
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(user, "账号或密码错误");
// 使用默认的RS256生成jwt
Instant now = Instant.now();
Instant end = now.plusSeconds(EXPIRY);
return this.createToken(List.of(), user.getDefaultRole(), String.valueOf(user.getId()), now, end);
}
private String createToken(List<Long> ruleList, DefaultUserRuleEnum userDefaultRule, String userId, Instant start, Instant end) {
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plusSeconds(expiry))
.issuedAt(start)
.expiresAt(end)
.claims((d) -> {
d.put(LoginUserAttr.ROLES, ruleList);
if (dd.getDefaultRole() == DefaultUserRule.ADMIN) {
if (userDefaultRule == DefaultUserRuleEnum.ADMIN) {
d.put(LoginUserAttr.DEFAULTS, "admin");
}
})
.subject(dd.getId() + "")//此处实际为用户id(数据库记录id)
.subject(userId)//此处实际为用户id(数据库记录id)
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
// 使用默认的RS256生成jwt
final String token = this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
return token;
}
@Transactional
@ -98,4 +109,30 @@ public class UserService {
this.authRoleUserRefRepository.saveBatch(refList);
}
}
public UserInfoAuthDTO userInfo(JwtAuthenticationToken authToken) {
Object iat = authToken.getTokenAttributes().get(JwtClaimNames.IAT);
Object exp = authToken.getTokenAttributes().get(JwtClaimNames.EXP);
Object defulatRole = authToken.getTokenAttributes().get(LoginUserAttr.DEFAULTS);
DefaultUserRuleEnum userDefulatRole = Objects.nonNull(defulatRole) ? DefaultUserRuleEnum.ADMIN : DefaultUserRuleEnum.USER;
long remainingSecond = 0;
List<AuthRole> roleList = null;
if (Objects.nonNull(iat) && !Objects.nonNull(exp)) {
Instant iatInstant = (Instant) iat;
Instant expInstant = (Instant) exp;
remainingSecond = expInstant.getEpochSecond() - iatInstant.getEpochSecond();
roleList = this.authRoleRepository.getAuthRoleByUserId(authToken.getName());
}
return new UserInfoAuthDTO(remainingSecond, roleList, userDefulatRole);
}
public UserTokenDTO refreshToken(JwtAuthenticationToken authToken) {
Object defulatRole = authToken.getTokenAttributes().get(LoginUserAttr.DEFAULTS);
DefaultUserRuleEnum userDefulatRole = Objects.nonNull(defulatRole) ? DefaultUserRuleEnum.ADMIN : DefaultUserRuleEnum.USER;
Instant now = Instant.now();
Instant end = now.plusSeconds(EXPIRY);
String token = this.createToken(List.of(), userDefulatRole, authToken.getName(), now, end);
return new UserTokenDTO(token, end.getEpochSecond() - now.getEpochSecond());
}
}

View File

@ -19,4 +19,13 @@
on A.id = B.role_id
where 1 = 1
</select>
<select id="getAuthRoleByUserId" resultType="club.joylink.xiannccda.entity.AuthRole">
select A.*
from auth_role A
left join auth_role_user_ref B on A.id = B.role_id
where 1 = 1
and B.user_id = ${userId}
</select>
</mapper>