增加消息模块 修改整体权限包结构 解决与gateway冲突

master
bynt 3 years ago
parent 2c94d18261
commit 2c515071bf

1
.gitignore vendored

@ -5,6 +5,7 @@
# Log file
*.log
/log
/logs
# BlueJ files
*.ctxt

@ -1,46 +0,0 @@
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Maven template
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
### Example user template template
### Example user template
# IntelliJ project files
.idea
*.iml
out
gen

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>ad-platform</artifactId>
<groupId>com.baiye</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common-auth</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ad-platform-common-auth</name>
<description>ad-platform-common-auth</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
</dependency>
<!-- Spring boot websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,49 @@
package com.baiye.aspect;
import cn.hutool.core.util.StrUtil;
import com.baiye.annotation.Inner;
import com.baiye.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;
import javax.servlet.http.HttpServletRequest;
/**
* @author Enzo
* @date : 2022/1/11
*/
@Slf4j
@Aspect
@RequiredArgsConstructor
public class SecurityInnerAspect implements Ordered {
private final HttpServletRequest request;
@SneakyThrows
@Around("@within(inner) || @annotation(inner)")
public Object around(ProceedingJoinPoint point, Inner inner) {
// 实际注入的inner实体由表达式后一个注解决定即是方法上的@Inner注解实体若方法上无@Inner注解则获取类上的
if (inner == null) {
Class<?> clazz = point.getTarget().getClass();
inner = AnnotationUtils.findAnnotation(clazz, Inner.class);
}
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("访问接口 {} 没有权限", point.getSignature().getName());
throw new AccessDeniedException("Access is denied");
}
return point.proceed();
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
}

@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.config;
package com.baiye.config;
import com.baiye.modules.security.config.bean.LoginProperties;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.properties.bean.LoginProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -35,9 +34,5 @@ public class ConfigBeanConfiguration {
return new LoginProperties();
}
@Bean
@ConfigurationProperties(prefix = "jwt")
public SecurityProperties securityProperties() {
return new SecurityProperties();
}
}

@ -0,0 +1,35 @@
package com.baiye.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author Enzo
* @date : 2022/1/11
*/
public class CustomAuthorityDeserializer extends JsonDeserializer {
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
ObjectMapper mapper = (ObjectMapper) p.getCodec();
JsonNode jsonNode = mapper.readTree(p);
LinkedList<GrantedAuthority> grantedAuthorities = new LinkedList<>();
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
JsonNode next = elements.next();
JsonNode authority = next.get("authority");
//将得到的值放入链表 最终返回该链表
grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
}
return grantedAuthorities;
}
}

@ -0,0 +1,43 @@
package com.baiye.feign;
import com.baiye.model.dto.UserDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Set;
/**
* @author Enzo
* @date : 2022/1/11
*/
@FeignClient(contextId = "remoteUserService", value = "ad-platform-management")
public interface RemoteUserService {
/**
*
* @param username
* @return
*/
@GetMapping("/api/users/info/findByName")
UserDto findByName(@RequestParam("username") String username);
/**
*
* @param user
* @return
*/
@PostMapping("/api/users/info/deptIds")
List<Long> getDeptIds(@RequestBody UserDto user);
/**
*
* @param user
* @return
*/
@PostMapping("/api/roles/user/authority")
Set<String> mapToGrantedAuthorities(@RequestBody UserDto user);
}

@ -13,9 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.config.bean;
package com.baiye.properties;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Jwt
@ -23,7 +26,10 @@ import lombok.Data;
* @author Zheng Jie
* @date 20191128
*/
@Data
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "jwt")
public class SecurityProperties {
/**

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.config.bean;
package com.baiye.properties.bean;
import lombok.Data;

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.config.bean;
package com.baiye.properties.bean;
/**
*

@ -1,19 +1,4 @@
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version loginCode.length.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-loginCode.length.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.config.bean;
package com.baiye.properties.bean;
import com.baiye.exception.BadConfigurationException;
import com.wf.captcha.*;

@ -0,0 +1,49 @@
package com.baiye.security;
import com.baiye.constant.SecurityConstants;
import com.baiye.security.TokenProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
/**
* @author Enzo
* @date : 2022/1/12
*/
@Slf4j
@Component
@RequiredArgsConstructor
class PrincipalHandshakeHandler implements HandshakeInterceptor {
private final TokenProvider tokenProvider;
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
//获取参数
String token = serverHttpRequest.getServletRequest().getParameter(SecurityConstants.AUTHORIZATION);
attributes.put("token", token);
if (StringUtils.isNotBlank(token)) {
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
return Boolean.TRUE;
}
return Boolean.FALSE;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}

@ -0,0 +1,108 @@
package com.baiye.security;
import com.baiye.properties.SecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import reactor.util.annotation.NonNull;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author Enzo
* @date : 2022/1/11
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class SocketTokenFilter extends OncePerRequestFilter {
private final SecurityProperties securityProperties;
private final TokenProvider tokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse httpServletResponse, @NonNull FilterChain filterChain)
throws ServletException, IOException {
// http连接时客户端应该是在头信息中携带令牌
String authorizationHeader = request.getHeader(securityProperties.getHeader());
if (StringUtils.isBlank(authorizationHeader)) {
// websocket连接时令牌放在url参数上以后重构
authorizationHeader = request.getParameter(securityProperties.getHeader());
}
String token = null;
if (!StringUtils.isEmpty(authorizationHeader) && authorizationHeader.startsWith(securityProperties.getTokenStartWith())) {
token = authorizationHeader.replace(securityProperties.getTokenStartWith(), "");
}
//验证token
if (StringUtils.isNotBlank(token)) {
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
// TODO 修改权限传递token
/* TokenFilter.ModifyParametersWrapper mParametersWrapper = new TokenFilter.ModifyParametersWrapper((HttpServletRequest) request);
mParametersWrapper.putHeader(SecurityConstants.AUTHORIZATION, authorizationHeader);
filterChain.doFilter(mParametersWrapper, httpServletResponse);*/
log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), request.getRequestURI());
}
filterChain.doFilter(request, httpServletResponse);
}
/**
* HttpServletRequestWrapperHttpServletRequest
*/
private static class ModifyParametersWrapper extends HttpServletRequestWrapper {
private final Map<String, String> customHeaders;
ModifyParametersWrapper(HttpServletRequest request) {
super(request);
this.customHeaders = new HashMap<>();
}
void putHeader(String name, String value) {
this.customHeaders.put(name, value);
}
@Override
public String getHeader(String name) {
// check the custom headers first
String headerValue = customHeaders.get(name);
if (headerValue != null) {
return headerValue;
}
// else return from into the original wrapped object
return ((HttpServletRequest) getRequest()).getHeader(name);
}
@Override
public Enumeration<String> getHeaderNames() {
// create a set of the custom header names
Set<String> set = new HashSet<>(customHeaders.keySet());
// now add the headers from the wrapped request object
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
// add the names of the request headers into the list
String n = e.nextElement();
set.add(n);
}
// create an enumeration from the set and return
return Collections.enumeration(set);
}
}
}

