diff --git a/.idea/compiler.xml b/.idea/compiler.xml index a33e3a2..e82e326 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -7,11 +7,14 @@ - + + + + - + diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 79bdcc6..4f3820a 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -1,6 +1,12 @@ + + + + + + @@ -11,8 +17,12 @@ + + + + diff --git a/.idea/misc.xml b/.idea/misc.xml index 131a039..7750dd9 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -9,6 +9,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + - - - + + - + + + + + + + - - - @@ -340,7 +358,8 @@ - diff --git a/etl-auth/etl-auth-common/pom.xml b/etl-auth/etl-auth-common/pom.xml new file mode 100644 index 0000000..f1a8fab --- /dev/null +++ b/etl-auth/etl-auth-common/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.bwie + etl-auth + 1.0-SNAPSHOT + + pom + etl-auth-common + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + + + + com.bwie + etl-common + 1.0-SNAPSHOT + + + com.baomidou + mybatis-plus-boot-starter + + + org.springframework.boot + spring-boot-starter-jdbc + + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + io.swagger + swagger-annotations + 1.6.6 + compile + + + diff --git a/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/PathPermission.java b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/PathPermission.java new file mode 100644 index 0000000..43726c2 --- /dev/null +++ b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/PathPermission.java @@ -0,0 +1,33 @@ +package com.auth.common.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("t_data_source") +public class PathPermission { + @TableId(value = "id",type = IdType.AUTO) + private Integer id; + + @ApiModelProperty(value = "权限代号") + private String permissionCode; + + @ApiModelProperty(value = "路由层次") + private String hierarchy; + + @ApiModelProperty(value = "路由") + private String path; + + @ApiModelProperty(value = "功能描述") + private String description; + + @ApiModelProperty(value = "状态 0-废弃 1-正在使用") + private boolean status; +} diff --git a/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/RolesPermission.java b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/RolesPermission.java new file mode 100644 index 0000000..7860c7d --- /dev/null +++ b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/RolesPermission.java @@ -0,0 +1,24 @@ +package com.auth.common.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@TableName("t_role_source") +@AllArgsConstructor +@NoArgsConstructor +public class RolesPermission { + @TableId(value = "id",type = IdType.AUTO) + private Integer id; + + @ApiModelProperty(value = "权限代号") + private String permissionCode; + + @ApiModelProperty(value = "角色") + private String role; +} diff --git a/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/UserAccount.java b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/UserAccount.java new file mode 100644 index 0000000..db1f24e --- /dev/null +++ b/etl-auth/etl-auth-common/src/main/java/com/auth/common/entity/UserAccount.java @@ -0,0 +1,26 @@ +package com.auth.common.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@Data +@TableName("t_user") +public class UserAccount { + @TableId(value = "id",type = IdType.AUTO) + private Integer id; + + @ApiModelProperty("角色") + private String roles; + + @ApiModelProperty("名称") + private String username; + + @ApiModelProperty("密码/") + private String password; + +// @ApiModelProperty("uuid") +// private String UUID; +} diff --git a/etl-auth/etl-auth-common/src/main/java/com/auth/common/enums/PermissionConstants.java b/etl-auth/etl-auth-common/src/main/java/com/auth/common/enums/PermissionConstants.java new file mode 100644 index 0000000..25a97d9 --- /dev/null +++ b/etl-auth/etl-auth-common/src/main/java/com/auth/common/enums/PermissionConstants.java @@ -0,0 +1,13 @@ +package com.auth.common.enums; + +public class PermissionConstants { + public static final String ROLES = "roles"; + public static final String CODE_LIST = "codeList"; + public static final String ROLE = "role"; + public static final String PERMISSION_CODE = "permission_code"; + public static final String USER_CACHE_KEY = "user:username:"; + public static final String USER_KEY = "user:key:"; + public static final String USER_NAME = "username"; + + public static final String USER_ID = "userId"; +} diff --git a/etl-auth/etl-auth-server/pom.xml b/etl-auth/etl-auth-server/pom.xml new file mode 100644 index 0000000..9a080dc --- /dev/null +++ b/etl-auth/etl-auth-server/pom.xml @@ -0,0 +1,154 @@ + + + 4.0.0 + + com.bwie + etl-auth + 1.0-SNAPSHOT + + etl-auth-server + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + 2021.0.5.0 + + + + com.bwie + etl-auth-common + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.apache.shiro + shiro-spring + 1.4.0 + + + io.springfox + springfox-swagger2 + 3.0.0 + + + com.bwie + etl-jwt-manage + 1.0-SNAPSHOT + + + servlet-api + javax.servlet + + + + + com.bwie + etl-common + 1.0-SNAPSHOT + + + com.mysql + mysql-connector-j + + + com.github.xiaoymin + knife4j-spring-boot-starter + 3.0.3 + + + com.baomidou + mybatis-plus-boot-starter + 3.5.4.1 + + + org.projectlombok + lombok + + + org.springframework.cloud + spring-cloud-starter-bootstrap + 3.1.7 + + + + org.apache.shiro + shiro-spring + 1.4.0 + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.auth.server.EtlAuthServerApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/EtlAuthServerApplication.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/EtlAuthServerApplication.java new file mode 100644 index 0000000..b03809f --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/EtlAuthServerApplication.java @@ -0,0 +1,25 @@ +package com.auth.server; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@SpringBootApplication +@MapperScan("com.auth.server.mapper") +@ComponentScan(basePackages = {"com.etl.jwt.util", "com.etl.jwt.config", + "com.auth.server.controller","com.auth.server.service","com.auth.server.service.impl","com.auth.server.config"}) +public class EtlAuthServerApplication { + + public static void main(String[] args) { + SpringApplication.run(EtlAuthServerApplication.class, args); + } + + @Bean + public BCryptPasswordEncoder encryptPasswordEncoder(){ + return new BCryptPasswordEncoder(); + } + +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MD5s.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MD5s.java new file mode 100644 index 0000000..cacd61c --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MD5s.java @@ -0,0 +1,44 @@ +package com.auth.server.config; + + +import org.apache.http.util.TextUtils; +import org.apache.shiro.crypto.hash.HashRequest; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/* + * MD5 算法 + */ + +public class MD5s { + + public static String md5(String string) { + if (TextUtils.isEmpty(string)) { + return ""; + } + MessageDigest md5 = null; + try { + md5 = MessageDigest.getInstance("MD5"); + byte[] bytes = md5.digest(string.getBytes()); + String result = ""; + for (byte b : bytes) { + String temp = Integer.toHexString(b & 0xff); + if (temp.length() == 1) { + temp = "0" + temp; + } + result += temp; + } + return result; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + HashRequest request = new HashRequest.Builder() + .setAlgorithmName("MD5") // 使用 SHA-256 算法 + .setSource(string.getBytes()) // 要散列的密码(作为字节数组) + .build(); + //passwordService.encryptPassword(request); + return ""; + } + +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MvcConfig.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MvcConfig.java new file mode 100644 index 0000000..d9d7556 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/MvcConfig.java @@ -0,0 +1,18 @@ +//package com.auth.server.config; +//import com.auth.server.interceptor.UserInterceptor; +//import com.auth.server.mapper.UserMangeMapper; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +//@Configuration +//public class MvcConfig implements WebMvcConfigurer { +// @Autowired +// private UserMangeMapper userMangeMapper; +// @Override +// public void addInterceptors(InterceptorRegistry registry) { +// //添加拦截器,排除/路径和 /login路径 +// registry.addInterceptor(new UserInterceptor(userMangeMapper)) +// .excludePathPatterns("/","/user/login"); +// } +//} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/ShiroConfig.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/ShiroConfig.java new file mode 100644 index 0000000..0f29627 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/config/ShiroConfig.java @@ -0,0 +1,69 @@ +package com.auth.server.config; + + +import com.auth.server.util.UserRealm; +import org.apache.shiro.authc.credential.HashedCredentialsMatcher; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Configuration +public class ShiroConfig { + + //此处用于实现授权功能,配置需要拦截的接口 + //此处用于实现授权功能,配置需要拦截的接口 + @Bean + public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) { + ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); + shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); + //拦截页面 + Map filterMap = new LinkedHashMap<>(); + //登录/登出,所有人的权限 + filterMap.put("/user/login", "anon"); + filterMap.put("/user/logout", "anon"); + + shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap); + //未登录页面跳转 + shiroFilterFactoryBean.setLoginUrl("/user/show"); + //未有权限页面跳转 + shiroFilterFactoryBean.setUnauthorizedUrl("/user/unauthorized"); + + return shiroFilterFactoryBean; + } + + //注入对应的userRealm类 + @Bean + public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) { + DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager(); + SecurityManager.setRealm(userRealm); + return SecurityManager; + } + @Bean + public UserRealm userRealm() { + UserRealm userRealm = new UserRealm(); + //注册MD5加密 + userRealm.setCredentialsMatcher(hashedCredentialsMatcher()); + return userRealm; + } + + /** + * 设置shiro加密方式 + * @return HashedCredentialsMatcher + */ + @Bean + public HashedCredentialsMatcher hashedCredentialsMatcher(){ + HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); + // 使用md5 算法进行加密 + hashedCredentialsMatcher.setHashAlgorithmName("MD5"); + // 设置散列次数: 意为加密几次 + hashedCredentialsMatcher.setHashIterations(2); + + return hashedCredentialsMatcher; + } +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/LoginControler.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/LoginControler.java new file mode 100644 index 0000000..7aa273d --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/LoginControler.java @@ -0,0 +1,84 @@ +package com.auth.server.controller; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.nacos.api.model.v2.Result; +import com.auth.common.entity.UserAccount; +import com.auth.common.enums.PermissionConstants; +import com.auth.server.service.UserManageService; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.etl.common.enums.ResponseCodeEnum; +import com.etl.common.result.CommonResult; +import com.etl.jwt.util.JwtTokenUtil; +import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.mgt.DefaultSecurityManager; +import org.apache.shiro.realm.SimpleAccountRealm; +import org.apache.shiro.subject.Subject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * 登录 controller层 + */ +@RestController +@Slf4j +@Api(tags = "登录-API") +@RequestMapping("/user") +public class LoginControler { + @Autowired + private UserManageService userManageService; + + /** + * 用户登录 (使用用户名) + * + * @param user + * @return + */ + @ApiOperation(value = "用户登录") + @ApiOperationSupport(author = "liz") + @RequestMapping(value = "/login", method = RequestMethod.POST) + public Result userLogin(@RequestBody UserAccount user) { + + return userManageService.userLogin(user); + + } + + + /** + * 刷新JWT令牌,用旧的令牌换新的令牌 + * 参数为需要刷新的令牌 + * header中携带刷新令牌 + */ + + /** + * 当认证服务返回给客户端的 JWT 也就是 access_token 过期后,客户端如果需要再次通过发送登录请求重新拿到 access_token会使得用户体验很不友好。 + * 而JWT 生成后是不能篡改里面的内容,即使是 JWT 的有效期也不行。所以延长 access_token 有效期的做法并不适合,而且如果长期保持一个 access_token 有效, + * 也是不安全的。所以我们时常使用refresh token来进行token的刷新。 + *

+ * 我们一般会把 refresh_token 设置的过期时间稍微长一点,比如两倍于 access_token,当 access_token 过期后,refresh_token 如果还没有过期, + * 就可以利用两者的过期时间差进行重新生成令牌的操作,也就是刷新令牌,同时删除掉redis中缓存的旧令牌。 + * + * @param token + * @return + */ + @RequestMapping(value = "/token/refresh", method = RequestMethod.GET) + @ApiOperation(value = "刷新令牌") + @ApiOperationSupport(author = "liz") + public CommonResult refreshToken(@RequestHeader(value = "${auth.jwt.header}") String token) { + + return userManageService.refreshToken(token); + + } +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/PermissionController.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/PermissionController.java new file mode 100644 index 0000000..1569cd3 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/controller/PermissionController.java @@ -0,0 +1,52 @@ +package com.auth.server.controller; + +import com.auth.common.entity.PathPermission; +import com.auth.common.entity.RolesPermission; +import com.auth.common.enums.PermissionConstants; +import com.auth.server.service.PathService; +import com.auth.server.service.PermissionService; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import io.swagger.annotations.Api; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 角色权限 controller层 + */ +@RestController +@Api(tags ="权限-API") +@RequestMapping("/permission") +public class PermissionController { + @Autowired + private PermissionService permissionService; + + @Resource + private PathService pathService; + + @PostMapping("/permission/add") + public boolean permissionAdd(@RequestBody Map map) { + String roles = (String) map.get(PermissionConstants.ROLES); + List codeList = (List) map.get(PermissionConstants.CODE_LIST); + return permissionService.permissionAdd(roles, codeList); + } + + @GetMapping("/get") + public List pathGet(@RequestParam("roles") String roles) { + RolesPermission permission = permissionService.getOne(new QueryWrapper().eq(PermissionConstants.ROLE,roles)); + String codes = StringUtils.strip(permission.getPermissionCode(), "[]"); + List list = Arrays.asList(codes.split(",")); + List pathList = new ArrayList<>(); + for(String code:list){ + String api = pathService.getOne(new QueryWrapper().eq(PermissionConstants.PERMISSION_CODE,code.trim())).getPath(); + pathList.add(api); + } + return pathList; + } +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/interceptor/UserInterceptor.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/interceptor/UserInterceptor.java new file mode 100644 index 0000000..19a535d --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/interceptor/UserInterceptor.java @@ -0,0 +1,31 @@ +//package com.auth.server.interceptor; +//import com.auth.server.mapper.UserMangeMapper; +//import org.springframework.web.servlet.HandlerInterceptor; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import javax.servlet.http.HttpSession; +//public class UserInterceptor implements HandlerInterceptor { +// private UserMangeMapper userMangeMapper; +// public UserInterceptor(UserMangeMapper userMapper){ +// this.userMangeMapper=userMapper; +// } +// @Override +// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { +// HttpSession session = request.getSession(); +// String username = (String) session.getAttribute("username"); +// //数据库 +// String UUID=userMangeMapper.getUUID(username); +// //session +// String uuid = (String)session.getAttribute("uuid"); +// System.out.println("uuid = " + uuid); +// System.out.println("UUID = " + UUID); +// if(UUID.equals(uuid)){ +// return true; +// }else { +// System.out.println("拦截"+request.getRequestURI()); +// response.sendRedirect("/login"); +// response.setStatus(401); +// return false; +// } +// } +//} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PathMapper.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PathMapper.java new file mode 100644 index 0000000..e243793 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PathMapper.java @@ -0,0 +1,8 @@ +package com.auth.server.mapper; + +import com.auth.common.entity.PathPermission; +import com.auth.common.entity.RolesPermission; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +public interface PathMapper extends BaseMapper { +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PermissionMapper.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PermissionMapper.java new file mode 100644 index 0000000..42e3bed --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/PermissionMapper.java @@ -0,0 +1,8 @@ +package com.auth.server.mapper; + + +import com.auth.common.entity.RolesPermission; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +public interface PermissionMapper extends BaseMapper { +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/UserMangeMapper.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/UserMangeMapper.java new file mode 100644 index 0000000..9a770ef --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/mapper/UserMangeMapper.java @@ -0,0 +1,12 @@ +package com.auth.server.mapper; + + +import com.auth.common.entity.UserAccount; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserMangeMapper extends BaseMapper { + +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PathService.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PathService.java new file mode 100644 index 0000000..b555b70 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PathService.java @@ -0,0 +1,9 @@ +package com.auth.server.service; + +import com.auth.common.entity.PathPermission; +import com.auth.common.entity.RolesPermission; +import com.auth.common.entity.UserAccount; +import com.baomidou.mybatisplus.extension.service.IService; + +public interface PathService extends IService { +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PermissionService.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PermissionService.java new file mode 100644 index 0000000..d487e57 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/PermissionService.java @@ -0,0 +1,11 @@ +package com.auth.server.service; + +import com.auth.common.entity.RolesPermission; +import com.auth.common.entity.UserAccount; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.List; + +public interface PermissionService extends IService { + boolean permissionAdd(String roles, List codeList); +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/UserManageService.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/UserManageService.java new file mode 100644 index 0000000..949f8b8 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/UserManageService.java @@ -0,0 +1,15 @@ +package com.auth.server.service; + +import com.alibaba.nacos.api.model.v2.Result; +import com.auth.common.entity.UserAccount; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.etl.common.result.CommonResult; + +public interface UserManageService extends IService { + + + Result userLogin(UserAccount user); + + CommonResult refreshToken(String token); +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PathServiceImpl.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PathServiceImpl.java new file mode 100644 index 0000000..8e4475a --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PathServiceImpl.java @@ -0,0 +1,16 @@ +package com.auth.server.service.impl; + +import com.auth.common.entity.PathPermission; +import com.auth.common.entity.RolesPermission; +import com.auth.server.mapper.PathMapper; +import com.auth.server.mapper.PermissionMapper; +import com.auth.server.service.PathService; +import com.auth.server.service.PermissionService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +public class PathServiceImpl extends ServiceImpl implements PathService { +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PermissionServiceImpl.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PermissionServiceImpl.java new file mode 100644 index 0000000..dc99f92 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/PermissionServiceImpl.java @@ -0,0 +1,61 @@ +package com.auth.server.service.impl; + +import com.auth.common.entity.RolesPermission; +import com.auth.common.enums.PermissionConstants; +import com.auth.server.mapper.PermissionMapper; +import com.auth.server.service.PermissionService; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; + +@Service +@Slf4j +public class PermissionServiceImpl extends ServiceImpl implements PermissionService { + @Autowired + private PermissionMapper permissionMapper; + + @Override + public boolean permissionAdd(String roles, List codeList) { + RolesPermission rolesPermission = new RolesPermission(); + rolesPermission.setRole(roles); + int result = 0; + RolesPermission role = getRoleByName(roles); + + if (role != null) { + result = updateRolePermission(rolesPermission, role, codeList); + } else { + result = insertRolePermission(rolesPermission, codeList); + } + return result > 0; + } + + private RolesPermission getRoleByName(String roleName) { + return permissionMapper.selectOne(new QueryWrapper().eq(PermissionConstants.ROLE, roleName)); + } + + private int updateRolePermission(RolesPermission rolesPermission, RolesPermission role, List codeList) { + //去掉头尾括号,并转为列表 + List list = new java.util.ArrayList<>(Collections.singletonList( + StringUtils.strip(role.getPermissionCode(), "[]"))); + //将新数据添加至列表 + list.addAll(codeList); + + rolesPermission.setPermissionCode(list.toString()); + rolesPermission.setId(role.getId()); + return permissionMapper.updateById(rolesPermission); + } + + private int insertRolePermission(RolesPermission rolesPermission, List codeList) { + if (codeList != null) { + rolesPermission.setPermissionCode(codeList.toString()); + } + return permissionMapper.insert(rolesPermission); + } + +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/UserManageServiceImpl.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/UserManageServiceImpl.java new file mode 100644 index 0000000..a594d0a --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/service/impl/UserManageServiceImpl.java @@ -0,0 +1,168 @@ +package com.auth.server.service.impl; + + +import com.alibaba.fastjson2.JSON; +import com.alibaba.nacos.api.model.v2.Result; +import com.auth.common.entity.UserAccount; +import com.auth.common.enums.PermissionConstants; +import com.auth.server.config.MD5s; +import com.auth.server.mapper.UserMangeMapper; +import com.auth.server.service.UserManageService; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.etl.common.enums.ResponseCodeEnum; +import com.etl.common.result.CommonResult; +import com.etl.jwt.util.JwtTokenUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.mgt.DefaultSecurityManager; +import org.apache.shiro.realm.SimpleAccountRealm; +import org.apache.shiro.subject.Subject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static java.lang.System.nanoTime; + +@Service +@Slf4j +public class UserManageServiceImpl extends ServiceImpl implements UserManageService { + @Resource + private StringRedisTemplate stringRedisTemplate; + + @Resource + private JwtTokenUtil jwtTokenUtil; + + @Autowired + private UserMangeMapper UserMangeMapper; + + @Override + public Result userLogin(UserAccount user) { + long startTime = nanoTime(); + // 获取用户名 + String username = user.getUsername(); + // 获取密码 + String password = user.getPassword(); + // 参数校验 + Result result = checkUser(username, password); + if (result != null) { + return result; + } + // 创建SimpleAccountRealm并添加账户信息 + SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm(); + // 确保这里添加的用户名和密码与用户提供的匹配 + simpleAccountRealm.addAccount(username, password); + // 配置SecurityManager并设置Realm + DefaultSecurityManager securityManager = new DefaultSecurityManager(simpleAccountRealm); + securityManager.setRealm(simpleAccountRealm); + SecurityUtils.setSecurityManager(securityManager); + //shiro验证 + Subject subject = SecurityUtils.getSubject(); + //根据用户名密码生成一个令牌 + AuthenticationToken token = new UsernamePasswordToken(username, password); + try { + //执行登录操作 + subject.login(token); + //将用户信息存入redis + saveUserInfoToRedis(username, user); + } catch (UnknownAccountException e) { + log.info("登录用户不存在:{}", e); + return new Result<>(416, "用户不存在", username); + } catch (IncorrectCredentialsException e) { + log.info("登录密码错误:{}", e); + return new Result<>(412, "密码错误,请重新登录", password); + } catch (AuthenticationException e) { + log.warn("用户登录异常:" + e.getMessage()); + return new Result<>(416, "账户异常", username); + } + String userInfo = stringRedisTemplate.opsForValue().get(PermissionConstants.USER_NAME + username); + UserAccount account = null; + if (userInfo != null) { + account = JSON.parseObject(userInfo, UserAccount.class); + } else { + //获取登录用户信息 + account = UserMangeMapper.selectOne(new QueryWrapper().eq(PermissionConstants.USER_NAME, username)); + stringRedisTemplate.opsForValue().set(PermissionConstants.USER_NAME + username, JSON.toJSONString(account)); + } + // 通过 jwtTokenUtil 生成 JWT 令牌和刷新令牌 + Map tokenMap = jwtTokenUtil + .generateTokenAndRefreshToken(String.valueOf(account.getId()), username); + // 用户角色映射表中中查询用户角色 + account.getRoles(); + long endTime = nanoTime(); + // 计算耗时(单位为纳秒) + long elapsedTime = endTime - startTime; + // 将耗时转换为毫秒 + double elapsedTimeInMillis = elapsedTime / 1000000.0; + // 输出结果 + System.out.println("程序运行耗时:" + elapsedTimeInMillis + " 毫秒"); + return Result.success(tokenMap); + } + + + private void saveUserInfoToRedis(String username, UserAccount user) { + stringRedisTemplate.opsForValue().set(PermissionConstants.USER_CACHE_KEY + username, + JSON.toJSONString(user), 30 * 60, TimeUnit.MINUTES); + } + + private Result checkUser(String username, String password) { + // 检查用户名和密码的合法性 + if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { + return new Result<>(400, "用户名或密码不能为空"); + } + if (username.length() < 3 || username.length() > 20) { + return new Result<>(400, "用户名长度必须在6-20个字符之间"); + } + if (password.length() < 3 || password.length() > 20) { + return new Result<>(400, "密码长度必须在6-20个字符之间"); + } + return null; + } + + @Override + public CommonResult refreshToken(String token) { + token = com.auth.server.util.SecurityUtils.replaceTokenPrefix(token); + + if (StringUtils.isEmpty(token)) { + return new CommonResult<>(ResponseCodeEnum.TOKEN_MISSION.getCode(), + ResponseCodeEnum.TOKEN_MISSION.getMessage()); + } + + // 对Token解签名,并验证Token是否过期 + boolean isJwtNotValid = jwtTokenUtil.isTokenExpired(token); + if (isJwtNotValid) { + return new CommonResult<>(ResponseCodeEnum.TOKEN_INVALID.getCode(), + ResponseCodeEnum.TOKEN_INVALID.getMessage()); + } + + // 验证 token 里面的 userId 是否为空 + String userId = jwtTokenUtil.getUserIdFromToken(token); + String username = jwtTokenUtil.getUserNameFromToken(token); + if (StringUtils.isEmpty(userId)) { + return new CommonResult<>(ResponseCodeEnum.TOKEN_INVALID.getCode(), + ResponseCodeEnum.TOKEN_INVALID.getMessage()); + } + + // 这里为了保证 refreshToken 只能用一次,刷新后,会从 redis 中删除。 + // 如果用的不是 redis 中的 refreshToken 进行刷新令牌,则不能刷新。 + // 如果使用 redis 中已过期的 refreshToken 也不能刷新令牌。 + boolean isRefreshTokenNotExisted = jwtTokenUtil.isRefreshTokenNotExistCache(token); + if (isRefreshTokenNotExisted) { + return new CommonResult<>(ResponseCodeEnum.REFRESH_TOKEN_INVALID.getCode(), + ResponseCodeEnum.REFRESH_TOKEN_INVALID.getMessage()); + } + + //String us = jwtTokenUtil.getUserIdFromToken(token); + Map tokenMap = jwtTokenUtil.refreshTokenAndGenerateToken(userId, username); + + return new CommonResult<>(200, ResponseCodeEnum.SUCCESS.getMessage(), tokenMap); + } + +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/SecurityUtils.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/SecurityUtils.java new file mode 100644 index 0000000..d689d0d --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/SecurityUtils.java @@ -0,0 +1,37 @@ +package com.auth.server.util; + + +import com.etl.common.constants.TokenConstants; + +import javax.servlet.http.HttpServletRequest; + +import static org.apache.logging.log4j.util.Strings.isEmpty; + +/** + * 权限获取工具类 + * + */ +public class SecurityUtils +{ + + /** + * 根据request获取请求token + */ + public static String getToken(HttpServletRequest request) + { + // 从header获取token标识 + String token = request.getHeader(TokenConstants.AUTHENTICATION); + return replaceTokenPrefix(token); + } + + /** + * 裁剪token前缀 + */ + public static String replaceTokenPrefix(String token) { + // 如果前端设置了令牌前缀,则裁剪掉前缀 + if (!isEmpty(token) && token.startsWith(TokenConstants.PREFIX)) { + token = token.replaceFirst(TokenConstants.PREFIX, ""); + } + return token; + } +} diff --git a/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/UserRealm.java b/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/UserRealm.java new file mode 100644 index 0000000..b9218f5 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/java/com/auth/server/util/UserRealm.java @@ -0,0 +1,65 @@ +package com.auth.server.util; + + +import com.auth.common.entity.UserAccount; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.auth.server.service.UserManageService; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.util.ByteSource; +import org.springframework.beans.factory.annotation.Autowired; + +@Slf4j +public class UserRealm extends AuthorizingRealm { + @Autowired + private UserManageService userManageService; + + //授权 + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { + + /**配置权限 + *此处User实体需配置属性roles,用户权限 + *获取当前用户对象 + * */ + SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); + Subject subject= SecurityUtils.getSubject(); + UserAccount currentUser =(UserAccount) subject.getPrincipal(); + authorizationInfo.addStringPermission(currentUser.getRoles()); + log.info("用户权限为:"+currentUser.getRoles()); + return authorizationInfo; + } + + //认证 + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { + + UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; + //用户名/密码认证 + //从接口处获取得到的用户名 + String username = token.getUsername(); + + //调用mybatis_plus中的方法,查询数据库中用户名对应的数据 + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("username",username); + UserAccount user=userManageService.getOne(wrapper); + + //为空,即用户名不存在 + if(user==null){ + return null; + }else { + log.info(user.getUsername()); + } + + //principal:认证的实体信息,可以是username,也可以是数据库表对应的用户的实体对象 + // Object principal = user.getUsername(); + ByteSource salt = ByteSource.Util.bytes(username); + return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword() , salt,getName()); + } +} diff --git a/etl-auth/etl-auth-server/src/main/resources/bootstrap.yml b/etl-auth/etl-auth-server/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..4edeee2 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/resources/bootstrap.yml @@ -0,0 +1,51 @@ +server: + port: 9092 +spring: + application: + name: engine-auth + redis: + host: 115.159.33.152 + port: 6379 + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://115.159.33.152:3306/etl + username: root + password: lzm@123 + mvc: + pathmatch: + matching-strategy: ant_path_matcher + profiles: + active: dev + cloud: + nacos: + #注册服务 + discovery: + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 + # 配置 + config: + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} +logging: + level: + com.bwie: DEBUG +auth: + jwt: + enabled: true # 是否开启JWT登录认证功能 + secret: passjava # JWT 私钥,用于校验JWT令牌的合法性 + expiration: 1800000 # JWT 令牌的有效期,用于校验JWT令牌的合法性,半个小时 + header: Authorization # HTTP 请求的 Header 名称,该 Header作为参数传递 JWT 令牌 + userParamName: username # 用户登录认证用户名参数名称 + pwdParamName: password # 用户登录认证密码参数名称 + useDefaultController: true # 是否使用默认的JwtAuthController + skipValidUrl: + - /auth/login + - /auth/logout +mybatis-plus: + mapper-locations: classpath:/mapper/*mapper.xml + typeAliasesPackage: com.auth.common.entity diff --git a/etl-auth/etl-auth-server/src/main/resources/mapper/PathMapper.xml b/etl-auth/etl-auth-server/src/main/resources/mapper/PathMapper.xml new file mode 100644 index 0000000..5829ce3 --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/resources/mapper/PathMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/src/main/resources/mapper/PermissionMapper.xml b/etl-auth/etl-auth-server/src/main/resources/mapper/PermissionMapper.xml new file mode 100644 index 0000000..c97efca --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/resources/mapper/PermissionMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/src/main/resources/mapper/UserMangeMapper.xml b/etl-auth/etl-auth-server/src/main/resources/mapper/UserMangeMapper.xml new file mode 100644 index 0000000..f74141e --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/resources/mapper/UserMangeMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/src/main/resources/static/index.html b/etl-auth/etl-auth-server/src/main/resources/static/index.html new file mode 100644 index 0000000..f67da0a --- /dev/null +++ b/etl-auth/etl-auth-server/src/main/resources/static/index.html @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + diff --git a/etl-auth/etl-auth-server/src/test/java/com/auth/server/EtlAuthServerApplicationTests.java b/etl-auth/etl-auth-server/src/test/java/com/auth/server/EtlAuthServerApplicationTests.java new file mode 100644 index 0000000..9a5ad53 --- /dev/null +++ b/etl-auth/etl-auth-server/src/test/java/com/auth/server/EtlAuthServerApplicationTests.java @@ -0,0 +1,31 @@ +package com.auth.server; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@SpringBootTest +class EtlAuthServerApplicationTests { + + @Autowired + private BCryptPasswordEncoder bCryptPasswordEncoder; + @Test + public void enCoder() { + String password="123"; + String encode = bCryptPasswordEncoder.encode(password); + System.out.println("加密后的密码:"+encode); + } + + @Test + public void matchesPassword(){ + String encode="$2a$10$qyOS46MrKAm2wIyJl95.eO70ioBDvsgv8nnCCjhGJUxPIhPC56PTa"; + boolean matches = bCryptPasswordEncoder.matches("123", encode); + if (matches){ + System.out.println("密码正确"); + }else { + System.out.println("密码错误"); + } + } + +} diff --git a/etl-auth/etl-auth-server/target/classes/bootstrap.yml b/etl-auth/etl-auth-server/target/classes/bootstrap.yml new file mode 100644 index 0000000..4edeee2 --- /dev/null +++ b/etl-auth/etl-auth-server/target/classes/bootstrap.yml @@ -0,0 +1,51 @@ +server: + port: 9092 +spring: + application: + name: engine-auth + redis: + host: 115.159.33.152 + port: 6379 + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://115.159.33.152:3306/etl + username: root + password: lzm@123 + mvc: + pathmatch: + matching-strategy: ant_path_matcher + profiles: + active: dev + cloud: + nacos: + #注册服务 + discovery: + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 + # 配置 + config: + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} +logging: + level: + com.bwie: DEBUG +auth: + jwt: + enabled: true # 是否开启JWT登录认证功能 + secret: passjava # JWT 私钥,用于校验JWT令牌的合法性 + expiration: 1800000 # JWT 令牌的有效期,用于校验JWT令牌的合法性,半个小时 + header: Authorization # HTTP 请求的 Header 名称,该 Header作为参数传递 JWT 令牌 + userParamName: username # 用户登录认证用户名参数名称 + pwdParamName: password # 用户登录认证密码参数名称 + useDefaultController: true # 是否使用默认的JwtAuthController + skipValidUrl: + - /auth/login + - /auth/logout +mybatis-plus: + mapper-locations: classpath:/mapper/*mapper.xml + typeAliasesPackage: com.auth.common.entity diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/EtlAuthServerApplication.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/EtlAuthServerApplication.class new file mode 100644 index 0000000..839078c Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/EtlAuthServerApplication.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/config/MD5s.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/config/MD5s.class new file mode 100644 index 0000000..b11995f Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/config/MD5s.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/config/ShiroConfig.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/config/ShiroConfig.class new file mode 100644 index 0000000..ea6fe07 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/config/ShiroConfig.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/LoginControler.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/LoginControler.class new file mode 100644 index 0000000..6be0a47 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/LoginControler.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/PermissionController.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/PermissionController.class new file mode 100644 index 0000000..c2b59f8 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/controller/PermissionController.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PathMapper.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PathMapper.class new file mode 100644 index 0000000..1b0aab4 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PathMapper.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PermissionMapper.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PermissionMapper.class new file mode 100644 index 0000000..8ee9317 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/PermissionMapper.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/UserMangeMapper.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/UserMangeMapper.class new file mode 100644 index 0000000..a8b6b55 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/mapper/UserMangeMapper.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PathService.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PathService.class new file mode 100644 index 0000000..88233ec Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PathService.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PermissionService.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PermissionService.class new file mode 100644 index 0000000..b26615f Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/PermissionService.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/UserManageService.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/UserManageService.class new file mode 100644 index 0000000..41fc9a0 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/UserManageService.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PathServiceImpl.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PathServiceImpl.class new file mode 100644 index 0000000..e8c9568 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PathServiceImpl.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PermissionServiceImpl.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PermissionServiceImpl.class new file mode 100644 index 0000000..884ed9b Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/PermissionServiceImpl.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/UserManageServiceImpl.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/UserManageServiceImpl.class new file mode 100644 index 0000000..e29edb7 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/service/impl/UserManageServiceImpl.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/util/SecurityUtils.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/util/SecurityUtils.class new file mode 100644 index 0000000..8bb5d1a Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/util/SecurityUtils.class differ diff --git a/etl-auth/etl-auth-server/target/classes/com/auth/server/util/UserRealm.class b/etl-auth/etl-auth-server/target/classes/com/auth/server/util/UserRealm.class new file mode 100644 index 0000000..4d29926 Binary files /dev/null and b/etl-auth/etl-auth-server/target/classes/com/auth/server/util/UserRealm.class differ diff --git a/etl-auth/etl-auth-server/target/classes/mapper/PathMapper.xml b/etl-auth/etl-auth-server/target/classes/mapper/PathMapper.xml new file mode 100644 index 0000000..5829ce3 --- /dev/null +++ b/etl-auth/etl-auth-server/target/classes/mapper/PathMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/target/classes/mapper/PermissionMapper.xml b/etl-auth/etl-auth-server/target/classes/mapper/PermissionMapper.xml new file mode 100644 index 0000000..c97efca --- /dev/null +++ b/etl-auth/etl-auth-server/target/classes/mapper/PermissionMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/target/classes/mapper/UserMangeMapper.xml b/etl-auth/etl-auth-server/target/classes/mapper/UserMangeMapper.xml new file mode 100644 index 0000000..f74141e --- /dev/null +++ b/etl-auth/etl-auth-server/target/classes/mapper/UserMangeMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/etl-auth/etl-auth-server/target/classes/static/index.html b/etl-auth/etl-auth-server/target/classes/static/index.html new file mode 100644 index 0000000..f67da0a --- /dev/null +++ b/etl-auth/etl-auth-server/target/classes/static/index.html @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + diff --git a/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/PathPermission.class b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/PathPermission.class new file mode 100644 index 0000000..47b2a17 Binary files /dev/null and b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/PathPermission.class differ diff --git a/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/RolesPermission.class b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/RolesPermission.class new file mode 100644 index 0000000..e0a3e5b Binary files /dev/null and b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/RolesPermission.class differ diff --git a/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/UserAccount.class b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/UserAccount.class new file mode 100644 index 0000000..7e2c105 Binary files /dev/null and b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/entity/UserAccount.class differ diff --git a/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/enums/PermissionConstants.class b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/enums/PermissionConstants.class new file mode 100644 index 0000000..da08aaa Binary files /dev/null and b/etl-auth/etl-auth-server/target/production/etl-auth-common/com/auth/common/enums/PermissionConstants.class differ diff --git a/etl-auth/etl-auth-server/target/test-classes/com/auth/server/EtlAuthServerApplicationTests.class b/etl-auth/etl-auth-server/target/test-classes/com/auth/server/EtlAuthServerApplicationTests.class new file mode 100644 index 0000000..3f07e7a Binary files /dev/null and b/etl-auth/etl-auth-server/target/test-classes/com/auth/server/EtlAuthServerApplicationTests.class differ diff --git a/etl-auth/pom.xml b/etl-auth/pom.xml new file mode 100644 index 0000000..1a7a28a --- /dev/null +++ b/etl-auth/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + com.bwie + etl-cloud + 1.0-SNAPSHOT + + etl-auth + pom + + etl-auth-common + etl-auth-server + etl-auth-common + + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + 2021.0.5.0 + + diff --git a/etl-common/src/main/java/com/etl/common/constants/TokenConstants.java b/etl-common/src/main/java/com/etl/common/constants/TokenConstants.java index ad6bbce..57d7030 100644 --- a/etl-common/src/main/java/com/etl/common/constants/TokenConstants.java +++ b/etl-common/src/main/java/com/etl/common/constants/TokenConstants.java @@ -21,4 +21,12 @@ public class TokenConstants { * token标识 */ public static final String TOKEN = "token"; + /** + * 令牌自定义标识 + */ + public static final String AUTHENTICATION = "Authorization"; + /** + * 令牌前缀 + */ + public static final String PREFIX = "Bearer "; } diff --git a/etl-common/src/main/java/com/etl/common/enums/ResponseCodeEnum.java b/etl-common/src/main/java/com/etl/common/enums/ResponseCodeEnum.java new file mode 100644 index 0000000..cd65e20 --- /dev/null +++ b/etl-common/src/main/java/com/etl/common/enums/ResponseCodeEnum.java @@ -0,0 +1,29 @@ +package com.etl.common.enums; + +public enum ResponseCodeEnum { + + SUCCESS(200, "成功"), + FAIL(412, "失败"), + LOGIN_ERROR(202, "用户名或密码错误"), + + UNKNOWN_ERROR(500, "未知错误"), + PARAMETER_ILLEGAL(400, "参数不合法"), + + TOKEN_INVALID(412, "token 已过期或验证不正确!"), + TOKEN_SIGNATURE_INVALID(403, "无效的签名"), + TOKEN_MISSION(403, "token 缺失"), + REFRESH_TOKEN_INVALID(412, "refreshToken 无效"), + LOGOUT_ERROR(444, "用户登出失败"); + private final int code; + private final String message; + ResponseCodeEnum(int code, String message) { + this.code = code; + this.message = message; + } + public int getCode() { + return code; + } + public String getMessage() { + return message; + } +} diff --git a/etl-common/src/main/java/com/etl/common/result/CommonResult.java b/etl-common/src/main/java/com/etl/common/result/CommonResult.java new file mode 100644 index 0000000..b771fdb --- /dev/null +++ b/etl-common/src/main/java/com/etl/common/result/CommonResult.java @@ -0,0 +1,22 @@ +package com.etl.common.result; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CommonResult{ + private Integer code; + private String message; + private T data; + private int dataSize; + + public CommonResult(Integer code,String message){ + this(code,message,null,0); + } + public CommonResult(Integer code,String message,T data){ + this(code,message,data,0); + } +} diff --git a/etl-common/target/classes/com/etl/common/constants/TokenConstants.class b/etl-common/target/classes/com/etl/common/constants/TokenConstants.class index a4da1a3..b845155 100644 Binary files a/etl-common/target/classes/com/etl/common/constants/TokenConstants.class and b/etl-common/target/classes/com/etl/common/constants/TokenConstants.class differ diff --git a/etl-common/target/classes/com/etl/common/enums/ResponseCodeEnum.class b/etl-common/target/classes/com/etl/common/enums/ResponseCodeEnum.class new file mode 100644 index 0000000..073a398 Binary files /dev/null and b/etl-common/target/classes/com/etl/common/enums/ResponseCodeEnum.class differ diff --git a/etl-common/target/classes/com/etl/common/result/CommonResult.class b/etl-common/target/classes/com/etl/common/result/CommonResult.class new file mode 100644 index 0000000..0f25ecb Binary files /dev/null and b/etl-common/target/classes/com/etl/common/result/CommonResult.class differ diff --git a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DataSource.java b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DataSource.java index 483e507..718e908 100644 --- a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DataSource.java +++ b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DataSource.java @@ -4,6 +4,7 @@ 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 io.swagger.models.auth.In; import lombok.Data; import javax.validation.constraints.NotEmpty; @@ -19,9 +20,6 @@ public class DataSource{ @TableId(type = IdType.AUTO) private Long id; - @NotNull(message = "数据源id不能为空") - private Long dataSourceId; - @NotEmpty(message = "数据源描述不能为空") private String dataSourceDescribe; @@ -51,4 +49,5 @@ public class DataSource{ private Integer dataSourceType; @TableField(exist = false) private String dataSourceTypeName; + } diff --git a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DatabaseConfig.java b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DatabaseConfig.java index 27c41a3..f9b0aab 100644 --- a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DatabaseConfig.java +++ b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/DatabaseConfig.java @@ -31,6 +31,7 @@ public class DatabaseConfig { private String tableName; @ApiModelProperty(value = "数据库库名") private String warehouseName; - + @ApiModelProperty(value = "数据表输入输出状态 0:输入 1:输出") + private Integer data; } diff --git a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/Task.java b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/Task.java index c9993fc..2a7101e 100644 --- a/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/Task.java +++ b/etl-data-source/el-data-source-common/src/main/java/com/etl/data/source/common/pojo/Task.java @@ -1,8 +1,8 @@ package com.etl.data.source.common.pojo; +import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import javax.persistence.*; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @@ -12,10 +12,10 @@ import java.util.Date; */ @Data @NoArgsConstructor +@TableName("task_manager") @ApiModel(value = "Task", description = "任务实体类") public class Task { - @ApiModelProperty(value = "主键ID", example = "1") private Integer id; diff --git a/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DataSource.class b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DataSource.class index d790689..cb783eb 100644 Binary files a/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DataSource.class and b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DataSource.class differ diff --git a/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DatabaseConfig.class b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DatabaseConfig.class index 350a6fd..18e8ab2 100644 Binary files a/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DatabaseConfig.class and b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/DatabaseConfig.class differ diff --git a/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/Task.class b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/Task.class new file mode 100644 index 0000000..ab5f33e Binary files /dev/null and b/etl-data-source/el-data-source-common/target/classes/com/etl/data/source/common/pojo/Task.class differ diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DataSheetController.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DataSheetController.java index a55991f..12b10ce 100644 --- a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DataSheetController.java +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DataSheetController.java @@ -3,6 +3,7 @@ package com.etl.data.source.server.controller; import com.etl.data.source.server.service.DataSheetService; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** @@ -16,4 +17,6 @@ import org.springframework.web.bind.annotation.RestController; public class DataSheetController { @Autowired private DataSheetService dataSheetService; + + } diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DatabaseController.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DatabaseController.java index 9e0ab85..4672c1a 100644 --- a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DatabaseController.java +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/DatabaseController.java @@ -5,6 +5,7 @@ import com.etl.data.source.common.config.Limit; import com.etl.data.source.common.pojo.DatabaseConfig; import com.etl.data.source.common.pojo.DatabaseRedis; import com.etl.data.source.common.pojo.resq.ColumnInfo; +import com.etl.data.source.common.pojo.until.R; import com.etl.data.source.server.service.DatabaseService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -60,4 +61,16 @@ public class DatabaseController { return Result.success(databaseService.findDatabaseTableField(config)); } + @PostMapping("/findDatabaseTableFieldPrice") + @ApiOperation("数据表输入") + public Result> > findDatabaseTableFieldPrice(@Valid @RequestBody DatabaseConfig config){ + return Result.success(databaseService.findDatabaseTableFieldPrice(config)); + } + + @PostMapping("outDatabaseTableFieldPrice") + @ApiOperation("数据表输出") + public Result outDatabaseTableFieldPrice(@Valid @RequestBody DatabaseConfig config){ + return Result.success(databaseService.findDatabaseTableFieldPrice(config)); + } + } diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/RuleController.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/RuleController.java new file mode 100644 index 0000000..befeae9 --- /dev/null +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/RuleController.java @@ -0,0 +1,57 @@ +package com.etl.data.source.server.controller; + +import com.etl.data.source.common.pojo.Code; +import com.etl.data.source.common.pojo.Rule; +import com.etl.data.source.common.pojo.req.RuleReq; +import com.etl.data.source.common.pojo.until.R; +import com.etl.data.source.server.service.RuleService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @ClassName RuleController + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 9:33 + */ +@RestController +@Api(tags = "规则管理") +public class RuleController { + @Autowired + private RuleService ruleService; + + @GetMapping("findRule") + @ApiOperation(value = "查询规则") + public R findRule(@RequestBody RuleReq ruleReq) { + List ruleList=ruleService.findRule(ruleReq); + return R.ok(ruleList); + } + + @PostMapping("addRule") + @ApiOperation(value = "添加规则") + public R addRule(@RequestBody Rule rule) { + return ruleService.addRule(rule); + } + + @PutMapping("updateRule") + @ApiOperation(value = "修改规则") + public R updateRule(@RequestBody Rule rule) { + return ruleService.updateRule(rule); + } + + @DeleteMapping("deleteRule") + @ApiOperation(value = "删除规则") + public R deleteRule(@RequestParam("id") Long id) { + return ruleService.deleteRule(id); + } + + @PostMapping("/addCode") + @ApiOperation(value = "添加规则") + public R addCode(@RequestBody Code code) { + return ruleService.addCode(code); + } +} diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/TaskController.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/TaskController.java index 607b3d2..d7bef75 100644 --- a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/TaskController.java +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/controller/TaskController.java @@ -17,7 +17,7 @@ import java.util.List; * @Date 2024/6/25 20:59 */ @RestController -@Api("任务模块") +@Api(tags = "任务模块") public class TaskController { @Autowired private TaskService taskService; diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/CodeBaseMapper.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/CodeBaseMapper.java new file mode 100644 index 0000000..0f58282 --- /dev/null +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/CodeBaseMapper.java @@ -0,0 +1,13 @@ +package com.etl.data.source.server.mapper; + +import com.etl.data.source.common.pojo.Code; +import com.github.yulichang.base.MPJBaseMapper; + +/** + * @ClassName CodeBaseMapper + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 9:36 + */ +public interface CodeBaseMapper extends MPJBaseMapper { +} diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/RuleBaseMapper.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/RuleBaseMapper.java new file mode 100644 index 0000000..e82c49e --- /dev/null +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/mapper/RuleBaseMapper.java @@ -0,0 +1,13 @@ +package com.etl.data.source.server.mapper; + +import com.etl.data.source.common.pojo.Rule; +import com.github.yulichang.base.MPJBaseMapper; + +/** + * @ClassName RuleBaseMapper + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 9:35 + */ +public interface RuleBaseMapper extends MPJBaseMapper { +} diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/DatabaseService.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/DatabaseService.java index 27e2e86..a5e5f61 100644 --- a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/DatabaseService.java +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/DatabaseService.java @@ -29,4 +29,5 @@ public interface DatabaseService { Map testDatabaseRedis(DatabaseRedis databaseRedis); + List> findDatabaseTableFieldPrice(DatabaseConfig config); } diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/RuleService.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/RuleService.java new file mode 100644 index 0000000..4bcd6a5 --- /dev/null +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/RuleService.java @@ -0,0 +1,27 @@ +package com.etl.data.source.server.service; + +import com.etl.data.source.common.pojo.Code; +import com.etl.data.source.common.pojo.Rule; +import com.etl.data.source.common.pojo.req.RuleReq; +import com.etl.data.source.common.pojo.until.R; +import com.github.yulichang.base.MPJBaseService; + +import java.util.List; + +/** + * @ClassName RuleService + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 9:33 + */ +public interface RuleService extends MPJBaseService { + List findRule(RuleReq ruleReq); + + R addRule(Rule rule); + + R addCode(Code code); + + R updateRule(Rule rule); + + R deleteRule(Long id); +} diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/DatabaseServiceImpl.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/DatabaseServiceImpl.java index 3b22b6f..55df9a9 100644 --- a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/DatabaseServiceImpl.java +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/DatabaseServiceImpl.java @@ -9,6 +9,7 @@ import com.etl.data.source.server.config.RedisConfig; import com.etl.data.source.server.mapper.DataSourceBaseMapper; import com.etl.data.source.server.mapper.DataSourceTypeBaseMapper; import com.etl.data.source.server.service.DatabaseService; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -29,6 +30,7 @@ import java.util.*; * @Date 2024/6/21 20:16 */ @Service +@Slf4j public class DatabaseServiceImpl implements DatabaseService { @Autowired private DataSourceBaseMapper dataSourceBaseMapper; @@ -159,54 +161,140 @@ public class DatabaseServiceImpl implements DatabaseService { return columnInfos; } + @Override + public List> findDatabaseTableFieldPrice(DatabaseConfig config) { + List> results = new ArrayList<>(); + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + try { + connection = getConnection(config); + // 这里我们仅作为示例直接构建SQL查询语句,实际中可能需要更复杂的逻辑来构建SQL + String sql = "SELECT * FROM " + config.getWarehouseName() + "." + config.getTableName(); + preparedStatement = connection.prepareStatement(sql); + resultSet = preparedStatement.executeQuery(); + + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + + while (resultSet.next()) { + Map rowData = new HashMap<>(); + for (int i = 1; i <= columnCount; i++) { + String columnName = metaData.getColumnName(i); + Object columnValue = resultSet.getObject(i); + rowData.put(columnName, columnValue); + } + results.add(rowData); + } + } catch (SQLException e) { + // 处理异常 + e.printStackTrace(); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } finally { + // 关闭资源 + try { + if (resultSet != null) resultSet.close(); + if (preparedStatement != null) preparedStatement.close(); + if (connection != null) connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if(1 == config.getData()){ + insertDataExcludingId(config, results); + } + return results; + } + + public void insertDataExcludingId(DatabaseConfig config, List> results) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = getConnection(config); + + for (Map rowData : results) { + // 获取列名并构建 SQL 语句 + List columnNames = new ArrayList<>(rowData.keySet()); + columnNames.remove("id"); // 移除 id 列 + StringBuilder sql = new StringBuilder("INSERT INTO "); + sql.append(config.getWarehouseName()).append(".").append(config.getTableName()).append(" ("); + for (int i = 0; i < columnNames.size(); i++) { + if (i > 0) { + sql.append(", "); + } + sql.append(columnNames.get(i)); + } + sql.append(") VALUES ("); + + // 添加占位符 + for (int i = 0; i < columnNames.size(); i++) { + if (i > 0) { + sql.append(", "); + } + sql.append("?"); + } + sql.append(")"); + + preparedStatement = connection.prepareStatement(sql.toString()); + + // 填充数据并执行 INSERT + int index = 1; + for (String columnName : columnNames) { + preparedStatement.setObject(index++, rowData.get(columnName)); + } + + preparedStatement.executeUpdate(); + } + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } finally { + // 关闭资源 + try { + if (preparedStatement != null) preparedStatement.close(); + if (connection != null) connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } @Override public Map testDatabaseRedis(DatabaseRedis databaseRedis) { // 创建一个空的HashMap来存储Redis中的所有键值对 Map allData = new HashMap<>(); - // 从Redis配置中获取Jedis连接池 JedisPool jedisPool = RedisConfig.getJedisPool(databaseRedis); - // 从连接池中获取一个Jedis资源 Jedis resource = jedisPool.getResource(); - // 创建一个ScanParams对象,设置每次迭代返回的键的数量(这里设置为100) ScanParams scanParams = new ScanParams().count(100); - // 初始化游标为0,表示开始迭代 String cursor = "0"; - // 使用do-while循环来迭代Redis中的所有键 do { // 使用scan方法和ScanParams对象来获取一批键和新的游标 ScanResult scanResult = resource.scan(cursor, scanParams); - // 更新游标以便下一次迭代 cursor = scanResult.getCursor(); - // 获取当前迭代返回的键列表 List keys = scanResult.getResult(); - // 遍历键列表,并获取每个键对应的值 for (String key : keys) { // 假设所有键对应的值都是字符串类型 String value = resource.get(key); - // 如果值不为null,则将其添加到Map中 if (value != null) { // 将键值对添加到Map中 allData.put(key, value); } } - - // 当游标为"0"时,表示迭代完成 + // 当游标为"0"时,表示迭代完成 } while (!cursor.equals("0")); - // 返回包含所有键值对的Map return allData; } - private static Connection getConnection(DatabaseConfig config) throws ClassNotFoundException, SQLException { // 加载MySQL驱动 Class.forName(config.getDriverClassName()); diff --git a/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/RuleServiceImpl.java b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/RuleServiceImpl.java new file mode 100644 index 0000000..bebfbcd --- /dev/null +++ b/etl-data-source/el-data-source-server/src/main/java/com/etl/data/source/server/service/impl/RuleServiceImpl.java @@ -0,0 +1,95 @@ +package com.etl.data.source.server.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.etl.data.source.common.pojo.Code; +import com.etl.data.source.common.pojo.CodeType; +import com.etl.data.source.common.pojo.Rule; +import com.etl.data.source.common.pojo.RuleType; +import com.etl.data.source.common.pojo.req.RuleReq; +import com.etl.data.source.common.pojo.until.R; +import com.etl.data.source.server.mapper.CodeBaseMapper; +import com.etl.data.source.server.mapper.RuleBaseMapper; +import com.etl.data.source.server.service.RuleService; +import com.github.yulichang.base.MPJBaseServiceImpl; +import com.github.yulichang.wrapper.MPJLambdaWrapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @ClassName RuleServiceImpl + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 9:34 + */ +@Service +public class RuleServiceImpl extends MPJBaseServiceImpl implements RuleService { + @Autowired + private RuleBaseMapper ruleBaseMapper; + + @Autowired + private CodeBaseMapper codeBaseMapper; + + @Override + public List findRule(RuleReq ruleReq) { + MPJLambdaWrapper ruleMPJLambdaWrapper = new MPJLambdaWrapper<>(); + ruleMPJLambdaWrapper.select(Rule::getId, Rule::getRuleTypeId, Rule::getRuleName) + .select(RuleType::getRuleTypeName) + .select(CodeType::getCodeTypeName) + .leftJoin(RuleType.class, RuleType::getId, Rule::getRuleTypeId) + .leftJoin(Code.class, Code::getRuleId, Rule::getId) + .leftJoin(CodeType.class, CodeType::getId, Code::getCodeTypeId); + if (ruleReq.getRuleTypeId() != null) { + ruleMPJLambdaWrapper.eq(Rule::getRuleTypeId, ruleReq.getRuleTypeId()); + } + if (ruleReq.getCodeTypeId() != null) { + ruleMPJLambdaWrapper.eq(Code::getCodeTypeId, ruleReq.getCodeTypeId()); + } + Page page = new Page<>(ruleReq.getPageNum(), ruleReq.getPageSize()); + IPage ruleIPage = ruleBaseMapper.selectJoinPage(page, Rule.class, ruleMPJLambdaWrapper); + List records = ruleIPage.getRecords(); + return records; + } + + @Override + public R addRule(Rule rule) { + if (rule != null){ + if (ruleBaseMapper.insert(rule) > 0){ + return R.ok("添加成功"); + } + } + return R.fail("添加失败"); + } + + @Override + public R updateRule(Rule rule) { + if (rule != null){ + if (ruleBaseMapper.updateById(rule) > 0){ + return R.ok("修改成功"); + } + } + return R.fail("修改失败"); + } + + @Override + public R deleteRule(Long id) { + if (id != null){ + if (ruleBaseMapper.deleteById(id) > 0){ + return R.ok("删除成功"); + } + } + return R.fail("删除失败"); + } + + @Override + public R addCode(Code code) { + if (code != null){ + if (codeBaseMapper.insert(code) > 0){ + return R.ok("添加成功"); + } + } + return R.fail("添加失败"); + } +} diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSheetController.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSheetController.class new file mode 100644 index 0000000..96b8008 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSheetController.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSourceController.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSourceController.class index c3216b2..477510d 100644 Binary files a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSourceController.class and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DataSourceController.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DatabaseController.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DatabaseController.class index 64b147b..1c78638 100644 Binary files a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DatabaseController.class and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/DatabaseController.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/RuleController.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/RuleController.class new file mode 100644 index 0000000..048129a Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/RuleController.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/TaskController.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/TaskController.class new file mode 100644 index 0000000..e424cd3 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/controller/TaskController.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/CodeBaseMapper.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/CodeBaseMapper.class new file mode 100644 index 0000000..76b4472 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/CodeBaseMapper.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/DataSheetMapper.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/DataSheetMapper.class new file mode 100644 index 0000000..d867a38 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/DataSheetMapper.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/RuleBaseMapper.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/RuleBaseMapper.class new file mode 100644 index 0000000..21b6129 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/RuleBaseMapper.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/TaskMapper.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/TaskMapper.class new file mode 100644 index 0000000..0015194 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/mapper/TaskMapper.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DataSheetService.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DataSheetService.class new file mode 100644 index 0000000..9af3a7e Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DataSheetService.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DatabaseService.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DatabaseService.class index a2443ff..e9b9bbe 100644 Binary files a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DatabaseService.class and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/DatabaseService.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/RuleService.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/RuleService.class new file mode 100644 index 0000000..90e8b8c Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/RuleService.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/TaskService.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/TaskService.class new file mode 100644 index 0000000..67572e5 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/TaskService.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DataSheetServiceImpl.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DataSheetServiceImpl.class new file mode 100644 index 0000000..3e4b096 Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DataSheetServiceImpl.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DatabaseServiceImpl.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DatabaseServiceImpl.class index 866cefb..39c51fc 100644 Binary files a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DatabaseServiceImpl.class and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/DatabaseServiceImpl.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/RuleServiceImpl.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/RuleServiceImpl.class new file mode 100644 index 0000000..1aeda1e Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/RuleServiceImpl.class differ diff --git a/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/TaskServiceImpl.class b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/TaskServiceImpl.class new file mode 100644 index 0000000..ecf968a Binary files /dev/null and b/etl-data-source/el-data-source-server/target/classes/com/etl/data/source/server/service/impl/TaskServiceImpl.class differ diff --git a/etl-gateway/pom.xml b/etl-gateway/pom.xml index 5c9f651..3d93677 100644 --- a/etl-gateway/pom.xml +++ b/etl-gateway/pom.xml @@ -8,7 +8,6 @@ 1.0-SNAPSHOT etl-gateway - etl-gateway 1.8 UTF-8 @@ -18,6 +17,56 @@ 2021.0.5 + + com.alibaba + fastjson + 2.0.15 + + + com.bwie + etl-jwt-manage + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-webflux + + + + com.bwie + etl-jwt-manage + 1.0-SNAPSHOT + compile + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba + druid-spring-boot-starter + + + servlet-api + javax.servlet + + + + + org.springframework.cloud + spring-cloud-starter-gateway + 3.1.3 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + com.bwie etl-common @@ -57,11 +106,6 @@ com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery - - org.springframework.cloud - spring-cloud-starter-gateway - 3.1.3 - diff --git a/etl-gateway/src/main/java/com/etl/gateway/EtlGatewayApplication.java b/etl-gateway/src/main/java/com/etl/gateway/EtlGatewayApplication.java index 62b9dd9..a02f238 100644 --- a/etl-gateway/src/main/java/com/etl/gateway/EtlGatewayApplication.java +++ b/etl-gateway/src/main/java/com/etl/gateway/EtlGatewayApplication.java @@ -2,8 +2,10 @@ package com.etl.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication +@ComponentScan(basePackages = {"com.etl.jwt.util", "com.etl.jwt.config"}) public class EtlGatewayApplication { public static void main(String[] args) { diff --git a/etl-gateway/src/main/java/com/etl/gateway/config/WhiteListProperties.java b/etl-gateway/src/main/java/com/etl/gateway/config/WhiteListProperties.java new file mode 100644 index 0000000..7e607e4 --- /dev/null +++ b/etl-gateway/src/main/java/com/etl/gateway/config/WhiteListProperties.java @@ -0,0 +1,14 @@ +package com.etl.gateway.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Data +@Component +@ConfigurationProperties(prefix = "auth.ignore") +public class WhiteListProperties { + private List whites; +} diff --git a/etl-gateway/src/main/java/com/etl/gateway/filters/AuthFilter.java b/etl-gateway/src/main/java/com/etl/gateway/filters/AuthFilter.java index 52441d0..19df148 100644 --- a/etl-gateway/src/main/java/com/etl/gateway/filters/AuthFilter.java +++ b/etl-gateway/src/main/java/com/etl/gateway/filters/AuthFilter.java @@ -1,95 +1,95 @@ package com.etl.gateway.filters;//package com.health.cloud.gateway.filters; -// -// -//import com.health.cloud.common.constants.TokenConstants; -//import com.health.cloud.common.util.JwtUtils; -//import com.health.cloud.common.util.StringUtils; -//import com.health.cloud.gateway.config.IgnoreWhiteConfig; -//import com.health.cloud.gateway.utils.GatewayUtils; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.cloud.gateway.filter.GatewayFilterChain; -//import org.springframework.cloud.gateway.filter.GlobalFilter; -//import org.springframework.core.Ordered; -//import org.springframework.data.redis.core.RedisTemplate; -//import org.springframework.http.server.reactive.ServerHttpRequest; -//import org.springframework.stereotype.Component; -//import org.springframework.web.server.ServerWebExchange; -//import reactor.core.publisher.Mono; -// -//import java.util.List; -//import java.util.concurrent.TimeUnit; -// -///** -// * @ClassName: -// * @Description: 过滤请求,验证 token -// * @Author: dongyan Ma -// * @Date: 2024/2/28 -// */ -//@Component -//public class AuthFilter implements GlobalFilter, Ordered { -// -// @Autowired -// private IgnoreWhiteConfig ignoreWhitesConfig; -// -// @Autowired -// private RedisTemplate redisTemplate; -// -// /** -// * 过滤请求方法 -// * @param exchange 请求的上下文, 通过这个对象可以获取请求对象以及响应对象 -// * @param chain 过滤器链 使用他进行 过滤 或者 放行 -// * @return -// */ -// @Override -// public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { -// // 判断这次请求是否需要验证 token 白名单【直接放行的请求】 -// // 获取系统白名单 -// List whites = ignoreWhitesConfig.getWhites(); -// // 获取当前请求的 URI -// ServerHttpRequest request = exchange.getRequest(); -// String path = request.getURI().getPath(); -// boolean matches = StringUtils.matches(path, whites); -// if (matches) { -// // 白名单请求 + + +import com.etl.common.constants.TokenConstants; +import com.etl.common.util.JwtUtils; +import com.etl.common.util.StringUtils; +import com.etl.gateway.config.IgnoreWhiteConfig; +import com.etl.gateway.utils.GatewayUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * @ClassName: + * @Description: 过滤请求,验证 token + * @Author: dongyan Ma + * @Date: 2024/2/28 + */ +@Component +public class AuthFilter implements GlobalFilter, Ordered { + + @Autowired + private IgnoreWhiteConfig ignoreWhitesConfig; + + @Autowired + private RedisTemplate redisTemplate; + + /** + * 过滤请求方法 + * @param exchange 请求的上下文, 通过这个对象可以获取请求对象以及响应对象 + * @param chain 过滤器链 使用他进行 过滤 或者 放行 + * @return + */ + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + // 判断这次请求是否需要验证 token 白名单【直接放行的请求】 + // 获取系统白名单 + List whites = ignoreWhitesConfig.getWhites(); + // 获取当前请求的 URI + ServerHttpRequest request = exchange.getRequest(); + String path = request.getURI().getPath(); + boolean matches = StringUtils.matches(path, whites); + if (matches) { + // 白名单请求 + return chain.filter(exchange); + } +// boolean anyMatch = whites.stream().anyMatch(white -> white.equals(path)); +// if (anyMatch) { + // 白名单请求 // return chain.filter(exchange); // } -//// boolean anyMatch = whites.stream().anyMatch(white -> white.equals(path)); -//// if (anyMatch) { -// // 白名单请求 -//// return chain.filter(exchange); -//// } -// // 验证 token -// String token = request.getHeaders().getFirst(TokenConstants.TOKEN); -// // 非空验证 -// if (StringUtils.isBlank(token)) { -// // 空的 -// return GatewayUtils.errorResponse(exchange, "token不能为空!"); -// } -// // 是否合法 -// try { -// JwtUtils.parseToken(token); -// } catch (Exception e) { -// return GatewayUtils.errorResponse(exchange, "token不合法!"); -// } -// // 是否有效 -// String userKey = JwtUtils.getUserKey(token); -// if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) { -// return GatewayUtils.errorResponse(exchange, "token过期!"); -// } else { -// // 重新设置 redis中的用户有效时间 -// redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey, 30, TimeUnit.MINUTES); -// } -// // 放行 -// return chain.filter(exchange); -// } -// -// /** -// * 规定过滤器执行的顺序 -// * @return 方法的返回值越小 执行顺序越高 -// */ -// @Override -// public int getOrder() { -// return 0; -// } -// -//} + // 验证 token + String token = request.getHeaders().getFirst(TokenConstants.TOKEN); + // 非空验证 + if (StringUtils.isBlank(token)) { + // 空的 + return GatewayUtils.errorResponse(exchange, "token不能为空!"); + } + // 是否合法 + try { + JwtUtils.parseToken(token); + } catch (Exception e) { + return GatewayUtils.errorResponse(exchange, "token不合法!"); + } + // 是否有效 + String userKey = JwtUtils.getUserKey(token); + if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) { + return GatewayUtils.errorResponse(exchange, "token过期!"); + } else { + // 重新设置 redis中的用户有效时间 + redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey, 30, TimeUnit.MINUTES); + } + // 放行 + return chain.filter(exchange); + } + + /** + * 规定过滤器执行的顺序 + * @return 方法的返回值越小 执行顺序越高 + */ + @Override + public int getOrder() { + return 0; + } + +} diff --git a/etl-gateway/src/main/java/com/etl/gateway/filters/JwtAuthCheckFilter.java b/etl-gateway/src/main/java/com/etl/gateway/filters/JwtAuthCheckFilter.java new file mode 100644 index 0000000..8304c6b --- /dev/null +++ b/etl-gateway/src/main/java/com/etl/gateway/filters/JwtAuthCheckFilter.java @@ -0,0 +1,134 @@ +package com.etl.gateway.filters; + +import com.alibaba.fastjson.JSON; +import com.etl.common.constants.TokenConstants; +import com.etl.common.result.CommonResult; +import com.etl.common.enums.ResponseCodeEnum; +import com.etl.jwt.config.AuthJwtProperties; +import com.etl.jwt.util.JwtTokenUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import javax.annotation.Resource; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +@Slf4j +@Configuration +public class JwtAuthCheckFilter { + private static final String AUTH_TOKEN_URL = "/auth/login"; + private static final String REFRESH_TOKEN_URL = "/auth/token/refresh"; + public static final String USER_ID = "userId"; + public static final String USER_NAME = "username"; + public static final String FROM_SOURCE = "from-source"; + + @Resource + private AuthJwtProperties authJwtProperties; + @Resource + private JwtTokenUtil jwtTokenUtil; + + + @Bean + @Order(-101) + public GlobalFilter jwtAuthGlobalFilter() { + + return (exchange, chain) -> { + + ServerHttpRequest serverHttpRequest = exchange.getRequest(); + ServerHttpResponse serverHttpResponse = exchange.getResponse(); + ServerHttpRequest.Builder mutate = serverHttpRequest.mutate(); + String requestUrl = serverHttpRequest.getURI().getPath(); + + // 跳过对登录请求的 token 检查。因为登录请求是没有 token 的,是来申请 token 的。 + if(AUTH_TOKEN_URL.equals(requestUrl)) { + log.info("登录url,放行"); + return chain.filter(exchange); + } + + // 从 HTTP 请求头中获取 JWT 令牌 + String token = getToken(serverHttpRequest); + if (StringUtils.isEmpty(token)) { + return unauthorizedResponse(exchange, serverHttpResponse, ResponseCodeEnum.TOKEN_MISSION); + } + + // 对Token解签名,并验证Token是否过期 + boolean isJwtNotValid = jwtTokenUtil.isTokenExpired(token); + if(isJwtNotValid){ + return unauthorizedResponse(exchange, serverHttpResponse, ResponseCodeEnum.TOKEN_INVALID); + } + // 验证 token 里面的 userId 是否为空 + String userId = jwtTokenUtil.getUserIdFromToken(token); + String username = jwtTokenUtil.getUserNameFromToken(token); + if (StringUtils.isEmpty(userId)) { + return unauthorizedResponse(exchange, serverHttpResponse, ResponseCodeEnum.TOKEN_INVALID); + } + + // 设置用户信息到请求 + addHeader(mutate, USER_ID, userId); + addHeader(mutate, USER_NAME, username); + // 内部请求来源参数清除 + removeHeader(mutate, FROM_SOURCE); + return chain.filter(exchange.mutate().request(mutate.build()).build()); + }; + } + + //添加头部信息 + private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) { + if (value == null) { + return; + } + String valueStr = value.toString(); + String valueEncode = urlEncode(valueStr); + mutate.header(name, valueEncode); + } + //移除头部信息 + private void removeHeader(ServerHttpRequest.Builder mutate, String name) { + mutate.headers(httpHeaders -> httpHeaders.remove(name)).build(); + } + + //内容编码,配置为UTF-8 + static String urlEncode(String str) { + try { + return URLEncoder.encode(str, "UTF-8"); + } + catch (UnsupportedEncodingException e) + { + return StringUtils.EMPTY; + } + } + + //请求token + private String getToken(ServerHttpRequest request) { + String token = request.getHeaders().getFirst(authJwtProperties.getHeader()); + // 如果前端设置了令牌前缀,则裁剪掉前缀 + if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) + { + token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY); + } + return token; + } + + //jwt鉴权失败处理类 + private Mono unauthorizedResponse(ServerWebExchange exchange, ServerHttpResponse serverHttpResponse, ResponseCodeEnum responseCodeEnum) { + log.warn("token异常处理,请求路径:{}", exchange.getRequest().getPath()); + serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); + serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); + CommonResult responseResult = new CommonResult<>(responseCodeEnum.getCode(),responseCodeEnum.getMessage()); + DataBuffer dataBuffer = serverHttpResponse.bufferFactory() + .wrap(JSON.toJSONStringWithDateFormat(responseResult, JSON.DEFFAULT_DATE_FORMAT) + .getBytes(StandardCharsets.UTF_8)); + return serverHttpResponse.writeWith(Flux.just(dataBuffer)); + } + +} diff --git a/etl-gateway/src/main/java/com/etl/gateway/filters/LogFilter.java b/etl-gateway/src/main/java/com/etl/gateway/filters/LogFilter.java index 6fd69cd..97e2c91 100644 --- a/etl-gateway/src/main/java/com/etl/gateway/filters/LogFilter.java +++ b/etl-gateway/src/main/java/com/etl/gateway/filters/LogFilter.java @@ -3,6 +3,7 @@ package com.etl.gateway.filters; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; +import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @@ -12,14 +13,15 @@ import reactor.core.publisher.Mono; * @Author: dongyan Ma * @Date: 2024/2/28 */ +@Component public class LogFilter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - return null; + return chain.filter(exchange); } @Override public int getOrder() { - return 1; + return 0; } } diff --git a/etl-gateway/src/main/resources/bootstrap.yml b/etl-gateway/src/main/resources/bootstrap.yml index 6aa11fb..d13bfdd 100644 --- a/etl-gateway/src/main/resources/bootstrap.yml +++ b/etl-gateway/src/main/resources/bootstrap.yml @@ -1,31 +1,33 @@ -# Tomcat server: port: 18080 -# Spring spring: application: - # 应用名称 - name: etl-gateway + name: engine-gateway profiles: - # 环境配置 active: dev - main: - # 允许使用循环引用 - allow-circular-references: true - # 允许定义相同的bean对象 去覆盖原有的 - allow-bean-definition-overriding: true cloud: nacos: + #注册服务 discovery: - # 服务注册地址 - server-addr: 182.254.221.163:8848 - namespace: 10a15e4b-3457-44dc-9378-cc25849f1872 + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 + # 配置 config: - # 配置中心地址 - server-addr: 182.254.221.163:8848 - namespace: 10a15e4b-3457-44dc-9378-cc25849f1872 + server-addr: 115.159.33.152:8848 + namespace: f9f293d4-55ce-45c1-aa15-124ca461c060 # 配置文件格式 file-extension: yml - # 共享配置 - shared-configs: - - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} +logging: + level: + com.bwie: DEBUG + +auth: + jwt: + enabled: true # 是否开启JWT登录认证功能 + secret: passjava # JWT 私钥,用于校验JWT令牌的合法性 + expiration: 3600000 # JWT 令牌的有效期,用于校验JWT令牌的合法性,一个小时 + header: Authorization # HTTP 请求的 Header 名称,该 Header作为参数传递 JWT 令牌 + userParamName: userId # 用户登录认证用户名参数名称 + pwdParamName: password # 用户登录认证密码参数名称 + useDefaultController: true # 是否使用默认的JwtAuthController + skipValidUrl: /auth/login diff --git a/etl-groovy/pom.xml b/etl-groovy/pom.xml new file mode 100644 index 0000000..df86b7c --- /dev/null +++ b/etl-groovy/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + com.bwie + etl-cloud + 1.0-SNAPSHOT + + etl-groovy + etl-groovy + + 1.8 + UTF-8 + UTF-8 + + + + com.bwie + etl-common + 1.0-SNAPSHOT + + + com.baomidou + mybatis-plus-boot-starter + + + + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + + mysql + mysql-connector-java + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + org.codehaus.groovy + groovy-all + 2.4.7 + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + diff --git a/etl-groovy/src/main/java/com/etl/groovy/SpringBootGroovyApplication.java b/etl-groovy/src/main/java/com/etl/groovy/SpringBootGroovyApplication.java new file mode 100644 index 0000000..b1ce458 --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/SpringBootGroovyApplication.java @@ -0,0 +1,20 @@ +package com.etl.groovy; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import groovy.lang.GroovyShell; +import groovy.lang.Script; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + + +@SpringBootApplication +public class SpringBootGroovyApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootGroovyApplication.class, args); + } + + +} diff --git a/etl-groovy/src/main/java/com/etl/groovy/controller/GrooyTestController.java b/etl-groovy/src/main/java/com/etl/groovy/controller/GrooyTestController.java new file mode 100644 index 0000000..3b9b3ca --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/controller/GrooyTestController.java @@ -0,0 +1,43 @@ +package com.etl.groovy.controller; + +import groovy.lang.GroovyShell; +import groovy.lang.Script; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @ClassName GrooyTestController + * @Description 描述 + * @Author ZeZhang.Liu + * @Date 2024/6/26 16:58 + */ +@RestController +@RequestMapping("/groovy") +public class GrooyTestController { + @RequestMapping("/test") + public String test() { + //创建GroovyShell + GroovyShell groovyShell = new GroovyShell(); + //装载解析脚本代码 + Script script = groovyShell.parse("package groovy\n" + + "\n" + + "import com.etl.groovy.service.GroovyTestService\n" + + "import com.etl.groovy.util.SpringContextUtil\n" + + "\n" + + "/**\n" + + " * 静态变量\n" + + " */\n" + + "class Globals {\n" + + " static String PARAM1 = \"静态变量\"\n" + + " static int[] arrayList = [1, 2]\n" + + "}\n" + + "\n" + + "def getBean() {\n" + + " GroovyTestService groovyTestService = SpringContextUtil.getBean(GroovyTestService.class);\n" + + " groovyTestService.removeDashesFromAddress()\n" + + "}"); + //执行 + script.invokeMethod("getBean", null); + return "ok"; + } +} diff --git a/etl-groovy/src/main/java/com/etl/groovy/entity/Address.java b/etl-groovy/src/main/java/com/etl/groovy/entity/Address.java new file mode 100644 index 0000000..d8f2757 --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/entity/Address.java @@ -0,0 +1,15 @@ +package com.etl.groovy.entity; + +import lombok.Data; + +/** + * @ClassName Address + * @Description 描述 + * @Author TingTing.Yao + * @Date 2024/06/26 14:08 + */ +@Data +public class Address { + private Integer id; + private String address; +} diff --git a/etl-groovy/src/main/java/com/etl/groovy/mapper/AddressMapper.java b/etl-groovy/src/main/java/com/etl/groovy/mapper/AddressMapper.java new file mode 100644 index 0000000..f5d8519 --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/mapper/AddressMapper.java @@ -0,0 +1,12 @@ +package com.etl.groovy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.etl.groovy.entity.Address; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Update; + +@Mapper +public interface AddressMapper extends BaseMapper
{ + @Update("UPDATE address SET address = REPLACE(address, '-', '') WHERE address LIKE '%-%'") + void removeDashesFromAddress(); +} diff --git a/etl-groovy/src/main/java/com/etl/groovy/service/GroovyTestService.java b/etl-groovy/src/main/java/com/etl/groovy/service/GroovyTestService.java new file mode 100644 index 0000000..d33c5ec --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/service/GroovyTestService.java @@ -0,0 +1,18 @@ +package com.etl.groovy.service; + +import com.etl.groovy.mapper.AddressMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class GroovyTestService { + + @Autowired + private AddressMapper addressMapper; + + public void removeDashesFromAddress() { + addressMapper.removeDashesFromAddress(); + } + +} + diff --git a/etl-groovy/src/main/java/com/etl/groovy/util/SpringContextUtil.java b/etl-groovy/src/main/java/com/etl/groovy/util/SpringContextUtil.java new file mode 100644 index 0000000..78cc933 --- /dev/null +++ b/etl-groovy/src/main/java/com/etl/groovy/util/SpringContextUtil.java @@ -0,0 +1,57 @@ +package com.etl.groovy.util; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * Spring上下文获取 + */ +@Component +public class SpringContextUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + SpringContextUtil.applicationContext = applicationContext; + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + /** + * 通过name获取 Bean. + * + * @param name + * @return + */ + public static Object getBean(String name) { + return getApplicationContext().getBean(name); + } + + /** + * 通过class获取Bean. + * + * @param clazz + * @param + * @return + */ + public static T getBean(Class clazz) { + return getApplicationContext().getBean(clazz); + } + + /** + * 通过name,以及Clazz返回指定的Bean + * + * @param name + * @param clazz + * @param + * @return + */ + public static T getBean(String name, Class clazz) { + return getApplicationContext().getBean(name, clazz); + } +} diff --git a/etl-groovy/src/main/resources/bootstrap.yml b/etl-groovy/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..96fc4be --- /dev/null +++ b/etl-groovy/src/main/resources/bootstrap.yml @@ -0,0 +1,23 @@ +# Tomcat +server: + port: 9010 +# Spring +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://43.142.12.243:3306/lian + username: root + password: ytt@123 + main: + allow-circular-references: true + application: + # 应用名称 + name: etl-groovy + profiles: + # 环境配置 + active: dev +mybatis-plus: + configuration: + map-underscore-to-camel-case: true + type-aliases-package: com.etl.groovy.entity + mapper-locations: classpath:mappers/*xml diff --git a/etl-groovy/src/test/java/com/etl/groovy/EtlGroovyApplicationTests.java b/etl-groovy/src/test/java/com/etl/groovy/EtlGroovyApplicationTests.java new file mode 100644 index 0000000..5007638 --- /dev/null +++ b/etl-groovy/src/test/java/com/etl/groovy/EtlGroovyApplicationTests.java @@ -0,0 +1,13 @@ +package com.etl.groovy; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EtlGroovyApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/etl-groovy/target/classes/bootstrap.yml b/etl-groovy/target/classes/bootstrap.yml new file mode 100644 index 0000000..96fc4be --- /dev/null +++ b/etl-groovy/target/classes/bootstrap.yml @@ -0,0 +1,23 @@ +# Tomcat +server: + port: 9010 +# Spring +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://43.142.12.243:3306/lian + username: root + password: ytt@123 + main: + allow-circular-references: true + application: + # 应用名称 + name: etl-groovy + profiles: + # 环境配置 + active: dev +mybatis-plus: + configuration: + map-underscore-to-camel-case: true + type-aliases-package: com.etl.groovy.entity + mapper-locations: classpath:mappers/*xml diff --git a/etl-groovy/target/classes/com/etl/groovy/SpringBootGroovyApplication.class b/etl-groovy/target/classes/com/etl/groovy/SpringBootGroovyApplication.class new file mode 100644 index 0000000..5ff0ac8 Binary files /dev/null and b/etl-groovy/target/classes/com/etl/groovy/SpringBootGroovyApplication.class differ diff --git a/etl-groovy/target/classes/com/etl/groovy/entity/Address.class b/etl-groovy/target/classes/com/etl/groovy/entity/Address.class new file mode 100644 index 0000000..6d3c086 Binary files /dev/null and b/etl-groovy/target/classes/com/etl/groovy/entity/Address.class differ diff --git a/etl-groovy/target/classes/com/etl/groovy/mapper/AddressMapper.class b/etl-groovy/target/classes/com/etl/groovy/mapper/AddressMapper.class new file mode 100644 index 0000000..929b4ca Binary files /dev/null and b/etl-groovy/target/classes/com/etl/groovy/mapper/AddressMapper.class differ diff --git a/etl-groovy/target/classes/com/etl/groovy/service/GroovyTestService.class b/etl-groovy/target/classes/com/etl/groovy/service/GroovyTestService.class new file mode 100644 index 0000000..0706d41 Binary files /dev/null and b/etl-groovy/target/classes/com/etl/groovy/service/GroovyTestService.class differ diff --git a/etl-groovy/target/classes/com/etl/groovy/util/SpringContextUtil.class b/etl-groovy/target/classes/com/etl/groovy/util/SpringContextUtil.class new file mode 100644 index 0000000..e3f9433 Binary files /dev/null and b/etl-groovy/target/classes/com/etl/groovy/util/SpringContextUtil.class differ diff --git a/etl-jwt-manage/pom.xml b/etl-jwt-manage/pom.xml new file mode 100644 index 0000000..393087f --- /dev/null +++ b/etl-jwt-manage/pom.xml @@ -0,0 +1,136 @@ + + + 4.0.0 + + com.bwie + etl-cloud + 1.0-SNAPSHOT + + etl-jwt-manage + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + 2021.0.5 + + + + javax.servlet + servlet-api + 2.5 + compile + + + + org.springframework.boot + spring-boot-starter-data-redis + + + com.alibaba + druid-spring-boot-starter + 1.2.6 + + + org.projectlombok + lombok + true + + + + io.jsonwebtoken + jjwt + 0.9.1 + compile + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + com.mysql + mysql-connector-j + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.etl.jwt.EtlJwtManageApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/etl-jwt-manage/src/main/java/com/etl/jwt/config/AuthJwtProperties.java b/etl-jwt-manage/src/main/java/com/etl/jwt/config/AuthJwtProperties.java new file mode 100644 index 0000000..74c3b57 --- /dev/null +++ b/etl-jwt-manage/src/main/java/com/etl/jwt/config/AuthJwtProperties.java @@ -0,0 +1,41 @@ +package com.etl.jwt.config; + +import com.etl.jwt.util.JwtTokenUtil; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +@Data +@ConfigurationProperties(prefix = "auth.jwt") +@Component +public class AuthJwtProperties { + + + //是否开启JWT,即注入相关的类对象 + private Boolean enabled = true; + + //JWT 密钥 + private String secret; + + //accessToken 有效时间 + private Long expiration; + + //header名称 + private String header; + + /** + * 用户登录-用户名参数名称 + */ + private String userParamName = "userId"; + /** + * 用户登录-密码参数名称 + */ + private String pwdParamName = "password"; + + //是否使用默认的JWTAuthController + private Boolean useDefaultController = false; + //跳过认证的路由 + private String skipValidUrl; + +} diff --git a/etl-jwt-manage/src/main/java/com/etl/jwt/util/JwtTokenUtil.java b/etl-jwt-manage/src/main/java/com/etl/jwt/util/JwtTokenUtil.java new file mode 100644 index 0000000..fe0385f --- /dev/null +++ b/etl-jwt-manage/src/main/java/com/etl/jwt/util/JwtTokenUtil.java @@ -0,0 +1,269 @@ +package com.etl.jwt.util; + + +import com.etl.jwt.config.AuthJwtProperties; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.springframework.context.annotation.Bean; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + + +@Component +public class JwtTokenUtil { + + private static final String JWT_CACHE_KEY = "jwt:userId:"; + private static final String USER_ID = "userId"; + private static final String USER_NAME = "username"; + private static final String ACCESS_TOKEN = "access_token"; + private static final String REFRESH_TOKEN = "refresh_token"; + private static final String EXPIRE_IN = "expire_in"; + + @Resource + private StringRedisTemplate stringRedisTemplate; + + @Resource + private AuthJwtProperties jwtProperties; + + + /** + * 生成 token 令牌主方法 + * @param userId 用户Id或用户名 + * @return 令token牌 + */ + public Map generateTokenAndRefreshToken(String userId, String username) { + //生成令牌及刷新令牌 + Map tokenMap = buildToken(userId, username); + //redis缓存结果 + cacheToken(userId, tokenMap); + return tokenMap; + } + + //将token缓存进redis + //方法将生产的token缓存进redis中,进行保存。 + private void cacheToken(String userId, Map tokenMap) { + stringRedisTemplate.opsForHash().put(JWT_CACHE_KEY + userId, ACCESS_TOKEN, tokenMap.get(ACCESS_TOKEN)); + stringRedisTemplate.opsForHash().put(JWT_CACHE_KEY + userId, REFRESH_TOKEN, tokenMap.get(REFRESH_TOKEN)); + stringRedisTemplate.expire(userId, jwtProperties.getExpiration() * 2, TimeUnit.MILLISECONDS); + } + //生成令牌 + private Map buildToken(String userId, String username) { + //生成token令牌 + String accessToken = generateToken(userId, username, null); + //生成刷新令牌 + String refreshToken = generateRefreshToken(userId, username, null); + //存储两个令牌及过期时间,返回结果 + HashMap tokenMap = new HashMap<>(2); + tokenMap.put(ACCESS_TOKEN, accessToken); + tokenMap.put(REFRESH_TOKEN, refreshToken); + tokenMap.put(EXPIRE_IN, jwtProperties.getExpiration()); + return tokenMap; + } + /** + * 生成 token 令牌 及 refresh token 令牌 + * @param payloads 令牌中携带的附加信息 + * @return 令牌 + */ + public String generateToken(String userId, String username, + Map payloads) { + Map claims = buildClaims(userId, username, payloads);; + + return generateToken(claims); + } + public String generateRefreshToken(String userId, String username, Map payloads) { + Map claims = buildClaims(userId, username, payloads); + + return generateRefreshToken(claims); + } + //构建map存储令牌需携带的信息 + //此方法中存放业务所需存放的信息,比如用户名,id等,生成的jwt解码后,payload中可查得以上信息 + private Map buildClaims(String userId, String username, Map payloads) { + int payloadSizes = payloads == null? 0 : payloads.size(); + + Map claims = new HashMap<>(payloadSizes + 2); + claims.put("sub", userId); + claims.put("username", username); + claims.put("created", new Date()); + //claims.put("roles", "admin"); + + if(payloadSizes > 0){ + claims.putAll(payloads); + } + + return claims; + } + + + /** + * 刷新令牌并生成新令牌 + * 并将新结果缓存进redis + */ + public Map refreshTokenAndGenerateToken(String userId, String username) { + Map tokenMap = buildToken(userId, username); + stringRedisTemplate.delete(JWT_CACHE_KEY + userId); + cacheToken(userId, tokenMap); + return tokenMap; + } + + /** + * 从request获取userid + * @param request http请求 + * @return request.getHeader + */ + public String getUserIdFromRequest(HttpServletRequest request) { + return request.getHeader(USER_ID); + } + + //缓存中删除token + public boolean removeToken(String userId) { + return Boolean.TRUE.equals(stringRedisTemplate.delete(JWT_CACHE_KEY + userId)); + } + + + /** + * 从令牌中获取用户id + * + * @param token 令牌 + * @return 用户id + */ + public String getUserIdFromToken(String token) { + String userId; + try { + Claims claims = getClaimsFromToken(token); + userId = claims.getSubject(); + } catch (Exception e) { + userId = null; + } + return userId; + } + /** + * 从令牌中获取用户名 + * + * @param token 令牌 + * @return 用户名 + */ + public String getUserNameFromToken(String token) { + String username; + try { + Claims claims = getClaimsFromToken(token); + username = (String) claims.get(USER_NAME); + } catch (Exception e) { + username = null; + } + return username; + } + + + /** + * 判断令牌是否不存在 redis 中 + * + * @param token 刷新令牌 + * @return true=不存在,false=存在 + */ + public Boolean isRefreshTokenNotExistCache(String token) { + String userId = getUserIdFromToken(token); + String refreshToken = (String)stringRedisTemplate.opsForHash().get(JWT_CACHE_KEY + userId, REFRESH_TOKEN); + return refreshToken == null || !refreshToken.equals(token); + } + + /** + * 判断令牌是否过期 + * + * @param token 令牌 + * @return true=已过期,false=未过期 + */ + public Boolean isTokenExpired(String token) { + try { + Claims claims = getClaimsFromToken(token); + Date expiration = claims.getExpiration(); + return expiration.before(new Date()); + } catch (Exception e) { + //验证 JWT 签名失败等同于令牌过期 + return true; + } + } + + /** + * 刷新令牌 + * + * @param token 原令牌 + * @return 新令牌 + */ + public String refreshToken(String token) { + String refreshedToken; + try { + Claims claims = getClaimsFromToken(token); + claims.put("created", new Date()); + refreshedToken = generateToken(claims); + } catch (Exception e) { + refreshedToken = null; + } + return refreshedToken; + } + + /** + * 验证令牌 + * + * @param token 令牌 + * @param userId 用户Id用户名 + * @return 是否有效 + */ + public Boolean validateToken(String token, String userId) { + + String username = getUserIdFromToken(token); + return (username.equals(userId) && !isTokenExpired(token)); + } + + + /** + * 生成令牌 + * @param claims 数据声明 + * @return 令牌 + */ + private String generateToken(Map claims) { + Date expirationDate = new Date(System.currentTimeMillis() + + jwtProperties.getExpiration()); + return Jwts.builder().setClaims(claims) + .setExpiration(expirationDate) + .signWith(SignatureAlgorithm.HS512, + jwtProperties.getSecret()) + .compact(); + } + /** + * 生成刷新令牌 refreshToken,有效期是令牌的 2 倍 + * @param claims 数据声明 + * @return 令牌 + */ + private String generateRefreshToken(Map claims) { + Date expirationDate = new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 2); + return Jwts.builder().setClaims(claims) + .setExpiration(expirationDate) + .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret()) + .compact(); + } + + /** + * 从令牌中获取数据声明,验证 JWT 签名 + * + * @param token 令牌 + * @return 数据声明 + */ + private Claims getClaimsFromToken(String token) { + Claims claims; + try { + claims = Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody(); + } catch (Exception e) { + claims = null; + } + return claims; + } +} + diff --git a/etl-jwt-manage/target/classes/META-INF/spring-configuration-metadata.json b/etl-jwt-manage/target/classes/META-INF/spring-configuration-metadata.json new file mode 100644 index 0000000..52c9406 --- /dev/null +++ b/etl-jwt-manage/target/classes/META-INF/spring-configuration-metadata.json @@ -0,0 +1,54 @@ +{ + "groups": [ + { + "name": "auth.jwt", + "type": "com.etl.jwt.config.AuthJwtProperties", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + } + ], + "properties": [ + { + "name": "auth.jwt.enabled", + "type": "java.lang.Boolean", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.expiration", + "type": "java.lang.Long", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.header", + "type": "java.lang.String", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.pwd-param-name", + "type": "java.lang.String", + "description": "用户登录-密码参数名称", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.secret", + "type": "java.lang.String", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.skip-valid-url", + "type": "java.lang.String", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.use-default-controller", + "type": "java.lang.Boolean", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + }, + { + "name": "auth.jwt.user-param-name", + "type": "java.lang.String", + "description": "用户登录-用户名参数名称", + "sourceType": "com.etl.jwt.config.AuthJwtProperties" + } + ], + "hints": [] +} \ No newline at end of file diff --git a/etl-jwt-manage/target/classes/com/etl/jwt/config/AuthJwtProperties.class b/etl-jwt-manage/target/classes/com/etl/jwt/config/AuthJwtProperties.class new file mode 100644 index 0000000..86beca1 Binary files /dev/null and b/etl-jwt-manage/target/classes/com/etl/jwt/config/AuthJwtProperties.class differ diff --git a/etl-jwt-manage/target/classes/com/etl/jwt/util/JwtTokenUtil.class b/etl-jwt-manage/target/classes/com/etl/jwt/util/JwtTokenUtil.class new file mode 100644 index 0000000..b0b5e70 Binary files /dev/null and b/etl-jwt-manage/target/classes/com/etl/jwt/util/JwtTokenUtil.class differ diff --git a/etl-jwt-manage/target/etl-jwt-manage-1.0-SNAPSHOT.jar b/etl-jwt-manage/target/etl-jwt-manage-1.0-SNAPSHOT.jar new file mode 100644 index 0000000..91f4862 Binary files /dev/null and b/etl-jwt-manage/target/etl-jwt-manage-1.0-SNAPSHOT.jar differ diff --git a/etl-jwt-manage/target/maven-archiver/pom.properties b/etl-jwt-manage/target/maven-archiver/pom.properties new file mode 100644 index 0000000..918f375 --- /dev/null +++ b/etl-jwt-manage/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Tue Jun 25 09:14:52 CST 2024 +version=1.0-SNAPSHOT +groupId=com.bwie +artifactId=etl-jwt-manage diff --git a/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..680670f --- /dev/null +++ b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,3 @@ +com\etl\jwt\config\AuthJwtProperties.class +com\etl\jwt\util\JwtTokenUtil.class +META-INF\spring-configuration-metadata.json diff --git a/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..8dcd269 --- /dev/null +++ b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,2 @@ +D:\workspace\ETL\etl-jwt-manage\src\main\java\com\etl\jwt\config\AuthJwtProperties.java +D:\workspace\ETL\etl-jwt-manage\src\main\java\com\etl\jwt\util\JwtTokenUtil.java diff --git a/etl-jwt-manage/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst new file mode 100644 index 0000000..e69de29 diff --git a/etl-jwt-manage/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst b/etl-jwt-manage/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst new file mode 100644 index 0000000..e69de29 diff --git a/pom.xml b/pom.xml index 7933abc..c6d7086 100644 --- a/pom.xml +++ b/pom.xml @@ -13,6 +13,9 @@ etl-gateway etl-data-source etl-heihei + etl-groovy + etl-auth + etl-jwt-manage @@ -27,6 +30,7 @@ + com.baomidou mybatis-plus-boot-starter @@ -35,6 +39,7 @@ org.springframework.boot spring-boot-starter-data-jdbc + ${spring-boot.version}