@ -13,18 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.security;
package com.baiye.security;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.properties.SecurityProperties;
import com.baiye.util.RedisUtils;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
@ -88,7 +87,7 @@ public class TokenProvider implements InitializingBean {
* @param token /
* @return /
*/
Authentication getAuthentication(String token) {
public Authentication getAuthentication(String token) {
Claims claims = getClaims(token);
User principal = new User(claims.getSubject(), "******", new ArrayList<>());
return new UsernamePasswordAuthenticationToken(principal, token, new ArrayList<>());
@ -103,7 +102,7 @@ public class TokenProvider implements InitializingBean {
/**
* @param token token
*/
public void checkRenewal(String token) {
public boolean checkRenewal(String token) {
// 判断是否续期token,计算token的过期时间
long time = redisUtils.getExpire(properties.getOnlineKey() + token) * 1000;
Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
@ -113,7 +112,9 @@ public class TokenProvider implements InitializingBean {
if (differ <= properties.getDetect()) {
long renew = time + properties.getRenew();
redisUtils.expire(properties.getOnlineKey() + token, renew, TimeUnit.MILLISECONDS);
return true;
}
return false;
}
public String getToken(HttpServletRequest request) {

@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.baiye.modules.security.service;
package com.baiye.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@ -13,16 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.service;
package com.baiye.service;
import com.baiye.exception.BadRequestException;
import com.baiye.modules.security.config.bean.LoginProperties;
import com.baiye.modules.security.service.dto.JwtUserDto;
import com.baiye.modules.system.service.DataService;
import com.baiye.modules.system.service.RoleService;
import com.baiye.modules.system.service.UserService;
import com.baiye.modules.system.service.dto.UserDto;
import com.baiye.feign.RemoteUserService;
import com.baiye.model.dto.JwtUserDto;
import com.baiye.model.dto.UserDto;
import com.baiye.properties.bean.LoginProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@ -30,8 +29,10 @@ import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* @author Zheng Jie
@ -40,9 +41,10 @@ import java.util.concurrent.atomic.AtomicInteger;
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserService userService;
private final RoleService roleService;
private final DataService dataService;
private final RemoteUserService remoteUserService;
private final LoginProperties loginProperties;
public void setEnableCache(boolean enableCache) {
@ -51,10 +53,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
/**
*
*
* @see {@link UserCacheClean}
*/
static final Map<String, Future<JwtUserDto>> USER_DTO_CACHE = new ConcurrentHashMap<>();
public static ExecutorService executor = newThreadPool();
@ -66,7 +65,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
if (!loginProperties.isCacheEnable()) {
UserDto user;
try {
user = userService.findByName(username);
user = remoteUserService.findByName(username);
} catch (EntityNotFoundException e) {
// SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
throw new UsernameNotFoundException("", e);
@ -77,10 +76,13 @@ public class UserDetailsServiceImpl implements UserDetailsService {
if (!user.getEnabled()) {
throw new BadRequestException("账号未激活!");
}
Set<String> strings = remoteUserService.mapToGrantedAuthorities(user);
jwtUserDto = new JwtUserDto(
user,
dataService.getDeptIds(user),
roleService.mapToGrantedAuthorities(user)
remoteUserService.getDeptIds(user),
strings.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList())
);
}
return jwtUserDto;
@ -110,7 +112,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
// 检查dataScope是否修改
List<Long> dataScopes = jwtUserDto.getDataScopes();
dataScopes.clear();
dataScopes.addAll(dataService.getDeptIds(jwtUserDto.getUser()));
dataScopes.addAll(remoteUserService.getDeptIds(jwtUserDto.getUser()));
}
return jwtUserDto;
@ -120,7 +122,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
private JwtUserDto getJwtBySearchDb(String username) {
UserDto user;
try {
user = userService.findByName(username);
user = remoteUserService.findByName(username);
} catch (EntityNotFoundException e) {
// SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
throw new UsernameNotFoundException("", e);
@ -131,13 +133,13 @@ public class UserDetailsServiceImpl implements UserDetailsService {
if (!user.getEnabled()) {
throw new BadRequestException("账号未激活!");
}
Set<String> strings = remoteUserService.mapToGrantedAuthorities(user);
return new JwtUserDto(
user,
dataService.getDeptIds(user),
roleService.mapToGrantedAuthorities(user)
user, remoteUserService.getDeptIds(user),
strings.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList())
);
}
}
public static ExecutorService newThreadPool() {

@ -0,0 +1,57 @@
package com.baiye.util;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
* @author Enzo
* @date : 2022/1/11
*/
public class AdUser extends User {
private static final long serialVersionUID = -66600042157219036L;
/**
* ID
*/
@Getter
private final Integer id;
/**
* ID
*/
@Getter
private final Integer deptId;
/**
* Construct the <code>User</code> with the details required by
* {@link DaoAuthenticationProvider}.
* @param id ID
* @param deptId ID
* @param username the username presented to the
* <code>DaoAuthenticationProvider</code>
* @param password the password that should be presented to the
* <code>DaoAuthenticationProvider</code>
* @param enabled set to <code>true</code> if the user is enabled
* @param accountNonExpired set to <code>true</code> if the account has not expired
* @param credentialsNonExpired set to <code>true</code> if the credentials have not
* expired
* @param accountNonLocked set to <code>true</code> if the account is not locked
* @param authorities the authorities that should be granted to the caller if they
* presented the correct username and password and the user is enabled. Not null.
* @throws IllegalArgumentException if a <code>null</code> value was passed either as
* a parameter or as an element in the <code>GrantedAuthority</code> collection
*/
public AdUser(Integer id, Integer deptId, String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.id = id;
this.deptId = deptId;
}
}

@ -20,6 +20,7 @@ import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baiye.exception.BadRequestException;
import com.baiye.model.dto.JwtUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
@ -31,14 +32,19 @@ import java.util.List;
/**
*
*
* @author Zheng Jie
* @date 2019-01-17
*/
@Slf4j
public class SecurityUtils {
private SecurityUtils() {
}
/**
*
*
* @return UserDetails
*/
public static UserDetails getCurrentUser() {
@ -70,6 +76,7 @@ public class SecurityUtils {
/**
* ID
*
* @return ID
*/
public static Long getCurrentUserId() {
@ -79,20 +86,23 @@ public class SecurityUtils {
/**
*
*
* @return /
*/
public static List<Long> getCurrentUserDataScope(){
public static List<Long> getCurrentUserDataScope() {
UserDetails userDetails = getCurrentUser();
JSONArray array = JSONUtil.parseArray(new JSONObject(userDetails).get("dataScopes"));
return JSONUtil.toList(array,Long.class);
return JSONUtil.toList(array, Long.class);
}
/**
*
*
* @return
*/
public static String getDataScopeType() {
List<Long> dataScopes = getCurrentUserDataScope();
if(dataScopes.size() != 0){
if (dataScopes.size() != 0) {
return "";
}
return "全部的数据权限";
@ -100,9 +110,10 @@ public class SecurityUtils {
/**
*
*
* @return
*/
public static JSONObject getUser(){
public static JSONObject getUser() {
UserDetails userDetails = getCurrentUser();
return new JSONObject(new JSONObject(userDetails).get("user"));
}

@ -0,0 +1,17 @@
#jwt
jwt:
header: Authorization
# 令牌前缀
token-start-with: Bearer
# 必须使用最少88位的Base64对该令牌进行编码
base64-secret: ZmQ0ZGI5NjQ0MDQwY2I4MjMxY2Y3ZmI3MjdhN2ZmMjNhODViOTg1ZGE0NTBjMGM4NDA5NzYxMjdjOWMwYWRmZTBlZjlhNGY3ZTg4Y2U3YTE1ODVkZDU5Y2Y3OGYwZWE1NzUzNWQ2YjFjZDc0NGMxZWU2MmQ3MjY1NzJmNTE0MzI=
# 令牌过期时间 此处单位/毫秒 默认2小时可在此网站生成 https://www.convertworld.com/zh-hans/time/milliseconds.html
token-validity-in-seconds: 7200000
# 在线用户key
online-key: online-token-
# 验证码
code-key: code-key-
# token 续期检查时间范围默认30分钟单位默认毫秒在token即将过期的一段时间内用户操作了则给用户的token续期
detect: 1800000
# 续期时间范围,默认 1小时这里单位毫秒
renew: 3600000

@ -1,22 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ad-platform</artifactId>
<groupId>com.baiye</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ad-platform-common</artifactId>
<artifactId>ad-platform-common-core</artifactId>
<name>ad-platform-comm-core</name>
<description>ad-platform-common-core</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.dangdang</groupId>
@ -29,33 +28,13 @@
</exclusion>
</exclusions>
</dependency>
<!-- springboot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- &lt;!&ndash; 排除默认的logback日志使用log4j&ndash;&gt;
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>-->
</dependency>
<!-- &lt;!&ndash; spring-boot test &ndash;&gt;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@ -122,8 +101,8 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
</dependencies>
</dependencies>
</project>

@ -0,0 +1,44 @@
/*
* Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.annotation;
import java.lang.annotation.*;
/**
*
*
* @author lengleng
* @date 2020-06-14
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Inner {
/**
* AOP
* @return false, true
*/
boolean value() default true;
/**
* ()
* @return {}
*/
String[] field() default {};
}

@ -11,6 +11,10 @@ public class DefaultNumberConstants {
private DefaultNumberConstants() {
}
/**
* -2
*/
public static final int MINUS_TWO_NUMBER = -2;
/**
* -1

@ -1,5 +1,6 @@
package com.baiye.http;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;

@ -0,0 +1,119 @@
package com.baiye.http;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author
* "" NULL json
* @param <T>
*/
@JsonSerialize
@Getter
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@NoArgsConstructor
public class WebSocketResponse<T> implements Serializable {
private static final long serialVersionUID = -7237947628886320124L;
/**
* 0, 1,
*/
private int code;
/**
*
*/
private String type;
/**
*
*/
private T data;
/*
*/
private WebSocketResponse(String type) {
this.type = type;
}
private WebSocketResponse(String type, T data) { // ps: 当调用T为String类型时候,会默认调用下面的ServerResponse(int status, String msg)类型的构造器
this.type = type;
this.data = data;
}
private WebSocketResponse(String type, Integer code, T data) {
this.type = type;
this.code = code;
this.data = data;
}
private WebSocketResponse(String type, Integer code) {
this.type = type;
this.code = code;
}
/*
,,
*/
/**
*
*/
public static <T> WebSocketResponse<T> createBySuccess() {
return new WebSocketResponse<>(ResponseCode.SUCCESS.getDesc(),HttpStatus.HTTP_OK);
}
/**
*
*/
public static <T> WebSocketResponse<T> createBySuccess(String type) {
return new WebSocketResponse<>(type,HttpStatus.HTTP_OK);
}
/**
*
*/
public static <T> WebSocketResponse<T> createBySuccess(String type,T data) {
return new WebSocketResponse<>(type, HttpStatus.HTTP_OK, data);
}
/**
*
*/
public static <T> WebSocketResponse<T> createBySuccess(String type,Integer code, T data) {
return new WebSocketResponse<>(type, code, data);
}
/*
,,
*/
/**
* ()
*/
public static <T> WebSocketResponse<T> createByErrorMessage(String errorMessage){
return new WebSocketResponse<>(errorMessage, ResponseCode.ERROR.getCode());
}
/**
* ()()
*/
public static <T> WebSocketResponse<T> createByErrorCodeMessage(String type, Integer code){
return new WebSocketResponse<>(type, code);
}
}

@ -1,8 +1,6 @@
package com.baiye.feign;
package com.baiye.socket.filter;
import com.baiye.constant.SecurityConstants;
import com.baiye.exception.CallException;
import com.baiye.http.ResponseCode;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
@ -24,11 +22,10 @@ public class FeignConfiguration implements RequestInterceptor {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI();
// HeaderConstants.TOKEN_HEADER_NAME 替换为自己的请求头名称,下同
String token = request.getHeader(SecurityConstants.AUTHORIZATION);
if (token == null && !FeignProvider.getDefaultSkipUrl().contains(uri)) {
throw new CallException(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
if (token == null) {
token = request.getParameter(SecurityConstants.AUTHORIZATION);
}
requestTemplate.header(SecurityConstants.AUTHORIZATION, token);
}

@ -1,4 +1,4 @@
package com.baiye.feign;
package com.baiye.socket.filter;
import java.util.ArrayList;
@ -15,6 +15,9 @@ public class FeignProvider {
static {
DEFAULT_SKIP_URL.add("/swagger/**");
DEFAULT_SKIP_URL.add("/api/users/user/findByName");
DEFAULT_SKIP_URL.add("/api/users/user/findByName");
DEFAULT_SKIP_URL.add("/api/roles/user/authority");
}

@ -32,11 +32,11 @@ public class PageUtil<T> extends cn.hutool.core.util.PageUtil {
/**
* List
*/
public static List toPage(int page, int size , List list) {
public static <T> List<T> toPage(int page, int size , List<T> list) {
int fromIndex = page * size;
int toIndex = page * size + size;
if(fromIndex > list.size()){
return new ArrayList();
return new ArrayList<>();
} else if(toIndex >= list.size()) {
return list.subList(fromIndex,list.size());
} else {
@ -47,7 +47,7 @@ public class PageUtil<T> extends cn.hutool.core.util.PageUtil {
/**
* Page redis
*/
public static Map<String,Object> toPage(Page page) {
public static <T> Map<String,Object> toPage(Page<T> page) {
Map<String,Object> map = new LinkedHashMap<>(2);
map.put("content",page.getContent());
map.put("totalElements",page.getTotalElements());

@ -43,8 +43,6 @@ public class RedisUtils {
private RedisTemplate<Object, Object> redisTemplate;
private String onlineKey = "online-token-";

@ -20,7 +20,9 @@ import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@ -30,6 +32,8 @@ import java.util.List;
* @date 2019-01-07
*/
@Slf4j
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
@ -42,7 +46,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
*
* @param callBack
*/
public synchronized static void addCallBacks(CallBack callBack) {
public static synchronized void addCallBacks(CallBack callBack) {
if (addCallback) {
SpringContextHolder.CALL_BACKS.add(callBack);
} else {

@ -1,114 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 通用的 log4j2 依赖配置 -->
<!--Configuration后面的status这个用于设置log4j2自身内部的信息输出可以不设置当设置成trace时你会看到log4j2内部各种详细输出-->
<!--monitorIntervalLog4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration monitorInterval="5">
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--变量配置-->
<Properties>
<!-- 格式化输出:%date表示日期%thread表示线程名%-5level级别从左显示5个字符宽度 %msg日志消息%n是换行符-->
<!-- %logger{36} 表示 Logger 名字最长36个字符 -->
<!--
%d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间,输出到毫秒的时间
%-5level : 输出日志级别,-5表示左对齐并且固定输出5个字符如果不足在右边补0
%c : logger的名称(%logger)
%t : 输出当前线程名称
%p : 日志输出格式
%m : 日志内容,即 logger.info("message")
%n : 换行符
%C : Java类名(%F)
%L : 行号
%M : 方法名
%l : 输出语句所在的行数, 包括类名、方法名、文件名、行数
hostName : 本地机器名
hostAddress : 本地ip地址
<property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
-->
<!-- 定义日志存储的路径 -->
<property name="FILE_PATH" value="更换为你的日志路径" />
<property name="FILE_NAME" value="更换为你的项目名" />
</Properties>
<appenders>
<console name="Console" target="SYSTEM_OUT">
<!--输出日志的格式-->
<PatternLayout pattern="${LOG_PATTERN}"/>
<!--控制台只输出level及其以上级别的信息onMatch其他的直接拒绝onMismatch-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</console>
<!--文件会打印出所有信息这个log每次运行程序会自动清空由append属性决定适合临时测试用-->
<File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">
<PatternLayout pattern="${LOG_PATTERN}"/>
</File>
<!-- 这个会打印出所有的info及以下级别的信息每次大小超过size则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息onMatch其他的直接拒绝onMismatch-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的warn及以下级别的信息每次大小超过size则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息onMatch其他的直接拒绝onMismatch-->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的error及以下级别的信息每次大小超过size则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息onMatch其他的直接拒绝onMismatch-->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
</appenders>
<!--Logger节点用来单独指定日志的形式比如要为指定包下的class指定不同的日志级别等。-->
<!--然后定义loggers只有定义了logger并引入的appenderappender才会生效-->
<loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.mybatis" level="info" additivity="false">
<AppenderRef ref="Console"/>
</logger>
<!--监控系统信息-->
<!--若是additivity设为false则 子Logger 只会在自己的appender里输出而不会在 父Logger 的appender里输出。-->
<Logger name="org.springframework" level="info" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="Filelog"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>
</configuration>

@ -21,7 +21,7 @@
<!-- 通用依赖 -->
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common</artifactId>
<artifactId>ad-platform-common-core</artifactId>
<version>1.0-SNAPSHOT</version>
<exclusions>
<exclusion>

@ -1,7 +1,7 @@
package com.baiye.config;
import com.baiye.filter.PasswordDecoderFilter;
import com.baiye.filter.ValidateCodeGatewayFilter;
import com.baiye.socket.filter.PasswordDecoderFilter;
import com.baiye.socket.filter.ValidateCodeGatewayFilter;
import com.baiye.handler.GlobalGateWayExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@ -1,4 +1,4 @@
package com.baiye.filter;
package com.baiye.socket.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;

@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.baiye.filter;
package com.baiye.socket.filter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;

@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.baiye.filter;
package com.baiye.socket.filter;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;

@ -45,3 +45,4 @@ hystrix:
isolation:
thread:
timeoutInMilliseconds: 1000

@ -20,7 +20,7 @@
<dependencies>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common</artifactId>
<artifactId>ad-platform-common-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
@ -56,12 +56,6 @@
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 通用依赖 -->
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.system.service.dto;
package com.baiye.model.dto;
import lombok.Data;

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.system.service.dto;
package com.baiye.model.dto;
import lombok.Data;
import lombok.NoArgsConstructor;

@ -14,14 +14,14 @@
* limitations under the License.
*/
package com.baiye.modules.security.service.dto;
package com.baiye.model.dto;
import com.baiye.modules.system.service.dto.UserDto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@ -34,6 +34,8 @@ import java.util.stream.Collectors;
@AllArgsConstructor
public class JwtUserDto implements UserDetails {
private static final long serialVersionUID = -1054997179383048319L;
private final UserDto user;
private final List<Long> dataScopes;

@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.security.service.dto;
package com.baiye.model.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.system.service.dto;
package com.baiye.model.dto;
import lombok.Data;

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baiye.modules.system.service.dto;
package com.baiye.model.dto;
import com.baiye.model.base.BaseDTO;
import lombok.Getter;
@ -31,6 +31,8 @@ import java.util.Set;
@Setter
public class UserDto extends BaseDTO implements Serializable {
private static final long serialVersionUID = -8826058649124662423L;
private Long id;
private Set<RoleSmallDto> roles;

@ -1,7 +1,6 @@
package com.baiye.model.entity;
import com.baiye.util.JpaConverterAes;
import com.baiye.util.JpaConverterListJson;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
@ -10,7 +9,6 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
/**

@ -29,7 +29,7 @@ public enum WebSocketEnums {
/**
*
*/
FILE(4, "file"),
FILE(4, "recovery"),
/**
*

@ -27,9 +27,18 @@
<!-- 通用依赖 -->
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common</artifactId>
<artifactId>ad-platform-common-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- 验证auth -->
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-common-auth</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>ad-platform-pojo</artifactId>
@ -42,10 +51,7 @@
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
</dependency>
<!--Spring boot 安全框架-->
<dependency>
@ -53,21 +59,7 @@
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
</dependency>
<!-- 获取系统信息 -->
<dependency>
@ -103,11 +95,7 @@
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--feign 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>

@ -1,12 +1,10 @@
package com.baiye;
import com.baiye.util.SpringContextHolder;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
@ -26,6 +24,6 @@ public class AdPlatformManagementApplication {
SpringApplication.run(AdPlatformManagementApplication.class, args);
}
@Bean
public SpringContextHolder springContextHolder() {return new SpringContextHolder();}
}

@ -17,13 +17,13 @@ package com.baiye.modules.security.config;
import com.baiye.annotation.AnonymousAccess;
import com.baiye.model.enums.RequestMethodEnum;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.modules.security.security.JwtAccessDeniedHandler;
import com.baiye.modules.security.security.JwtAuthenticationEntryPoint;
import com.baiye.modules.security.security.TokenConfigurer;
import com.baiye.modules.security.security.TokenProvider;
import com.baiye.modules.security.service.OnlineUserService;
import com.baiye.modules.security.service.UserCacheClean;
import com.baiye.service.UserCacheClean;
import com.baiye.properties.SecurityProperties;
import com.baiye.security.TokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
@ -32,6 +32,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
@ -122,14 +123,13 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/file/**").permitAll()
// 阿里巴巴 druid
.antMatchers("/druid/**").permitAll()
.antMatchers("/api/task/saveTask").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// TODO 权限待测试 Enzo
.antMatchers("/api/task/saveTask").permitAll()
.antMatchers( "/api/users/admin").permitAll()
.antMatchers( "/api/task/query").permitAll()
.antMatchers( "/api/organize/queryAll").permitAll()
.antMatchers("/api/users/info/findByName").permitAll()
.antMatchers("/api/users/info/deptIds").permitAll()
.antMatchers("/api/roles/user/authority").permitAll()
.antMatchers( "/api/report/organize").permitAll()
.antMatchers( "/api/download/task").permitAll()
// 自定义匿名访问所有url放行允许匿名和带Token访问细腻化到每个 Request 类型
@ -198,4 +198,11 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
return anonymousUrls;
}
@Override
public void configure(WebSecurity webSecurity){
webSecurity.ignoring().antMatchers(
"/ws/**"
);
}
}

@ -21,13 +21,13 @@ import com.baiye.annotation.rest.AnonymousGetMapping;
import com.baiye.annotation.rest.AnonymousPostMapping;
import com.baiye.config.properties.RsaProperties;
import com.baiye.exception.BadRequestException;
import com.baiye.modules.security.config.bean.LoginCodeEnum;
import com.baiye.modules.security.config.bean.LoginProperties;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.modules.security.security.TokenProvider;
import com.baiye.model.dto.JwtUserDto;
import com.baiye.modules.security.service.OnlineUserService;
import com.baiye.modules.security.service.dto.AuthUserDto;
import com.baiye.modules.security.service.dto.JwtUserDto;
import com.baiye.properties.SecurityProperties;
import com.baiye.properties.bean.LoginCodeEnum;
import com.baiye.properties.bean.LoginProperties;
import com.baiye.security.TokenProvider;
import com.baiye.util.RedisUtils;
import com.baiye.util.RsaUtils;
import com.baiye.util.SecurityUtils;

@ -15,9 +15,10 @@
*/
package com.baiye.modules.security.security;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.modules.security.service.OnlineUserService;
import com.baiye.modules.security.service.UserCacheClean;
import com.baiye.service.UserCacheClean;
import com.baiye.properties.SecurityProperties;
import com.baiye.security.TokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;

@ -17,12 +17,12 @@ package com.baiye.modules.security.security;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.model.dto.OnlineUserDto;
import com.baiye.modules.security.service.OnlineUserService;
import com.baiye.modules.security.service.UserCacheClean;
import com.baiye.modules.security.service.dto.OnlineUserDto;
import com.baiye.service.UserCacheClean;
import com.baiye.properties.SecurityProperties;
import com.baiye.security.TokenProvider;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;

@ -16,9 +16,9 @@
package com.baiye.modules.security.service;
import cn.hutool.json.JSONUtil;
import com.baiye.modules.security.config.bean.SecurityProperties;
import com.baiye.modules.security.service.dto.JwtUserDto;
import com.baiye.modules.security.service.dto.OnlineUserDto;
import com.baiye.model.dto.JwtUserDto;
import com.baiye.model.dto.OnlineUserDto;
import com.baiye.properties.SecurityProperties;
import com.baiye.util.*;
import lombok.extern.slf4j.Slf4j;
@ -65,6 +65,7 @@ public class OnlineUserService {
log.error(e.getMessage(),e);
}
redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000);
redisUtils.set(token, jwtUserDto.getUser().getId(), properties.getTokenValidityInSeconds()/1000);
}
/**

@ -22,6 +22,7 @@ import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
/**
@ -68,13 +69,13 @@ public class MessageNotification implements Serializable {
private Boolean isReuse;
@Column(name = "type")
@Column(name = "message_type")
@ApiModelProperty(value = "类型 1公告 2自提醒")
private Integer type;
private Integer messageType;
@Column(name = "point_time")
@ApiModelProperty(value = "时间点")
private Integer pointTime;
private Date pointTime;
@Column(name = "create_by")
@ApiModelProperty(value = "创建者")

@ -1,6 +1,6 @@
package com.baiye.modules.system.domain;
import com.baiye.modules.system.service.dto.UserDto;
import com.baiye.model.dto.UserDto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.*;

@ -17,8 +17,14 @@ package com.baiye.modules.system.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
@ -33,6 +39,7 @@ import java.sql.Timestamp;
@Entity
@Data
@Table(name="tb_user_message")
@EntityListeners(AuditingEntityListener.class)
public class UserMessage implements Serializable {
private static final long serialVersionUID = -1582474376747148049L;
@ -47,13 +54,17 @@ public class UserMessage implements Serializable {
@ApiModelProperty(value = "消息id")
private Long messageId;
@Column(name = "type")
@Column(name = "message_type")
@ApiModelProperty(value = "消息类型")
private Integer messageType;
@Column(name = "status")
@ApiModelProperty(value = "消息状态")
private Integer type;
private Integer status;
@Column(name = "is_read")
@ApiModelProperty(value = "是否已读")
private Boolean isRead = Boolean.TRUE;
private Boolean isRead = Boolean.FALSE;
@Column(name = "start_time")
@ApiModelProperty(value = "开始时间")
@ -91,10 +102,13 @@ public class UserMessage implements Serializable {
@ApiModelProperty(value = "更新者")
private String updateBy;
@CreationTimestamp
@Column(name = "create_time")
@ApiModelProperty(value = "创建日期")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DatePattern.NORM_DATETIME_PATTERN, timezone = "GMT+8")
private Timestamp createTime;
@LastModifiedDate
@Column(name = "update_time")
@ApiModelProperty(value = "更新时间")
private Timestamp updateTime;

@ -16,6 +16,8 @@
package com.baiye.modules.system.repository;
import com.baiye.modules.system.domain.UserMessage;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
@ -36,8 +38,8 @@ public interface UserMessageRepository extends JpaRepository<UserMessage, Long>,
* @return
*/
@Modifying
@Query(value = "update UserMessage set type = ?1 where messageId = ?2")
Boolean deleteUserMessageByMessageId(Integer num, Long messageId);
@Query(value = "update UserMessage set status = ?1 where messageId = ?2")
int deleteUserMessageByMessageId(Integer num, Long messageId);
/**
*
@ -47,5 +49,28 @@ public interface UserMessageRepository extends JpaRepository<UserMessage, Long>,
*/
@Modifying
@Query(value = "update UserMessage set isRead = ?1 where id = ?2")
Boolean updateUserMessageIsReadById(Boolean aTrue, Long aLong);
int updateUserMessageIsReadById(Boolean aTrue, Long aLong);
/**
*
* @param isTop
* @param id
* @return
*/
@Modifying
@Query(value = "update UserMessage set isTop = ?1 where messageId = ?2")
int updateIsTopByMessageId(Boolean isTop, Long id);
/**
*
* @param isTop
* @param id
* @return
*/
@Modifying
@Query(value = "update UserMessage set isTop = ?1 where id = ?2")
int changeMessageIsTop(Boolean isTop, Long id);
}

@ -16,7 +16,6 @@
package com.baiye.modules.system.rest;
import com.baiye.modules.system.service.MessageNotificationService;
import com.baiye.modules.system.service.dto.MessageNotificationDto;
import com.baiye.modules.system.service.dto.MessageNotificationQueryCriteria;
import com.baiye.util.SecurityUtils;
import io.swagger.annotations.Api;
@ -25,7 +24,6 @@ import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
@ -59,13 +57,13 @@ public class MessageNotificationController {
@PostMapping("/createMessage")
@ApiOperation("新增message")
public ResponseEntity<Object> create(@RequestBody String body){
return new ResponseEntity<>(messageNotificationService.create(body),HttpStatus.CREATED);
public ResponseEntity<Object> create(@RequestParam("body") String body,@RequestParam Long userId){
return new ResponseEntity<>(messageNotificationService.create(body,userId), HttpStatus.CREATED);
}
@PutMapping("changeMessage")
@PostMapping("changeMessage")
@ApiOperation("修改message")
public ResponseEntity<Object> update(@RequestBody String body){
messageNotificationService.update(body);

@ -16,12 +16,14 @@
package com.baiye.modules.system.rest;
import cn.hutool.core.lang.Dict;
import com.baiye.annotation.Inner;
import com.baiye.exception.BadRequestException;
import com.baiye.model.dto.UserDto;
import com.baiye.modules.system.domain.Role;
import com.baiye.modules.system.service.RoleService;
import com.baiye.modules.system.service.dto.RoleDto;
import com.baiye.modules.system.service.dto.RoleQueryCriteria;
import com.baiye.modules.system.service.dto.RoleSmallDto;
import com.baiye.model.dto.RoleSmallDto;
import com.baiye.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -54,6 +56,15 @@ public class RoleController {
private static final String ENTITY_NAME = "role";
@Inner
@ApiOperation("获取单个role")
@PostMapping(value = "/user/authority")
public Set<String> authority(@RequestBody UserDto userDto){
return roleService.getUserPermissions(userDto);
}
@ApiOperation("获取单个role")
@GetMapping(value = "/{id}")
@PreAuthorize("@el.check('roles:list')")
@ -133,6 +144,8 @@ public class RoleController {
return new ResponseEntity<>(HttpStatus.OK);
}
/**
*
* @return /

@ -20,9 +20,11 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baiye.annotation.Inner;
import com.baiye.config.properties.RsaProperties;
import com.baiye.constant.RoleNumberConstants;
import com.baiye.exception.BadRequestException;
import com.baiye.model.dto.UserDto;
import com.baiye.model.dto.UserFavorOfExcel;
import com.baiye.modules.system.domain.Dept;
import com.baiye.modules.system.domain.User;
@ -31,8 +33,7 @@ import com.baiye.modules.system.service.DataService;
import com.baiye.modules.system.service.DeptService;
import com.baiye.modules.system.service.RoleService;
import com.baiye.modules.system.service.UserService;
import com.baiye.modules.system.service.dto.RoleSmallDto;
import com.baiye.modules.system.service.dto.UserDto;
import com.baiye.model.dto.RoleSmallDto;
import com.baiye.modules.system.service.dto.UserQueryCriteria;
import com.baiye.util.PageUtil;
import com.baiye.util.RsaUtils;
@ -211,6 +212,26 @@ public class UserController {
}
}
/**
*
*
* @return
*/
@GetMapping("/info/findByName")
@ApiOperation("名称查询")
public UserDto info(@RequestParam("username") String username) {
return userService.findByName(username);
}
@Inner
@PostMapping("/info/deptIds")
@ApiOperation("查找部门")
public List<Long> info(@RequestBody UserDto user) {
return dataService.getDeptIds(user);
}
@ApiOperation("查询所有的管理员")
@PostMapping(value = "/admin")
public ResponseEntity<Object> getAdminInfo(@RequestBody List<Long> roleIds) {

@ -1,10 +1,8 @@
package com.baiye.modules.system.rest;
import com.baiye.constant.DefaultNumberConstants;
import com.baiye.exception.BadRequestException;
import com.baiye.http.CommonResponse;
import com.baiye.http.ResponseCode;
import com.baiye.modules.system.domain.Role;
import com.baiye.modules.system.domain.UserMessage;
import com.baiye.modules.system.service.UserMessageService;
import com.baiye.modules.system.service.dto.UserMessageQueryCriteria;
@ -13,6 +11,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
@ -33,9 +32,8 @@ public class UserMessageController {
@ApiOperation("查询任务(分页)")
@GetMapping("/queryAll")
public ResponseEntity<Object> queryAll(UserMessageQueryCriteria criteria) {
criteria.setType(DefaultNumberConstants.ONE_NUMBER);
criteria.setUserId(SecurityUtils.getCurrentUserId());
return new ResponseEntity<>(userMessageService.queryAll(criteria), HttpStatus.OK);
return new ResponseEntity<>(userMessageService.queryAll(criteria, criteria.getPage(), criteria.getSize()), HttpStatus.OK);
}
@ -46,22 +44,26 @@ public class UserMessageController {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@ApiOperation("创建小")
@PostMapping("/createMessage")
public CommonResponse<Boolean> create(String body) {
@ApiOperation("已读")
@PostMapping("/read")
public CommonResponse<Boolean> read(@RequestBody String body) {
if (StringUtils.isEmpty(body)) {
return CommonResponse.createByErrorMessage(ResponseCode.ERROR.getDesc());
}
return userMessageService.createUserMessage(body);
return userMessageService.read(body);
}
@ApiOperation("已读")
@PostMapping("/read")
public CommonResponse<Boolean> read(String body) {
@PostMapping("/top")
public CommonResponse<Boolean> messageTop(@RequestBody String body) {
if (StringUtils.isEmpty(body)) {
return CommonResponse.createByErrorMessage(ResponseCode.ERROR.getDesc());
}
return userMessageService.read(body);
userMessageService.messageTop(body);
return CommonResponse.createBySuccess();
}
}

@ -16,7 +16,7 @@
package com.baiye.modules.system.service;
import com.baiye.modules.system.service.dto.UserDto;
import com.baiye.model.dto.UserDto;
import java.util.List;

@ -56,10 +56,13 @@ public interface MessageNotificationService {
/**
*
* @param resources /
*
* @param resources \
* @param userId \
*
* @return MessageNotificationDto
*/
MessageNotificationDto create(String resources);
MessageNotificationDto create(String resources, Long userId);
/**
*
@ -81,11 +84,4 @@ public interface MessageNotificationService {
*/
void download(List<MessageNotificationDto> all, HttpServletResponse response) throws IOException;
/**
* body
* @param body
* @return
*/
Boolean withdrawMessage(String body);
}

@ -1,6 +1,7 @@
package com.baiye.modules.system.service;
import com.baiye.model.dto.OrganizeQueryCriteria;
import com.baiye.model.dto.UserDto;
import com.baiye.modules.system.domain.Organize;
import com.baiye.modules.system.domain.OrganizeUser;
import com.baiye.modules.system.domain.TaskOrganize;

@ -18,8 +18,8 @@ package com.baiye.modules.system.service;
import com.baiye.modules.system.domain.Role;
import com.baiye.modules.system.service.dto.RoleDto;
import com.baiye.modules.system.service.dto.RoleQueryCriteria;
import com.baiye.modules.system.service.dto.RoleSmallDto;
import com.baiye.modules.system.service.dto.UserDto;
import com.baiye.model.dto.RoleSmallDto;
import com.baiye.model.dto.UserDto;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority;
@ -134,4 +134,11 @@ public interface RoleService {
* @return /
*/
List<Role> findInMenuId(List<Long> menuIds);
/**
*
* @param userDto
* @return
*/
Set<String> getUserPermissions(UserDto userDto);
}

@ -46,9 +46,11 @@ public interface UserMessageService {
/**
*
* @param criteria
* @param page
* @param size
* @return List<UserMessageDto>
*/
List<UserMessageDto> queryAll(UserMessageQueryCriteria criteria);
Map<String, Object> queryAll(UserMessageQueryCriteria criteria, Integer page, Integer size);
/**
* ID
@ -94,24 +96,43 @@ public interface UserMessageService {
/**
*
*
* @param num
* @param messageId
* @return
*/
Boolean deleteAllByMessageId(Integer num, Long messageId);
Boolean deleteAllByMessageId(Integer num,Long messageId);
/**
*
*
* @param body
* @return
*/
CommonResponse<Boolean> createUserMessage(String body);
CommonResponse<Boolean> read(String body);
/**
*
*
* @param isTop
* @param id
* @return
*/
Boolean updateIsTopByMessage(Boolean isTop, Long id);
/**
*
* @param body
* @return
*/
CommonResponse<Boolean> read(String body);
UserMessageDto messageTop(String body);
/**
*
* @param message
* @param num
* @return
*/
UserMessageDto changeUserMessage(String message, int num);
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save