tao.mo

Merge remote-tracking branch 'origin/master'

Showing 78 changed files with 4077 additions and 18 deletions
package com.fedex.connect.common.dao.log;
import com.fedex.connect.common.model.log.UserLoginInfo;
import com.fedex.connect.common.model.log.UserLoginInfoExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserLoginInfoMapper {
long countByExample(UserLoginInfoExample example);
int deleteByExample(UserLoginInfoExample example);
int deleteByPrimaryKey(Long id);
int insert(UserLoginInfo record);
int insertSelective(UserLoginInfo record);
List<UserLoginInfo> selectByExample(UserLoginInfoExample example);
UserLoginInfo selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UserLoginInfo record, @Param("example") UserLoginInfoExample example);
int updateByExample(@Param("record") UserLoginInfo record, @Param("example") UserLoginInfoExample example);
int updateByPrimaryKeySelective(UserLoginInfo record);
int updateByPrimaryKey(UserLoginInfo record);
}
\ No newline at end of file
package com.fedex.connect.common.dao.log;
\ No newline at end of file
package com.fedex.connect.common.dao.sys;
import com.fedex.connect.common.model.sys.RedisSlab;
import com.fedex.connect.common.model.sys.RedisSlabExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RedisSlabMapper {
long countByExample(RedisSlabExample example);
int deleteByExample(RedisSlabExample example);
int deleteByPrimaryKey(Long id);
int insert(RedisSlab record);
int insertSelective(RedisSlab record);
List<RedisSlab> selectByExample(RedisSlabExample example);
RedisSlab selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") RedisSlab record, @Param("example") RedisSlabExample example);
int updateByExample(@Param("record") RedisSlab record, @Param("example") RedisSlabExample example);
int updateByPrimaryKeySelective(RedisSlab record);
int updateByPrimaryKey(RedisSlab record);
}
\ No newline at end of file
package com.fedex.connect.common.mapper.log;
\ No newline at end of file
package com.fedex.connect.common.model.log;
import java.io.Serializable;
import java.util.Date;
/**
* DESC: 用户登录日志表
* TABLE: T_LOG_USER_LOGIN_INFO
*/
public class UserLoginInfo implements Serializable {
/**
* ID,主键自增
*/
private Long id;
/**
* 操作人用户ID,关联用户表ID
*/
private Long userId;
/**
* 操作类型ID。
关联数据字典表。指定字典目录CODE:USER_LOGIN_TYPE
*/
private Long operTypeId;
/**
* 操作类型名称(登录、退出、修改密码、FCL登录注册,、停用、启用)
*/
private String operTypeName;
/**
* 操作描述
*/
private String operDesc;
/**
* 操作IP
*/
private String ip;
/**
* 创建时间
*/
private Date createTime;
/**
* 创建人ID,关联用户表ID
*/
private Long createUserId;
/**
* 创建人名称
*/
private String createUserName;
/**
* 修改时间
*/
private Date modifyTime;
/**
* 修改人ID,关联用户表ID
*/
private Long modifyUserId;
/**
* 修改人名称
*/
private String modifyUserName;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getOperTypeId() {
return operTypeId;
}
public void setOperTypeId(Long operTypeId) {
this.operTypeId = operTypeId;
}
public String getOperTypeName() {
return operTypeName;
}
public void setOperTypeName(String operTypeName) {
this.operTypeName = operTypeName == null ? null : operTypeName.trim();
}
public String getOperDesc() {
return operDesc;
}
public void setOperDesc(String operDesc) {
this.operDesc = operDesc == null ? null : operDesc.trim();
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
}
public String getCreateUserName() {
return createUserName;
}
public void setCreateUserName(String createUserName) {
this.createUserName = createUserName == null ? null : createUserName.trim();
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Long getModifyUserId() {
return modifyUserId;
}
public void setModifyUserId(Long modifyUserId) {
this.modifyUserId = modifyUserId;
}
public String getModifyUserName() {
return modifyUserName;
}
public void setModifyUserName(String modifyUserName) {
this.modifyUserName = modifyUserName == null ? null : modifyUserName.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userId=").append(userId);
sb.append(", operTypeId=").append(operTypeId);
sb.append(", operTypeName=").append(operTypeName);
sb.append(", operDesc=").append(operDesc);
sb.append(", ip=").append(ip);
sb.append(", createTime=").append(createTime);
sb.append(", createUserId=").append(createUserId);
sb.append(", createUserName=").append(createUserName);
sb.append(", modifyTime=").append(modifyTime);
sb.append(", modifyUserId=").append(modifyUserId);
sb.append(", modifyUserName=").append(modifyUserName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
package com.fedex.connect.common.model.log;
\ No newline at end of file
package com.fedex.connect.common.model.sys;
import java.io.Serializable;
import java.util.Date;
/**
* DESC: 用户登录信息token表
* TABLE: T_SYS_REDIS_SLAB
*/
public class RedisSlab implements Serializable {
/**
* ID,自动增加
*/
private Long id;
/**
* Redis key
*/
private String redisKey;
/**
* Redis信息
*/
private String redisMsg;
/**
* 有效时长
*/
private Long validDuration;
/**
* 失效时间
*/
private Date disTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 创建人ID,关联用户表ID
*/
private Long createUserId;
/**
* 创建人名称
*/
private String createUserName;
/**
* 修改时间
*/
private Date modifyTime;
/**
* 修改人ID,关联用户表ID
*/
private Long modifyUserId;
/**
* 修改人名称
*/
private String modifyUserName;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRedisKey() {
return redisKey;
}
public void setRedisKey(String redisKey) {
this.redisKey = redisKey == null ? null : redisKey.trim();
}
public String getRedisMsg() {
return redisMsg;
}
public void setRedisMsg(String redisMsg) {
this.redisMsg = redisMsg == null ? null : redisMsg.trim();
}
public Long getValidDuration() {
return validDuration;
}
public void setValidDuration(Long validDuration) {
this.validDuration = validDuration;
}
public Date getDisTime() {
return disTime;
}
public void setDisTime(Date disTime) {
this.disTime = disTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
}
public String getCreateUserName() {
return createUserName;
}
public void setCreateUserName(String createUserName) {
this.createUserName = createUserName == null ? null : createUserName.trim();
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Long getModifyUserId() {
return modifyUserId;
}
public void setModifyUserId(Long modifyUserId) {
this.modifyUserId = modifyUserId;
}
public String getModifyUserName() {
return modifyUserName;
}
public void setModifyUserName(String modifyUserName) {
this.modifyUserName = modifyUserName == null ? null : modifyUserName.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", redisKey=").append(redisKey);
sb.append(", redisMsg=").append(redisMsg);
sb.append(", validDuration=").append(validDuration);
sb.append(", disTime=").append(disTime);
sb.append(", createTime=").append(createTime);
sb.append(", createUserId=").append(createUserId);
sb.append(", createUserName=").append(createUserName);
sb.append(", modifyTime=").append(modifyTime);
sb.append(", modifyUserId=").append(modifyUserId);
sb.append(", modifyUserName=").append(modifyUserName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
......@@ -40,7 +40,7 @@
sys:系统 系统相关表,例如kafka表
log: 日志 日志记录表,例如邮件发送日志表
-->
<javaModelGenerator targetPackage="com.fedex.connect.common.model.base" targetProject="src/main/java">
<javaModelGenerator targetPackage="com.fedex.connect.common.model.sys" targetProject="src/main/java">
<!---enableSubPackages:如果true,MBG会根据catalog和schema来生成子包。如果false就会直接用targetPackage属性-->
<property name="enableSubPackages" value="false"/>
<!--该属性只对MyBatis3有效,如果true就会使用构造方法入参,如果false就会使用setter方式。默认为false-->
......@@ -52,13 +52,13 @@
</javaModelGenerator>
<!-- 生成映射文件*.xml的位置-->
<sqlMapGenerator targetPackage="mapper.base" targetProject="src/main/java/com/fedex/connect/common">
<sqlMapGenerator targetPackage="mapper.sys" targetProject="src/main/java/com/fedex/connect/common">
<!--如果true,MBG会根据catalog和schema来生成子包。如果false就会直接用targetPackage属性。默认为false-->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.fedex.connect.common.dao.base" targetProject="src/main/java">
<javaClientGenerator type="XMLMAPPER" targetPackage="com.fedex.connect.common.dao.sys" targetProject="src/main/java">
<!--如果true,MBG会根据catalog和schema来生成子包。如果false就会直接用targetPackage属性。默认为false-->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
......@@ -73,6 +73,13 @@
generatedKey 指定KEY,Oracle需要指定序列。
sqlStatement 指定序列名称
-->
<table tableName="T_SYS_REDIS_SLAB" domainObjectName="redisSlab"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
selectByExampleQueryId="true">
<generatedKey column="ID" sqlStatement="SELECT SEQ_T_SYS_REDIS_SLAB.NEXTVAL FROM DUAL" />
</table>
<!-- <table tableName="T_KAFKA_TEMPORARY_STORAGE" domainObjectName="KafkaTemporaryStorage"-->
<!-- enableCountByExample="true" enableUpdateByExample="true"-->
<!-- enableDeleteByExample="true" enableSelectByExample="true"-->
......@@ -123,18 +130,18 @@
<!-- </table>-->
<table tableName="T_BI_DICTIONARY_ENTRIES" domainObjectName="DictionaryEntries"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
selectByExampleQueryId="true">
<generatedKey column="ID" sqlStatement="SELECT SEQ_T_BI_DICTIONARY_ENTRIES.NEXTVAL FROM DUAL" />
</table>
<table tableName="T_BI_DICTIONARY" domainObjectName="Dictionary"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
selectByExampleQueryId="true">
<generatedKey column="ID" sqlStatement="SELECT SEQ_T_BI_DICTIONARY.NEXTVAL FROM DUAL" />
</table>
<!-- <table tableName="T_BI_DICTIONARY_ENTRIES" domainObjectName="DictionaryEntries"-->
<!-- enableCountByExample="true" enableUpdateByExample="true"-->
<!-- enableDeleteByExample="true" enableSelectByExample="true"-->
<!-- selectByExampleQueryId="true">-->
<!-- <generatedKey column="ID" sqlStatement="SELECT SEQ_T_BI_DICTIONARY_ENTRIES.NEXTVAL FROM DUAL" />-->
<!-- </table>-->
<!-- <table tableName="T_BI_DICTIONARY" domainObjectName="Dictionary"-->
<!-- enableCountByExample="true" enableUpdateByExample="true"-->
<!-- enableDeleteByExample="true" enableSelectByExample="true"-->
<!-- selectByExampleQueryId="true">-->
<!-- <generatedKey column="ID" sqlStatement="SELECT SEQ_T_BI_DICTIONARY.NEXTVAL FROM DUAL" />-->
<!-- </table>-->
<!-- <table tableName="T_TASK_MANAGEMENT" domainObjectName="TaskManagement"-->
......
package com.fedex.connect.common.dependencies.arithmetic;
/**
* 密钥的长度
*/
public enum AESType {
AES_128(128),
AES_192(192),
AES_256(256);
public int value;
private AESType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
package com.fedex.connect.common.dependencies.arithmetic;
/**
*
*/
public class EncodeType {
/**
算法/模式/填充 字节加密后数据长度 不满16字节加密后长度
AES/CBC/NoPadding 16 不支持
AES/CBC/PKCS5Padding 32 16
AES/CBC/ISO10126Padding 32 16
AES/CFB/NoPadding 16 原始数据长度
AES/CFB/PKCS5Padding 32 16
AES/CFB/ISO10126Padding 32 16
AES/ECB/NoPadding 16 不支持
AES/ECB/PKCS5Padding 32 16
AES/ECB/ISO10126Padding 32 16
AES/OFB/NoPadding 16 原始数据长度
AES/OFB/PKCS5Padding 32 16
AES/OFB/ISO10126Padding 32 16
AES/PCBC/NoPadding 16 不支持
AES/PCBC/PKCS5Padding 32 16
AES/PCBC/ISO10126Padding 32 16
*/
//默认为 AES_CBC_PKCS5PADDING
public final static String AES_DEFAULT = "AES";
public final static String AES_CBC_NOPADDING = "AES/CBC/NoPadding";
public final static String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
public final static String AES_CBC_ISO10126PADDING = "AES/CBC/ISO10126Padding";
public final static String AES_CFB_NOPADDING = "AES/CFB/NoPadding";
public final static String AES_CFB_PKCS5PADDING = "AES/CFB/PKCS5Padding";
public final static String AES_CFB_ISO10126PADDING = "AES/CFB/ISO10126Padding";
public final static String AES_ECB_NOPADDING = "AES/ECB/NoPadding";
public final static String AES_ECB_PKCS5PADDING = "AES/ECB/PKCS5Padding";
public final static String AES_ECB_ISO10126PADDING = "AES/ECB/ISO10126Padding";
public final static String AES_OFB_NOPADDING = "AES/OFB/NoPadding";
public final static String AES_OFB_PKCS5PADDING = "AES/OFB/PKCS5Padding";
public final static String AES_OFB_ISO10126PADDING = "AES/OFB/ISO10126Padding";
public final static String AES_PCBC_NOPADDING = "AES/PCBC/NoPadding";
public final static String AES_PCBC_PKCS5PADDING = "AES/PCBC/PKCS5Padding";
public final static String AES_PCBC_ISO10126PADDING = "AES/PCBC/ISO10126Padding";
}
package com.fedex.connect.common.dependencies.authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
/**
* @author Administrator
*/
public class EncryptProvider {
//加密密钥
private static final PasswordEncoder ENCODER = new StandardPasswordEncoder("exportTw");
/**
* Spring-security-crypto加密方式
*
* @param pwd 需要加密的密码
*/
public static String encrypt(String pwd) {
return ENCODER.encode(pwd);
}
/**
* 校验原密码和加密后的密码是否一致
*
* @param pwd 原密码
* @param encodedPassword 加密后的密码
* @return
*/
public static boolean match(String pwd, String encodedPassword) {
return ENCODER.matches(pwd, encodedPassword);
}
}
package com.fedex.connect.common.dependencies.authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 登录失败处理器
* @author Administrator
*/
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final String forwardUrl;
public MyAuthenticationFailureHandler(String forwardUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
return "'" + forwardUrl + "' is not a valid forward URL";
});
this.forwardUrl = forwardUrl;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
response.sendRedirect(forwardUrl);
}
}
package com.fedex.connect.common.dependencies.authentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 自定义认证成功处理器
* @author Administrator
*/
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final String forwardUrl;
public MyAuthenticationSuccessHandler(String forwardUrl) {
this.forwardUrl = forwardUrl;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.sendRedirect(forwardUrl);
}
}
package com.fedex.connect.common.dependencies.authentication;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 读取配置文件
* @author Administrator
*/
@ConfigurationProperties(prefix = "export.jwt")
public class SecurityConstants {
/**
* 定义鉴权使用常量
*/
public static final String TOKEN_HEADER = "Authorization";
public static final String REFLUSH_TOKEN= "ReflushToken";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String TOKEN_TYPE = "JWT";
public static final String ROLE_CLAIMS = "rol";
public static long expire_1H;
public static long expire_1D;
/**
* JWT 的 秘钥
*/
public static String securitykey;
public static String[] urlWhiteList;
public static String[] uriWhiteList;
public static long getExpire_1H() {
return expire_1H;
}
public void setExpire_1H(long expire_1H) {
SecurityConstants.expire_1H = expire_1H;
}
public static long getExpire_1D() {
return expire_1D;
}
public void setExpire_1D(long expire_1D) {
SecurityConstants.expire_1D = expire_1D;
}
public static String getSecuritykey() {
return securitykey;
}
public void setSecuritykey(String securitykey) {
SecurityConstants.securitykey = securitykey;
}
public static String[] getUrlWhiteList() {
return urlWhiteList;
}
public void setUrlWhiteList(String[] urlWhiteList) {
SecurityConstants.urlWhiteList = urlWhiteList;
}
public static String[] getUriWhiteList() {
return uriWhiteList;
}
public void setUriWhiteList(String[] uriWhiteList) {
SecurityConstants.uriWhiteList = uriWhiteList;
}
}
package com.fedex.connect.common.dependencies.authentication;
import com.fedex.export.authentication.exception.JwtAccessDeniedHandler;
import com.fedex.export.authentication.exception.JwtAuthenticationEntryPoint;
import com.fedex.export.authentication.filter.JwtAuthorizationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Spring-Security 配置
* @author Administrator
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置安全过滤器
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//放行白名单(这个配置会比读取配置文件优先进行,别问我怎么知道的)
String[] whiteList = {"/icleartw/login.html","/icleartw/auth/login","/icleartw/auth/addUser",
"/icleartw/oss/ossLogin", "/icleartw/sysUser/logout","/icleartw/auth/getUser","/icleartw/static/*",
"/icleartw/swagger-ui.html","/icleartw/swagger-resources","/icleartw/webjars","/icleartw/swagger-ui/*", "/icleartw/v2/api-docs","/**"};
//formLogin配置登录页面和成功/失败的响应
http.formLogin()
.loginPage("/icleartw/login.html").permitAll()
//.successHandler(new MyAuthenticationSuccessHandler("/main"))
//.failureHandler(new MyAuthenticationFailureHandler("/403.html"))
.and()
//authorizeRequests方法配置访问控制规则
.authorizeRequests()
.antMatchers(whiteList).permitAll()
.anyRequest().authenticated() //其他未定义的 URL 需要进行身份认证才能访问
//添加JWT
.and()
//配置过滤器
.addFilter(new JwtAuthorizationFilter(super.authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //禁用Session
.and().exceptionHandling()
.authenticationEntryPoint(new JwtAuthenticationEntryPoint()) //拒绝访问处理
.accessDeniedHandler(new JwtAccessDeniedHandler()) //无权访问处理
.and().logout().permitAll()
.and().csrf().disable();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
//添加BC加密算法
return new BCryptPasswordEncoder();
}
}
package com.fedex.connect.common.dependencies.authentication.exception;
import com.fedex.export.common.i18n.LocaleMessageUtil;
import com.fedex.export.common.util.SpringBeanUtil;
import com.fedex.export.data.vo.JsonResult;
import com.google.gson.Gson;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Administrator
*
*/
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
/**
* 没有访问权限:当用户通过认证,但没有足够的权限对指定资源操作,返回403
*/
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
JsonResult result = new JsonResult();
result.setCode(HttpServletResponse.SC_FORBIDDEN);
//使用context手动注入
LocaleMessageUtil localeMessageUtil = SpringBeanUtil.getBean(LocaleMessageUtil.class);
result.setMsg(localeMessageUtil.getMessage("auth_exc_no_auth"));
Gson gson = new Gson();
response.getWriter().println(gson.toJson(result));
response.getWriter().flush();
}
}
package com.fedex.connect.common.dependencies.authentication.exception;
import com.fedex.export.common.i18n.LocaleMessageUtil;
import com.fedex.export.common.util.SpringBeanUtil;
import com.fedex.export.data.vo.JsonResult;
import com.google.gson.Gson;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 拒绝访问:当用户没有通过认证,返回401
* @author Administrator
*/
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
JsonResult result = new JsonResult();
result.setCode(HttpServletResponse.SC_UNAUTHORIZED);
//使用context手动注入
LocaleMessageUtil localeMessageUtil = SpringBeanUtil.getBean(LocaleMessageUtil.class);
result.setMsg(localeMessageUtil.getMessage("auth_exc_no_pass_auth"));
Gson gson = new Gson();
response.getWriter().println(gson.toJson(result));
response.getWriter().flush();
}
}
package com.fedex.connect.common.dependencies.authentication.filter;
import com.fedex.export.authentication.SecurityConstants;
import com.fedex.export.common.contants.RedisConstants;
import com.fedex.export.common.i18n.LocaleMessageUtil;
import com.fedex.export.common.util.JsonUtils;
import com.fedex.export.common.util.JwtTokenUtils;
import com.fedex.export.common.util.SpringBeanUtil;
import com.fedex.export.common.util.Utils;
import com.fedex.export.repository.entity.RedisSlab;
import com.fedex.export.service.system.RedisUtilService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* Spring Security实际 上是基于Filter实现的
* 写一个过滤器,继承BasicAuthenticationFilter
* @author EDY
*/
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
private Logger logger = LoggerFactory.getLogger(JwtAuthorizationFilter.class);
public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
String token = request.getHeader(SecurityConstants.TOKEN_HEADER);
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN,Token,userName,client,OBLIX_UID");
response.setHeader("Access-Control-Expose-Headers", "Token");
//放行白名单
List<String> urlWhiteList = Arrays.asList(SecurityConstants.urlWhiteList);
List<String> uriWhiteList = Arrays.asList(SecurityConstants.uriWhiteList);
//返回请求行中的资源名部分
String requestUri = request.getRequestURI();
//返回客户端发出请求完整URL
String reqeustUrl = request.getRequestURL().toString();
logger.info("------------- FROM NETWORK :{}", requestUri);
if (reqeustUrl.indexOf("/sysUser/logout") > 0) {
//退出登录接口,不验token
chain.doFilter(request, response);
return;
}
//使用context手动注入
LocaleMessageUtil localeMessageUtil = SpringBeanUtil.getBean(LocaleMessageUtil.class);
RedisUtilService redisUtilService = SpringBeanUtil.getBean(RedisUtilService.class);
if (token == null || !token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
SecurityContextHolder.clearContext();
if(Utils.listOf(urlWhiteList).stream().filter(Objects::nonNull).anyMatch(urlW -> reqeustUrl.indexOf(urlW) > 0)
|| Utils.listOf(uriWhiteList).stream().filter(Objects::nonNull).anyMatch(uriW -> requestUri.equals(uriW))
|| Utils.listOf(uriWhiteList).stream().filter(Objects::nonNull).filter(u -> u.indexOf("*") > 0).anyMatch(uriW -> requestUri.startsWith(uriW.replace("*","")))
|| "/".equals(requestUri)
|| "OPTIONS".equals(request.getMethod())){
logger.info("--------------- 登录白名单无需验证");
chain.doFilter(request, response);
return;
}
Map<String, Object> result = new HashMap<>();
result.put("code", 301);
result.put("msg", localeMessageUtil.getMessage("auth_filter_user_error"));
logger.info("CODE_301 requestURL:{} ,reason:{}" , request.getRequestURL()," 非白名单url路径登录");
ServletOutputStream out = response.getOutputStream();
out.write(JsonUtils.mapToJson(result).getBytes());
out.flush();
return;
}
UsernamePasswordAuthenticationToken authentication = null;
//判断accessToken是否过期
String tokenValue = token.replace(SecurityConstants.TOKEN_PREFIX, "");
try {
Date expiredTime = JwtTokenUtils.getAccessTokenExpiredTime(tokenValue);
logger.debug("TOKEN 过期时间为 :{}", expiredTime);
String id = JwtTokenUtils.getId(tokenValue);
String redisKey = RedisConstants.REDIS_KEY_TOKEN + id;
RedisSlab redisSlab = redisUtilService.get(redisKey);
String tokenRedis = redisSlab != null ? Optional.ofNullable(redisSlab.getRedisMsg()).orElse(null): null;
/*String tokenRedis = redisUtilService.get(redisKey);*/
if (StringUtils.isEmpty(tokenRedis)) {
//redis没有,超过8小时,踢出去
Map<String, Object> result = new HashMap<>();
result.put("code", 301);
result.put("msg", localeMessageUtil.getMessage("auth_filter_timeout"));
logger.info("CODE_301 requestURL:{} ,reason:{}" , request.getRequestURL() ,"tokenRedis is empty");
ServletOutputStream out = response.getOutputStream();
out.write(JsonUtils.mapToJson(result).getBytes());
out.flush();
return;
}
/*//更新token
String tokenRedisValue = tokenRedis.replace(SecurityConstants.TOKEN_PREFIX, "");
String userName = JwtTokenUtils.getUserName(tokenRedisValue);
List<String> role = JwtTokenUtils.getRoleList(tokenRedisValue);
//返回前端的新token
String newToken = JwtTokenUtils.createReflushToken(userName, id, role);
logger.info("REFRESH TOKEN ");
response.setHeader("Token", newToken);*/
} catch (ExpiredJwtException ee) {
//已经过期了,直接踢
logger.info("CODE_301 requestURL:{},reason:{}" , request.getRequestURL(),"ExpiredJwtException ",ee);
Claims claims = ee.getClaims();
String id = claims.getId();
Map<String, Object> result = new HashMap<>();
result.put("code", 301);
result.put("msg", localeMessageUtil.getMessage("auth_filter_stale_dated"));
ServletOutputStream out = response.getOutputStream();
out.write(JsonUtils.mapToJson(result).getBytes());
out.flush();
return;
} catch (Exception e) {
logger.error("*********************token 异常 : *******************************", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 301);
result.put("msg", localeMessageUtil.getMessage("auth_filter_user_error"));
ServletOutputStream out = response.getOutputStream();
out.write(JsonUtils.mapToJson(result).getBytes());
out.flush();
return;
}
authentication = JwtTokenUtils.getAuthentication(tokenValue);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
return;
}
}
package com.fedex.connect.common.dependencies.config;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.dependencies.util.Utils;
import com.fedex.connect.common.model.base.DictionaryEntries;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* 预先数据的加载
* 有兴趣了解搜索:CommandLineRunner详解
* @author EDY
*/
@Component
@Order(1)
public class CacheSystem implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(CacheSystem.class);
// 从 DictionaryProvider 获取字典数据
List<DictionaryEntries> dictionaryData = DictionaryProvider.getDictionaryData();
// 静态缓存数据
public static List<DictionaryEntries> dictionaryListAll = new ArrayList<>();
public static Map<String, List<DictionaryEntries>> dictionaryMap = new HashMap<>();
public static Map<String, String> declarationTypeMap = new HashMap<>();
public static Map<String, String> deliveryStatusMap = new HashMap<>();
public static Map<String, String> operStatusMap = new HashMap<>();
public static List<DictionaryEntries> currencyCdList = new ArrayList<>();
@Override
public void run(String... args) {
if (dictionaryData == null) {
log.warn("SysDictionaryService not set, skipping cache initialization.");
return;
}
log.info("System init load to cache in memory start");
try{
CacheSystem.dictionaryListAll = dictionaryData;
if (CollectionUtils.isEmpty(CacheSystem.dictionaryListAll)){
return;
}
CacheSystem.dictionaryMap = Utils.listOf(CacheSystem.dictionaryListAll).stream().filter(Objects::nonNull)
.collect(Collectors.groupingBy(DictionaryEntries::getDictCode));
List<DictionaryEntries> declarationTypeList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_CUSTOMS_DECLARATION_TYPE_CODE);
CacheSystem.declarationTypeMap = Utils.listOf(declarationTypeList).stream()
.collect(Collectors.toMap(DictionaryEntries::getCode, DictionaryEntries::getEnglishName));
List<DictionaryEntries> deliveryStatusList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_DELIVERY_STATUS_CODE);
CacheSystem.deliveryStatusMap = Utils.listOf(deliveryStatusList).stream()
.collect(Collectors.toMap(DictionaryEntries::getCode, DictionaryEntries::getEnglishName));
List<DictionaryEntries> operStatusList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_OPER_STATUS_CODE);
CacheSystem.operStatusMap = Utils.listOf(operStatusList).stream()
.collect(Collectors.toMap(DictionaryEntries::getCode, DictionaryEntries::getEnglishName));
CacheSystem.currencyCdList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_CURRENCY_CD_CODE);
} catch (Exception e){
log.error("load cache error:{}",e);
} log.info("System init load to cache in memory end");
}
}
package com.fedex.connect.common.dependencies.config;
import com.fedex.connect.common.model.base.DictionaryEntries;
import java.util.List;
public class DictionaryProvider {
// 用于存储字典数据的静态列表
private static List<DictionaryEntries> dictionaryData;
// 设置字典数据的方法
public static void setDictionaryData(List<DictionaryEntries> data) {
dictionaryData = data;
}
// 获取字典数据的方法
public static List<DictionaryEntries> getDictionaryData() {
return dictionaryData;
}
}
package com.fedex.connect.common.dependencies.contants;
/**
* 定义数据库同样常量
*/
public class DatabaseConstants {
/**
* 定义通用状态常量。
* 1:有效[true]。0:无效[false]
*/
public static final Long GLOBAL_STATUS_VALID = 1L;
public static final Long GLOBAL_STATUS_DEL = 0L;
/**
* 定义操作状态常量
* 1: 已提交 2:正在录入
*/
public static final Long GLOBAL_OPER_STATUS_SAVE = 1L;
public static final Long GLOBAL_OPER_STATUS_DRAFT = 2L;
/**
* 定义申报信息提单状态
* 0:未发送 (冗余)
* 1:已发送(异步成功状态)
* 2:已接收。(回执成功状态)
* 3:发送失败。(提交后异步发送失败状态。定时任务补偿机制读取此状态数据)
* 4:接收失败。
* (4-1:3次重发邮件都失败。
* 4-2:回执3次重试读取仍失败为此状态。
* 4-3:超过1小时为此状态。
* 4-4:3次匹配不到为此状态。
* 4-5:其他失败)
*/
public static final Long DELIVERY_STATUS_UNSENT = 0L;
public static final Long DELIVERY_STATUS_SENT = 1L;
public static final Long DELIVERY_STATUS_RECEIVE = 2L;
public static final Long DELIVERY_STATUS_SENT_FAIL = 3L;
public static final Long DELIVERY_STATUS_RECEIVE_FAIL = 4L;
/**
* 定义文件来源常量
* 1:上传。2:系统生成。3:图案商标
*/
public static final Long FILE_SOURCE_UPDATE = 1L;
public static final Long FILE_SOURCE_SYS_CREATE = 2L;
public static final Long FILE_SOURCE_SYS_BRAND = 3L;
/**
* 定义信息录入状态
* 1:已校验过数据。2:数据未校验
*/
public static final Long DECLARE_CHECK = 1L;
public static final Long DECLARE_SAVE = 2L;
/**
* 定义邮件发送状态
* (0:未发送。1:发送成功。2:发送失败)
*/
public static final Long MAIL_SEND_UNSENT = 0L;
public static final Long MAIL_SEND_SUCC = 1L;
public static final Long MAIL_SEND_FAIL = 2L;
public static final Long USER_SOURCE_TW = 1L;
public static final Long USER_SOURCE_FCL = 2L;
/**
* 定义用户操作类型常量
* 1:登录 2:退出 3:修改密码4:FCL登录注册。5:停用,6:启用
*/
public static final Long USER_OPER_LOGIN = 1L;
public static final Long USER_OPER_LOGOUT = 2L;
public static final Long USER_OPER_UPD_PWD = 3L;
public static final Long USER_OPER_FCL_REGISTER = 4L;
public static final Long USER_OPER_STOP = 5L;
public static final Long USER_OPER_INIT = 6L;
/**
* 定义申报信息文件生成选择常量
* 1: 立即制作 2:使用已制作
*/
public static final Long FILE_SELECT_MAKE = 1L;
public static final Long FILE_SELECT_EXISTS = 2L;
/**
* 菜单类型
* M:主菜单 C:分支菜单 B:按钮
*/
public static final String SYS_MENU_TYPE_MAIN = "M";
public static final String SYS_MENU_TYPE_BRANCH = "C";
public static final String SYS_MENU_TYPE_BUTTON = "B";
/**
* 用户类型
* 在线申报平台账号
*/
public static final String DICT_USER_GOOUP_CODE = "user_type";
public static final String DICT_USER_DEFAULT_CODE = "default";
public static final String DICT_USER_FEDEX_CODE = "fedex";
/**
* 角色类型
* admin
*/
public static final String DICT_ROLE_GOOUP_CODE = "role_type";
public static final String DICT_ROLE_DEFAULT_CODE = "admin";
/**
* 报关类别
*/
public static final String DICT_CUSTOMS_DECLARATION_TYPE_CODE = "customs_declaration_type";
/**
* 报关类别 -> 其它
*/
public static final String DICT_CUSTOMS_DECLARATION_TYPE_CODE_OTHER = "OTHER";
/**
* 出口统计方式
*/
public static final String DICT_EXPORT_STATISTICS_METHOD_CODE = "export_statistics_method";
/**
* 币种
*/
public static final String DICT_CURRENCY_CD_CODE = "currency_cd";
/**
* 商标
*/
public static final String DICT_BRAND_CODE = "brand";
/**
* 产证
*/
public static final String DICT_PROPERTY_CERTIFICATE_CODE = "property_certificate";
/**
* ECFA产证
*/
public static final String DICT_ECFA_PROPERTY_CERTIFICATE_CODE = "ecfa_property_certificate";
/**
* 申请
*/
public static final String DICT_APPLY_FOR_CODE = "apply_for";
/**
* 提单状态
*/
public static final String DICT_DELIVERY_STATUS_CODE = "delivery_status";
/**
* 操作状态
*/
public static final String DICT_OPER_STATUS_CODE = "oper_status";
/**
* 提单状态
*/
public static final String DICT_FILE_SOURCE_CODE = "file_source";
/**
* 提单状态
*/
public static final String DICT_LOGIN_TYPE_CODE = "login_type";
/**
* 邮件发送状态
*/
public static final String DICT_MAIL_SEND_STATUS_CODE = "mail_send_status";
/**
* 任务默认节点
*/
public static final Long TASK_DEFAULT_NODE = 1L;
/**
* 任务默认执行类型
*/
public static final Long TASK_EXEC_TYPE = 1L;
/**
* 任务类型。
* 1:执行程序操作(增删改查)数据。
* 2:邮件发送。
* 3:读取消息系统数据(MQ、Kafka、redis等)
* 4:写入消息系统数据(MQ、Kafka、redis等)
* 5:请求外部系统获取数据。
* 6:推送数据到外部系统。
*/
public static final Long TASK_TYPE_EXEC = 1L;
public static final Long TASK_TYPE_MAIL = 2L;
public static final Long TASK_TYPE_READ_MQ = 3L;
public static final Long TASK_TYPE_WRITE_MQ = 4L;
public static final Long TASK_TYPE_READ_SERVER = 5L;
public static final Long TASK_TYPE_WRITE_SERVER = 6L;
/**
* 任务状态
* 0:待执行(初始状态)。
* 1:执行成功。
* 2:执行中待获取结果。
* 3:执行失败
*/
public static final Long TASK_STATUS_INIT = 0L;
public static final Long TASK_STATUS_SUCC = 1L;
public static final Long TASK_STATUS_IN_EXEC = 2L;
public static final Long TASK_STATUS_FAIL = 3L;
/**
* 申报信息在任务管理中的分组CODE
*/
public static final String TASK_GROUP_CODE_DECLARE = "DECLARE_INFO";
/**
* 重置密码在邮件日志里面的分组
*/
public static final String MAIL_GROUP_CODE_RESETPWD = "RESULT_PASSWORD";
public static final String FCL_PREFIX = "FCL";
/**
* 有无商标
* 1:无商标
*/
public static final Long BRAND_NO = 1L;
/**
* 是否为电子冲退税报单
* 0:否
* 1:是
*/
public static final Long TAX_FLAG_NO = 0L;
public static final Long TAX_FLAG_YES = 1L;
/**
* 定义保存操作步骤
* 1:申报信息 2:核检信息 3:文件上传
*/
public static final Long DEC_SAVE_INFO = 1L;
public static final Long DEC_SAVE_CHECK_INFO = 2L;
public static final Long DEC_SAVE_FILE = 3L;
/**
* 报关类别
*/
public static final String DT_G5 = "G5";
public static final String DT_G3 = "G3";
public static final String DT_B9 = "B9";
public static final String DT_B8 = "B8";
public static final String DT_D5 = "D5";
public static final String DT_F5 = "F5";
/**
* 出口统计方式
*/
public static final String ESM_02 = "02";
public static final String ESM_81 = "81";
public static final String ESM_04 = "04";
public static final String ESM_82 = "82";
public static final String ESM_9E = "9E"; //del
public static final String ESM_9L = "9L";
public static final String ESM_91 = "91";
public static final String ESM_9S = "9S";
public static final String ESM_94 = "94";
public static final String ESM_92 = "92";
public static final String ESM_9M = "9M";
public static final String ESM_96 = "96";
public static final String ESM_53 = "53";
public static final String ESM_OTHER = "OTHER";
/**
* 产证
*/
public static final String PC_NO = "pc_no";
public static final String PC_YES = "pc_yes";
public static final String PC_RANDOM = "pc_random";
public static final String PC_NI_RANDOM = "pc_niRandom";
/**
* ECFA产证
*/
public static final String ECFA_NO = "ecfa_no";
public static final String ECFA_YES = "ecfa_yes";
public static final String ECFA_APPLY = "ecfa_apply";
/**
* 申请
*/
public static final String AF_CT = "ct";
public static final String AF_TN = "tn";
public static final String AF_CK = "ck";
/**
* 提单失败类型
* 1:超时失败(提单状态=4,超时情况。提示联系清关部门)
* 2:三次发送邮件失败(提单状态=4,三次重发邮件失败。显示操作:重发)
* 3:读取回执为失败(提单状态=4,读取失败,重试次数耗尽。浮框显示FAILED_MSG失败原因。)
* 4:其他情况失败(3次匹配。其他情况等。显示:联系清关部门)
*/
public static final Long RECEIPT_FAIL_TYPE_TIMEOUT = 1L;
public static final Long RECEIPT_FAIL_TYPE_RESEND = 2L;
public static final Long RECEIPT_FAIL_TYPE_RECEIPT = 3L;
public static final Long RECEIPT_FAIL_TYPE_OTHER = 4L;
/**
* 获取系统配置参数中邮件人员信息配置
*/
public static final String SEND_MAIL_GROUP_DECLARE = "DECLARE_SEND_MAIL";
public static final String SEND_MAIL_GROUP_RESETPWD = "RESETPWD_SEND_MAIL";
public static final String MAIL_FROM = "FROM";
public static final String MAIL_PWD = "PWD";
public static final String MAIL_TO = "TO";
public static final String MAIL_CC = "CC";
/**
* VIP清关组
*/
public static final Long VIP_CC_TYPE = 1L;
public static final Long VIP_CC_LIST_TYPE_WHITE = 1L;
public static final Long VIP_CC_LIST_TYPE_BLACK = 2L;
public static final String VIP_CC_ADD_CC_MAIL = "ADD_CC_MAIL";
}
package com.fedex.connect.common.dependencies.contants;
/**
* Redis使用常量。鉴权和redis都使用
*/
public class RedisConstants {
public static final String REDIS_KEY_TOKEN = "tw_user:token:";
public static final int REDIS_EXPIRE_TIME_2H = 7200;
public static final int REDIS_EXPIRE_TIME_8H = 28800;
public static final int REDIS_EXPRIE_TIME_1D = 86400;
public static final int REDIS_EXPRIE_TIME_1W = 604800;
}
package com.fedex.connect.common.dependencies.enums;
/**
* @author erry
*/
public enum ResponseCode {
/**
* 200=操作成功
* 201=操作失败
* 202=API接口请求异常
* 203=后台程序发生异常
* 204=请求方式错误
* 205=api接口请求错误
* 206=api接口请求结果为空
* 207=系统异常!
*
* 301=登录身份异常
* 302=登录已过期
* 303=用户不存在
* 304=用户已禁用,不能登录!
* 305=登录token过期,请重新登录!
* 306=该角色下有用户存在,是否确认删除?
*
* 601=数据被占用
* 602=记录已存在,请勿重复添加
* 603=导出数据量过大,请不要超过10W条
*
* 604=请求参数为空
* 605=ID为空
* 606=数据不存在
* 607=请求参数值不合理
*/
SUCCESS_CODE(200,"enum_res_code_200"),
FAIL_CODE(201,"enum_res_code_201"),
API_EXCEPTION(202, "enum_res_code_202"),
PROGRAM_ERROR(203,"enum_res_code_203"),
METHOD_EXCEPTION_CODE(204, "enum_res_code_204"),
HTTP_CLIENT_ERROR(205, "enum_res_code_205"),
HTTP_CLIENT_EMPTY(206, "enum_res_code_206"),
SYSTEM_EXECEPTION_CODE(207,"enum_res_code_207"),
TOKEN_FORMAT_ERROR(301, "enum_res_code_301"),
TOKEN_EXPIRE(302, "enum_res_code_302"),
USER_IS_NULL(303, "enum_res_code_303"),
USER_DISABLED(304, "enum_res_code_304"),
OVERDUE_TOKEN_CODE(305,"enum_res_code_305"),
ROLE_CONFIRM_DEL(306, "enum_res_code_306"),
INSERT_EXCEPITON(601,"enum_res_code_601"),
RECORD_EXIST(602, "enum_res_code_602"),
EXPORT_TOO_LARGE(603, "enum_res_code_603"),
REQUEST_PARAM_NULL(604, "enum_res_code_604"),
REQUEST_ID_NULL(605, "enum_res_code_605"),
REQUEST_OBJECT_NULL(606, "enum_res_code_606"),
REQUEST_PARAM_UNREASONABLE(606, "enum_res_code_607");
private Integer code;
private String msg;
ResponseCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
package com.fedex.connect.common.dependencies.i18n;
import org.springframework.context.MessageSourceResolvable;
import java.io.Serializable;
/**
* @author EDY
*/
public class DefaultMessageSourceResolvable implements MessageSourceResolvable, Serializable {
private final String[] codes;
private final Object[] arguments;
private final String defaultMessage;
/**
* 创建一个新的DefaultMessageSourceResolvable.
* @param code 用来解析消息的码
*/
public DefaultMessageSourceResolvable(String code) {
this(new String[] {code}, null, null);
}
/**
* 创建一个新的DefaultMessageSourceResolvable.
* @param codes 用来解析消息的码
*/
public DefaultMessageSourceResolvable(String[] codes) {
this(codes, null, null);
}
/**
* 创建一个新的DefaultMessageSourceResolvable.
* @param codes 用来解析消息的码
* @param defaultMessage 用来解析消息的默认消息
*/
public DefaultMessageSourceResolvable(String[] codes, String defaultMessage) {
this(codes, null, defaultMessage);
}
/**
* 创建一个新的DefaultMessageSourceResolvable.
* @param codes 用来解析消息的码
* @param arguments 用来解析消息的参数数组
*/
public DefaultMessageSourceResolvable(String[] codes, Object[] arguments) {
this(codes, arguments, null);
}
/**
* 创建一个新的DefaultMessageSourceResolvable.
* @param codes 用来解析消息的码
* @param arguments 用来解析消息的参数数组
* @param defaultMessage 用来解析消息的默认消息
*/
public DefaultMessageSourceResolvable(
String[] codes,Object[] arguments, String defaultMessage) {
this.codes = codes;
this.arguments = arguments;
this.defaultMessage = defaultMessage;
}
/**
* Copy constructor: Create a new instance from another resolvable.
* @param resolvable the resolvable to copy from
*/
public DefaultMessageSourceResolvable(MessageSourceResolvable resolvable) {
this(resolvable.getCodes(), resolvable.getArguments(), resolvable.getDefaultMessage());
}
/**
* Return the default code of this resolvable, that is,
* the last one in the codes array.
*/
public String getCode() {
return (this.codes != null && this.codes.length > 0 ? this.codes[this.codes.length - 1] : null);
}
@Override
public String[] getCodes() {
return this.codes;
}
@Override
public Object[] getArguments() {
return this.arguments;
}
@Override
public String getDefaultMessage() {
return this.defaultMessage;
}
/**
* 表示指定默认的消息是否需要获取,来替换占位符and/or MessageFormat
* return true:如果默认的消息可能包含参数占位符
* return false:如果它明确没有包含占位符或者自定义逃逸并且当前可以被简单暴露
* @see #getDefaultMessage()
* @see #getArguments()
*/
public boolean shouldRenderDefaultMessage() {
return true;
}
}
package com.fedex.connect.common.dependencies.i18n;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class I18nConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
return new MessageLocaleResolver();
}
}
package com.fedex.connect.common.dependencies.i18n;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 根据语言编码查询内容
*/
@Component
public class LocaleMessageUtil {
@Resource
private MessageSource messageSource;
public LocaleMessageUtil() {
}
public String getMessage(String code) {
return this.getConnectorMessage(code, null);
}
public String getMessage(String code,String defaultMessage) {
return this.getConnectorMessage(code, null, defaultMessage);
}
public String getMessage(String code, Object[] args) {
return this.getConnectorMessage(code, args);
}
public String getMessage(String code, Object[] args,String defaultMessage) {
return this.getConnectorMessage(code, args,defaultMessage);
}
/**
* 解析code对应的信息进行返回,如果对应的code不能被解析则抛出异常NoSuchMessageException
* @param code 需要进行解析的code,对应资源文件中的一个属性名
* @param args 需要用来替换code对应的信息中包含参数的内容,如:{0},{1,date},{2,time}
* @return
*/
private String getConnectorMessage(String code, Object[] args){
return this.messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
/**
* 解析code对应的信息进行返回,如果对应的code不能被解析则返回默认信息defaultMessage。
* @param code 需要进行解析的code,对应资源文件中的一个属性名
* @param args 需要用来替换code对应的信息中包含参数的内容,如:{0},{1,date},{2,time}
* @param defaultMessage 当对应code对应的信息不存在时需要返回的默认值
* @return
*/
private String getConnectorMessage(String code, Object[] args, String defaultMessage){
return this.messageSource.getMessage(code, args, defaultMessage, LocaleContextHolder.getLocale());
}
/**
* 根据封装对象,获取
* @param resolvable 封装对象
* @return
*/
private String getConnectorMessage(MessageSourceResolvable resolvable){
return this.messageSource.getMessage(resolvable, LocaleContextHolder.getLocale());
}
}
package com.fedex.connect.common.dependencies.i18n;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* 根据请求头中携带的请求语言内容,生成会话,解析内容
* @author EDY
*/
public class MessageLocaleResolver implements LocaleResolver {
@Value("${export.language}")
private String exportTwLanguage;
/*private static final String I18N_LANGUAGE = "i18n_language";
private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";*/
private Logger logger = LoggerFactory.getLogger(MessageLocaleResolver.class);
@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale locale;
// String language = request.getParameter("I18N_LANGUAGE");
if (StringUtils.isNotEmpty(exportTwLanguage)) {
//获取知道配置文件中的语言为: exportTwLanguage;
locale = new Locale(exportTwLanguage);
/*//将国际化语言保存到session
HttpSession session = req.getSession();
session.setAttribute(I18N_LANGUAGE_SESSION, locale);*/
} else {
//如果没有带国际化参数,则判断session有没有保存,有保存,则使用保存的,也就是之前设置的,避免之后的请求不带国际化参数造成语言显示不对
/*HttpSession session = req.getSession();
Locale localeInSession = (Locale) session.getAttribute(I18N_LANGUAGE_SESSION);*/
//读取不到指定语言文件,采用默认中文。即默认的message.properties
locale = Locale.getDefault();
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
package com.fedex.connect.common.dependencies.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
/**
* 类型转换
*/
public class BytesUtils {
/**
* 获取字符串UTF-8的字节数
* @param str
* @return
*/
public static int getStrUTF8ByteLength(String str){
if (StringUtils.isBlank(str)){
return 0;
}
return str.getBytes(StandardCharsets.UTF_8).length;
}
/**
* 字符串转换成十六进制字符串
*/
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString();
}
/**
* 十六进制字符串转换为 byte[]
*
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* char to byte
*
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 数组转换成十六进制字符串
*
* @param bArray byte[]
* @return HexString
*/
public static final String bytesToHexString(byte[] bArray) {
if (bArray == null || bArray.length == 0) {
return null;
}
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 十六进制字符串转换成字符串
*
* @param hexStr
* @return String
*/
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
/**
* @param hexString String str = "000AB"
* @return
*/
public static int hexString2Int(String hexString) {
Integer num = Integer.valueOf(hexString, 16);
return num;
}
/**
* 把byte转为字符串的bit
*/
public static String byteToBitString(byte b) {
return ""
+ (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
+ (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
+ (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
+ (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
}
/**
* 把byte转为字符串数组的bit
*/
public static String[] byteToBitStrings(byte b) {
String[] bit = new String[8];
bit[0] = "" + (byte) ((b >> 7) & 0x1);
bit[1] = "" + (byte) ((b >> 6) & 0x1);
bit[2] = "" + (byte) ((b >> 5) & 0x1);
bit[3] = "" + (byte) ((b >> 4) & 0x1);
bit[4] = "" + (byte) ((b >> 3) & 0x1);
bit[5] = "" + (byte) ((b >> 2) & 0x1);
bit[6] = "" + (byte) ((b >> 1) & 0x1);
bit[7] = "" + (byte) ((b >> 0) & 0x1);
return bit;
}
//base64字符串转byte[]
public static byte[] base64String2ByteFun(String base64Str) {
return Base64.decodeBase64(base64Str);
}
//byte[]转base64
public static String byte2Base64StringFun(byte[] b) {
return Base64.encodeBase64String(b);
}
public static void main(String[] args) {
String hexString = "3A60432A5C01211F291E0F4E0C132825";
byte[] result = hexStringToBytes(hexString);
System.out.println(new String(result));
System.out.println(bytesToHexString(result));
}
}
package com.fedex.connect.common.dependencies.util;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GsonUtils {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public static String toJsonString(Object object) {
return object == null ? null : gson.toJson(object);
}
/**
* 转成json
*/
public static String beanToString(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
}
/**
* 转成bean
*/
public static <T> T stringToBean(String gsonString, Class<T> cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* 转成list
*/
public static <T> List<T> stringToList(String gsonString, Class<T> cls) {
List<T> list = new ArrayList<>();
if (gson != null) {
JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
for (final JsonElement elem : array) {
list.add(gson.fromJson(elem, cls));
}
}
return list;
}
/**
* 转成list, 有可能造成类型擦除
*/
public static <T> ArrayList<T> stringToList(String gsonString) {
ArrayList<T> list = null;
if (gson != null) {
list = gson.fromJson(gsonString, new TypeToken<ArrayList<T>>() {
}.getType());
}
return list;
}
/**
* 转成map的
*/
public static <T> Map<String, T> stringToMaps(String gsonString, Class<T> cls) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
}
package com.fedex.connect.common.dependencies.util;
import com.fedex.connect.common.dependencies.authentication.SecurityConstants;
import com.fedex.connect.common.dependencies.contants.RedisConstants;
import com.fedex.export.data.dto.SecurityUserDetails;
import com.fedex.export.repository.dao.SysUserMapperExt;
import com.fedex.export.repository.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Administrator
*/
public class JwtTokenUtils {
private static final SysUserMapperExt sysUserMapper = com.fedex.export.common.util.SpringBeanUtil.getBean(SysUserMapperExt.class);
/**
* 生成足够的安全随机密钥,以适合符合规范的签名
*/
private static final byte[] API_KEY_SECRET_BYTES = DatatypeConverter.parseBase64Binary(SecurityConstants.getSecuritykey());
private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(API_KEY_SECRET_BYTES);
public static String createAccessToken(String username, String id, List<String> roles, boolean isRememberMe) {
long expiration = isRememberMe ? SecurityConstants.getExpire_1D() : RedisConstants.REDIS_EXPIRE_TIME_8H;
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
String tokenPrefix = Jwts.builder()
.setHeaderParam("type", SecurityConstants.TOKEN_TYPE)
.signWith(SECRET_KEY, SignatureAlgorithm.HS256)
.claim(SecurityConstants.ROLE_CLAIMS, String.join(",", roles))
.setId(id)
.setIssuer("EXPORT_TW") //证书发行者
.setIssuedAt(createdDate)
.setSubject(username)
.setExpiration(expirationDate)
.compact();
return SecurityConstants.TOKEN_PREFIX + tokenPrefix;
}
public static String createReflushToken(String username, String id, List<String> roles) {
//默认保留1小时
long expiration = 3600L;
Date createdDate = new Date();
Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
String tokenPrefix = Jwts.builder()
.setHeaderParam("type", SecurityConstants.TOKEN_TYPE)
.signWith(SECRET_KEY, SignatureAlgorithm.HS256)
.claim(SecurityConstants.ROLE_CLAIMS, String.join(",", roles))
.setId(id)
.setIssuer("EXPORT_TW")
.setIssuedAt(createdDate)
.setSubject(username)
.setExpiration(expirationDate)
.compact();
return SecurityConstants.TOKEN_PREFIX + tokenPrefix;
}
/**
* 从token中获取用户id
* @param token
* @return
*/
public static String getId(String token) {
Claims claims = getClaims(token);
return claims.getId();
}
/**
* 从token中获取用户id
* @param token
* @return
*/
public static String getUserName(String token) {
Claims claims = getClaims(token);
return claims.getSubject();
}
/**
* 获取token的过期时间
* @param token
* @return
*/
public static Date getAccessTokenExpiredTime(String token){
Claims claims = getClaims(token);
return claims.getExpiration();
}
/**
* 从token中获取权限
* @param token
* @return
*/
public static UsernamePasswordAuthenticationToken getAuthentication(String token) {
Claims claims = getClaims(token);
List<SimpleGrantedAuthority> authorities = getAuthorities(claims);
String userName = claims.getSubject();
String id = claims.getId();
SecurityUserDetails userDetails = new SecurityUserDetails();
userDetails.setId(Long.parseLong(id));
userDetails.setUsername(userName);
SysUser user = sysUserMapper.findOne(Long.parseLong(id));
userDetails.setUser(user);
return new UsernamePasswordAuthenticationToken(userDetails, token, authorities);
}
private static List<SimpleGrantedAuthority> getAuthorities(Claims claims) {
String role = (String) claims.get(SecurityConstants.ROLE_CLAIMS);
if (!"".equals(role)) {
return Arrays.stream(role.split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}else {
return new ArrayList<>();
}
}
private static Claims getClaims(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
public static List<String> getRoleList(String token){
Claims claims = getClaims(token);
String roleStr = (String) claims.get(SecurityConstants.ROLE_CLAIMS);
return Arrays.asList(roleStr.split(","));
}
}
......@@ -51,6 +51,12 @@
<version>12.2.0.1</version>
<scope>${install.scope}</scope>
</dependency>
<dependency>
<groupId>com.fedex.connect</groupId>
<artifactId>common-dependencies</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
......
package com.fedex.connect.manager.common.enums;
import java.util.ArrayList;
import java.util.List;
/**
* FCL登录Session信息
*/
public enum FCLSessionInfoEnum {
FDX_LOGIN("fdx_login","FCL登录SESSION信息"),
FCL_UUID("fcl_uuid","FCL-UUID信息"),
FCL_CONTACTNAME("fcl_contactname","FCL联系人信息");
FCLSessionInfoEnum(String code, String name){
this.code = code;
this.name = name;
}
private String code;
private String name;
public String getCode() {
return code;
}
public String getName() {
return name;
}
public static List<String> getCodeList() {
List<String> codeList = new ArrayList<>();
for(FCLSessionInfoEnum fclSessionInfoEnum : FCLSessionInfoEnum.values()){
codeList.add(fclSessionInfoEnum.getCode());
}
return codeList;
}
}
package com.fedex.connect.manager.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
public class PropertiesConfig {
@Value("${fcl.login.url}")
private String fclLoginUrl;
@Value("${fcl.twidx.url}")
private String twIdxUrl;
@Value("${fcl.login.redjrectLogin}")
private String redjrectLogin;
}
package com.fedex.connect.manager.controller;
import com.fedex.connect.common.dependencies.i18n.LocaleMessageUtil;
import com.fedex.connect.manager.config.PropertiesConfig;
import com.fedex.connect.manager.controller.log.ILogLoginService;
import com.fedex.connect.manager.data.vo.JsonResult;
import com.fedex.connect.manager.service.system.ISysAuthService;
import com.fedex.connect.manager.service.system.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import javax.annotation.Resource;
import java.net.URI;
import java.util.Objects;
/**
* @author EDY
*/
public class AbstractEtController {
@Resource
protected LocaleMessageUtil localeMessageUtil;
@Autowired
protected PropertiesConfig propertiesConfig;
@Autowired
protected ISysUserService sysUserService;
@Autowired
protected ISysAuthService sysAuthService;
@Autowired
protected ILogLoginService logLoginService;
public <T> ResponseEntity<T> seeOther(String url) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(URI.create(url));
return result(HttpStatus.SEE_OTHER, httpHeaders);
}
public <T> ResponseEntity<T> temporaryRedirect(String url) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(URI.create(url));
return result(HttpStatus.TEMPORARY_REDIRECT, httpHeaders);
}
public <T> ResponseEntity<T> permanentRedirect(String url) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(URI.create(url));
return result(HttpStatus.PERMANENT_REDIRECT, httpHeaders);
}
public <T> ResponseEntity<T> result(HttpStatus status, T data) {
return new ResponseEntity<>(data, status);
}
public <T> ResponseEntity<T> result(HttpStatus status, HttpHeaders headers) {
return new ResponseEntity<>(headers, status);
}
public <T> ResponseEntity<T> ok(T data) {
return new ResponseEntity<>(data, HttpStatus.OK);
}
public <T> ResponseEntity<T> ok(MultiValueMap<String, String> headers, T data) {
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
public <T> ResponseEntity<T> error(HttpStatus code) {
return new ResponseEntity<>(code);
}
public <T> ResponseEntity<T> error(HttpStatus code, MultiValueMap<String, String> headers) {
return new ResponseEntity<>(headers, code);
}
/**
* 通过自定义的错误码,转换为对应的HttpStatus
* @param response
* @return
*/
public HttpStatus errorMappingStatus(JsonResult response) {
if (Objects.isNull(response)) {
return HttpStatus.BAD_REQUEST; //400
}
return HttpStatus.BAD_REQUEST; //400
}
/**
* 判定是否返回成功
* @param responseEntity
* @param <T>
* @return
*/
public <T> boolean isSuccess(ResponseEntity<JsonResult<T>> responseEntity) {
return responseEntity != null && responseEntity.getBody() != null && responseEntity.getBody().isSuccess();
}
/**
* 判定是否返回成功
* @param response
* @param <T>
* @return
*/
public <T> boolean isSuccess(JsonResult<T> response) {
return response != null && response.isSuccess();
}
}
package com.fedex.connect.manager.controller.log;
import com.fedex.connect.manager.data.dto.LogLoginDto;
public interface ILogLoginService {
int saveLoginLog(LogLoginDto dto);
}
package com.fedex.connect.manager.controller.log.impl;
import com.fedex.connect.manager.controller.log.ILogLoginService;
import com.fedex.connect.manager.data.dto.LogLoginDto;
import com.fedex.connect.manager.data.model.LogShowModel;
import com.fedex.connect.manager.service.AbstractEtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 日志相关service
* @author EDY
*/
@Service
public class LogLoginServiceImpl extends AbstractEtService implements ILogLoginService {
private Logger logger = LoggerFactory.getLogger(LogLoginServiceImpl.class);
/**
* 保存登录日志
* @param dto
* @return
*/
@Transactional(rollbackFor = Exception.class)
public int saveLoginLog(LogLoginDto dto){
try{
return userLoginLogRepository.insert(LogLoginDto.dtoToDao(dto));
} catch (Exception e){
logger.error(LogShowModel.showException("Exception",e));
throw e;
}
}
}
package com.fedex.connect.manager.controller.system;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface ISysAuthController {
void wlgnLogin(HttpServletRequest request, HttpServletResponse res);
void wlgnForward(HttpServletRequest request, HttpServletResponse res);
}
package com.fedex.connect.manager.controller.system.impl;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.dependencies.util.GsonUtils;
import com.fedex.connect.common.dependencies.util.StringExtUtil;
import com.fedex.connect.common.dependencies.util.Utils;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.manager.common.enums.FCLSessionInfoEnum;
import com.fedex.connect.manager.controller.AbstractEtController;
import com.fedex.connect.manager.controller.system.ISysAuthController;
import com.fedex.connect.manager.data.dto.LogLoginDto;
import com.fedex.connect.manager.data.dto.LoginRequest;
import com.fedex.connect.manager.data.dto.SysUserDto;
import com.fedex.connect.manager.data.vo.JsonResult;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
@RestController
@RequestMapping(value = "/auth", name = "权鉴操作相关请求")
@Api(value="SysAuthController",tags={"用户相关请求(无需token)"})
public class SysAuthControllerImpl extends AbstractEtController implements ISysAuthController {
private static final Logger logger = LoggerFactory.getLogger(SysAuthControllerImpl.class);
@Value("${fcl.interface.logurl}")
private String fclIndexLoginUrl;
@PostMapping("/init")
@ApiOperation(value = "初始化进入首页获取FCL登录地址")
public JsonResult init(){
return JsonResult.succ(fclIndexLoginUrl);
}
@RequestMapping(value = "/wlgnForward")
@ApiOperation(value = "FCL中转Cookie地址")
public void wlgnForward(HttpServletRequest request, HttpServletResponse res){
printRequestInfo(request);
try {
boolean equals = true;
if (!equals){
return;
}
Cookie[] cookies = request.getCookies();
if (Utils.isEmpty(cookies)){
return;
}
List<String> saveKeyList = FCLSessionInfoEnum.getCodeList();
List<String> cookiesList = new ArrayList();
for (int i = 0, max = cookies.length; i < max; i++) {
Cookie cookie = cookies[i];
if(saveKeyList.contains(cookie.getName())){
cookiesList.add("'"+cookie.getName()+"':'"+cookie.getValue()+"'");
if(cookiesList.size() == saveKeyList.size()){
break;
}
}
}
if (cookiesList.size() > 0 && cookiesList.size() == saveKeyList.size()){
JsonObject jsonObject = GsonUtils.stringToBean("{"+String.join(",",cookiesList)+"}",JsonObject.class);
//set cookie by fcl_key
JsonResult tokenResult = sysAuthService.createFclToken(jsonObject);
if (tokenResult.isSuccess()){
String fcl_token_key = String.valueOf(tokenResult.getData());
String redirectUrl = String.format("%s?token=%s", propertiesConfig.getFclLoginUrl(), fcl_token_key);
res.sendRedirect(redirectUrl);
}
}else {
res.sendRedirect(propertiesConfig.getTwIdxUrl());
}
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
@GetMapping(value = "/wlgnLogin")
@ApiOperation(value = "FCL登录")
public void wlgnLogin(HttpServletRequest request, HttpServletResponse res) {
logger.info("wlgnLogin____________________start");
String fcl_token_key = request.getParameter("token");
if (StringUtils.isBlank(fcl_token_key)){
return;
}
JsonObject jsonObject = sysAuthService.getFclToken(fcl_token_key);
String fcl_uuid = jsonObject.get(FCLSessionInfoEnum.FCL_UUID.getCode()).getAsString();
String fcl_contactname = jsonObject.get(FCLSessionInfoEnum.FCL_CONTACTNAME.getCode()).getAsString().replaceAll("\"","");
User loginUser = sysUserService.findUserByFcl(fcl_uuid);
if (loginUser == null){
//如果用户不存在,则创建FCL用户信息
SysUserDto dto = new SysUserDto(fcl_uuid, fcl_contactname);
loginUser = sysUserService.save(dto);
} else {
//首先对用户中的姓名进行解密
if (StringUtils.isNotBlank(loginUser.getUserName())){
String decode_userName = loginUser.getUserName();
if (StringUtils.isNotBlank(decode_userName)){
loginUser.setUserName(decode_userName);
}
}
//如果名称和原来不一样,则更新
if(StringUtils.isNotBlank(fcl_contactname) && !fcl_contactname.equals(loginUser.getUserName())){
String encode_fcl_contactname = StringUtils.trimToEmpty(fcl_contactname);
if (StringUtils.isNotBlank(encode_fcl_contactname)){
loginUser.setUserName(encode_fcl_contactname);
} else {
loginUser.setUserName(StringUtils.trimToEmpty(fcl_contactname));
}
loginUser.setUpdateTime(new Date());
sysUserService.update(loginUser);
}
}
//创建token
LoginRequest loginRequest = new LoginRequest();
loginRequest.setRememberMe(true);
JsonResult tokenResult = sysAuthService.createAccessToken(loginRequest, loginUser);
//记录日志
LogLoginDto dto = new LogLoginDto(loginUser.getId(), DatabaseConstants.USER_OPER_FCL_REGISTER,
localeMessageUtil.getMessage("auth_login_desc"));
logLoginService.saveLoginLog(dto);
try{
if (tokenResult.isSuccess()){
String redirectUrl = String.format("%s?token=%s&uid=%s", propertiesConfig.getRedjrectLogin(), tokenResult.getData(), loginUser.getId());
res.sendRedirect(redirectUrl);
logger.info("wlgnLogin____________________finish");
}else {
res.sendRedirect(propertiesConfig.getTwIdxUrl());
}
} catch (IOException e) {
logger.error("FCL客户登录初始化 | 发生异常 | 异常如下:",e);
throw new RuntimeException(e);
}
}
private void printRequestInfo(HttpServletRequest request) {
logger.info("wlgnForward____________________headerNames");
Enumeration<String> headerNames = request.getHeaderNames();
if(Objects.nonNull(headerNames)) {
while (headerNames.hasMoreElements()) {
String s = headerNames.nextElement();
String header = request.getHeader(s);
logger.info(s + ":" + header);
}
}
logger.info("wlgnForward____________________parameterNames");
Enumeration<String> parameterNames = request.getParameterNames();
if(Objects.nonNull(parameterNames)){
while(parameterNames.hasMoreElements()){
String s = parameterNames.nextElement();
String parameter = request.getHeader(s);
logger.info(s+":"+parameter);
}
}
logger.info("wlgnForward____________________parameterMap");
Map<String, String[]> parameterMap = request.getParameterMap();
if(Objects.nonNull(parameterMap)) {
Set<String> strings = parameterMap.keySet();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
String[] strings1 = parameterMap.get(next);
logger.info(next + ":" + StringExtUtil.convertArrayToString(strings1, ","));
}
}
logger.info("wlgnForward____________________cookies");
Cookie[] cookies = request.getCookies();
if(Objects.nonNull(cookies)) {
for (int i = 0, max = cookies.length; i < max; i++) {
Cookie cookie = cookies[i];
logger.info(cookie.getName() + ":" + cookie.getValue());
}
}
logger.info("wlgnForward____________________Session");
HttpSession session = request.getSession();
Enumeration<String> attributeNames = session.getAttributeNames();
while(attributeNames.hasMoreElements()){
String s = attributeNames.nextElement();
String parameter = (String)request.getAttribute(s);
logger.info(s+":"+parameter);
}
}
}
package com.fedex.connect.manager.dao.base;
import com.fedex.connect.common.dao.base.DictionaryEntriesMapper;
import com.fedex.connect.common.dao.log.UserLoginInfoMapper;
import com.fedex.connect.common.dao.sys.RedisSlabMapper;
import com.fedex.connect.common.dao.sys.RoleMapper;
import com.fedex.connect.common.dao.sys.UserMapper;
import com.fedex.connect.common.dao.sys.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseDao {
@Autowired
public UserLoginInfoMapper userLoginInfoMapper;
@Autowired
public RedisSlabMapper redisSlabMapper;
@Autowired
public RoleMapper roleMapper;
@Autowired
public UserRoleMapper userRoleMapper;
@Autowired
public UserMapper userMapper;
@Autowired
public DictionaryEntriesMapper dictionaryEntriesMapper;
}
package com.fedex.connect.manager.dao.repository.log;
import com.fedex.connect.common.model.log.UserLoginInfo;
public interface IUserLoginLogRepository {
int insert(UserLoginInfo userLoginInfo);
}
package com.fedex.connect.manager.dao.repository.log.impl;
import com.fedex.connect.common.model.log.UserLoginInfo;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.log.IUserLoginLogRepository;
import org.springframework.stereotype.Repository;
@Repository
public class UserLoginLogRepositoryImpl extends BaseDao implements IUserLoginLogRepository {
@Override
public int insert(UserLoginInfo userLoginInfo) {
return userLoginInfoMapper.insert(userLoginInfo);
}
}
package com.fedex.connect.manager.dao.repository.sys;
import com.fedex.connect.common.model.base.DictionaryEntries;
import com.fedex.connect.common.model.base.DictionaryEntriesExample;
import java.util.List;
public interface IDictionaryEntriesRepository {
List<DictionaryEntries> selectByExample(DictionaryEntriesExample example);
}
package com.fedex.connect.manager.dao.repository.sys;
import com.fedex.connect.common.model.sys.RedisSlab;
import com.fedex.connect.common.model.sys.RedisSlabExample;
import java.util.List;
public interface IRedisSlabRepository {
int insert(RedisSlab record);
List<RedisSlab> selectByExample(RedisSlabExample example);
int deleteByPrimaryKey(Long id);
}
package com.fedex.connect.manager.dao.repository.sys;
import com.fedex.connect.common.model.sys.Role;
import com.fedex.connect.common.model.sys.RoleExample;
import java.util.List;
public interface IRoleRepository {
List<Role> selectByExample(RoleExample example);
Role selectByPrimaryKey(Long id);
int insert(Role record);
}
package com.fedex.connect.manager.dao.repository.sys;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.common.model.sys.UserExample;
import java.util.List;
public interface IUserRepository {
List<User> selectByExample(UserExample example);
int insert(User record);
int updateByPrimaryKeySelective(User record);
}
package com.fedex.connect.manager.dao.repository.sys;
import com.fedex.connect.common.model.sys.UserRole;
import com.fedex.connect.common.model.sys.UserRoleExample;
import java.util.List;
public interface IUserRoleRepository {
List<UserRole> selectByExample(UserRoleExample example);
int insert(UserRole record);
}
package com.fedex.connect.manager.dao.repository.sys.impl;
import com.fedex.connect.common.model.base.DictionaryEntries;
import com.fedex.connect.common.model.base.DictionaryEntriesExample;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.sys.IDictionaryEntriesRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class DictionaryEntriesImpl extends BaseDao implements IDictionaryEntriesRepository {
@Override
public List<DictionaryEntries> selectByExample(DictionaryEntriesExample example) {
return dictionaryEntriesMapper.selectByExample(example);
}
}
package com.fedex.connect.manager.dao.repository.sys.impl;
import com.fedex.connect.common.model.sys.RedisSlab;
import com.fedex.connect.common.model.sys.RedisSlabExample;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.sys.IRedisSlabRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class RedisSlabRepositoryImpl extends BaseDao implements IRedisSlabRepository {
@Override
public int insert(RedisSlab record) {
return redisSlabMapper.insert(record);
}
@Override
public List<RedisSlab> selectByExample(RedisSlabExample example) {
return redisSlabMapper.selectByExample(example);
}
@Override
public int deleteByPrimaryKey(Long id) {
return redisSlabMapper.deleteByPrimaryKey(id);
}
}
package com.fedex.connect.manager.dao.repository.sys.impl;
import com.fedex.connect.common.model.sys.Role;
import com.fedex.connect.common.model.sys.RoleExample;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.sys.IRoleRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class RoleRepositoryImpl extends BaseDao implements IRoleRepository {
@Override
public List<Role> selectByExample(RoleExample example) {
return roleMapper.selectByExample(example);
}
@Override
public Role selectByPrimaryKey(Long id) {
return roleMapper.selectByPrimaryKey(id);
}
@Override
public int insert(Role record) {
return roleMapper.insert(record);
}
}
package com.fedex.connect.manager.dao.repository.sys.impl;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.common.model.sys.UserExample;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.sys.IUserRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserRepositoryImpl extends BaseDao implements IUserRepository {
@Override
public List<User> selectByExample(UserExample example) {
return userMapper.selectByExample(example);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
}
package com.fedex.connect.manager.dao.repository.sys.impl;
import com.fedex.connect.common.model.sys.UserRole;
import com.fedex.connect.common.model.sys.UserRoleExample;
import com.fedex.connect.manager.dao.base.BaseDao;
import com.fedex.connect.manager.dao.repository.sys.IUserRoleRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserRoleRepositoryImpl extends BaseDao implements IUserRoleRepository {
@Override
public List<UserRole> selectByExample(UserRoleExample example) {
return userRoleMapper.selectByExample(example);
}
@Override
public int insert(UserRole record) {
return userRoleMapper.insert(record);
}
}
package com.fedex.connect.manager.data.bo;
import com.fedex.connect.common.dependencies.util.DateUtil;
import com.fedex.connect.common.model.sys.RedisSlab;
import java.util.Date;
public class RedisSlabBo {
public static RedisSlab toDao(String key, String value, int validDuration){
RedisSlab dao = new RedisSlab();
dao.setRedisKey(key);
dao.setRedisMsg(value);
dao.setValidDuration(validDuration != 0 ? Long.valueOf(validDuration) : 0L);
dao.setDisTime(DateUtil.getHoursAgoTime(validDuration));
dao.setCreateTime(new Date());
return dao;
}
/**
* ID自增
*/
private Long id;
/**
* Redis key
*/
private String redisKey;
/**
* Redis信息
*/
private String redisMsg;
/**
* 有效时长
*/
private Long validDuration;
/**
* 失效时间
*/
private Date disTime;
/**
* 创建时间
*/
private Date createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRedisKey() {
return redisKey;
}
public void setRedisKey(String redisKey) {
this.redisKey = redisKey;
}
public String getRedisMsg() {
return redisMsg;
}
public void setRedisMsg(String redisMsg) {
this.redisMsg = redisMsg;
}
public Long getValidDuration() {
return validDuration;
}
public void setValidDuration(Long validDuration) {
this.validDuration = validDuration;
}
public Date getDisTime() {
return disTime;
}
public void setDisTime(Date disTime) {
this.disTime = disTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public RedisSlabBo() {
}
public RedisSlabBo(Long id, String redisKey, String redisMsg, Long validDuration, Date disTime, Date createTime) {
this.id = id;
this.redisKey = redisKey;
this.redisMsg = redisMsg;
this.validDuration = validDuration;
this.disTime = disTime;
this.createTime = createTime;
}
}
package com.fedex.connect.manager.data.dto;
import com.fedex.connect.common.model.log.UserLoginInfo;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
/**
* Dto对象用于记录登录操作日志
* 不建议继承:含义不同,不要混淆
* 不建议反射:数据量上来反射copy很慢。set最快
* dao 转dto 看业务是否需要了。
*/
public class LogLoginDto {
/**
* 重载构造函数
*/
public LogLoginDto(Long userId, Long operType, String operDesc){
this.userId = userId;
this.operTime = new Date();
this.operType = operType;
this.operDesc = operDesc;
try{
this.ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e){
this.ip = "127.0.01";
}
}
/**
* dto转dao
* @param dto
* @return
*/
public static UserLoginInfo dtoToDao(LogLoginDto dto){
UserLoginInfo log = new UserLoginInfo();
if (dto == null){
return log;
}
if (dto.getId() != null && dto.getId() != 0){
log.setId(dto.getId());
}
log.setUserId(dto.getUserId());
log.setOperDesc(dto.getOperDesc());
log.setIp(dto.getIp());
return log;
}
//InetAddress.getLocalHost().getHostAddress()
/**
* ID
*/
private Long id;
/**
* 用户id
*/
private Long userId;
/**
* 操作时间
*/
private Date operTime;
/**
* 操作类型
1:登录 2:退出 3:修改密码4:FCL登录注册
*/
private Long operType;
/**
* 操作描述
*/
private String operDesc;
/**
* IP
*/
private String ip;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getOperTime() {
return operTime;
}
public void setOperTime(Date operTime) {
this.operTime = operTime;
}
public Long getOperType() {
return operType;
}
public void setOperType(Long operType) {
this.operType = operType;
}
public String getOperDesc() {
return operDesc;
}
public void setOperDesc(String operDesc) {
this.operDesc = operDesc;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public LogLoginDto() {
}
public LogLoginDto(Long id, Long userId, Date operTime, Long operType, String operDesc, String ip) {
this.id = id;
this.userId = userId;
this.operTime = operTime;
this.operType = operType;
this.operDesc = operDesc;
this.ip = ip;
}
}
package com.fedex.connect.manager.data.dto;
import com.fedex.connect.common.dependencies.enums.ResponseCode;
import com.fedex.connect.common.dependencies.util.Utils;
import com.fedex.connect.manager.data.vo.JsonResult;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
/**
* 用户登录请求DTO
* @author Administrator
*/
public class LoginRequest implements Serializable {
public static LoginRequest dataProcessing(LoginRequest dto){
dto.setAccNo(Utils.trim(dto.getAccNo()));
dto.setPassword(Utils.trim(dto.getPassword()));
return dto;
}
/**
* 验证用户登录信息
* @param dto
* @return
*/
public static JsonResult validate(LoginRequest dto){
if (dto == null){
JsonResult.fail(ResponseCode.REQUEST_PARAM_NULL.getMsg());
}
if (StringUtils.isBlank(dto.getAccNo())){
JsonResult.fail("auth_login_accno_null");
}
if (StringUtils.isBlank(dto.getPassword())){
JsonResult.fail("auth_login_pwd_null");
}
return JsonResult.succ(null);
}
/**
* 用户账号
*/
private String accNo;
/**
* 用户密码
*/
private String password;
/**
* 记住用户号
*/
private Boolean rememberMe;
public String getAccNo() {
return accNo;
}
public void setAccNo(String accNo) {
this.accNo = accNo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getRememberMe() {
return rememberMe;
}
public void setRememberMe(Boolean rememberMe) {
this.rememberMe = rememberMe;
}
}
package com.fedex.connect.manager.data.model;
import com.google.gson.Gson;
/**
* 用于打印日志的Model。
* 为了将来打印的日志,转换语言
* @author EDY
*/
public class LogShowModel {
/**
* 方法
*/
private String method;
/**
* 参数
*/
private Object param;
/**
* 返回
*/
private Object result;
/**
* 异常
*/
private Exception e;
/**
* 错误
*/
private String msg;
public static String showRequest(String methodName, Object param){
LogShowModel lsm = new LogShowModel();
lsm.setMethod(methodName);
lsm.setParam(param);
return lsm.toString();
}
public static String showResponse(String methodName, Object result){
LogShowModel lsm = new LogShowModel();
lsm.setMethod(methodName);
lsm.setResult(result);
return lsm.toString();
}
public static String showException(String methodName, Exception e){
LogShowModel lsm = new LogShowModel();
lsm.setMethod(methodName);
lsm.setE(e);
return lsm.toString();
}
public static String showMsg(String methodName, String msg){
LogShowModel lsm = new LogShowModel();
lsm.setMethod(methodName);
lsm.setMsg(msg);
return lsm.toString();
}
@Override
public String toString() {
Gson gson = new Gson();
StringBuilder show = new StringBuilder("方法:" + method);
if (param != null){
show.append(",请求参数:"+gson.toJson(param));
}
if (result != null){
show.append(",响应:"+gson.toJson(result));
}
if (e != null){
show.append(",异常:"+ e.toString());
}
if (msg != null){
show.append(","+ msg);
}
return show.toString();
}
public LogShowModel(String method, Object param, Object result, Exception e, String msg) {
this.method = method;
this.param = param;
this.result = result;
this.e = e;
this.msg = msg;
}
public LogShowModel() {
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Object getParam() {
return param;
}
public void setParam(Object param) {
this.param = param;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public Exception getE() {
return e;
}
public void setE(Exception e) {
this.e = e;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.fedex.connect.manager.data.vo;
import com.fedex.connect.common.dependencies.enums.ResponseCode;
import javax.servlet.http.HttpServletResponse;
public class JsonResult<T> {
private int code = HttpServletResponse.SC_BAD_REQUEST;;
private String msg;
private boolean success;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static JsonResult succ(Object data,String message) {
return succ(ResponseCode.SUCCESS_CODE.getCode(), message, data);
}
public static JsonResult succ(Object data) {
return succ(ResponseCode.SUCCESS_CODE.getCode(), "SUCCESS", data);
}
public static JsonResult succ(int code, String msg, Object data) {
JsonResult r = new JsonResult();
r.setCode(code);
r.setMsg(msg);
r.setSuccess(true);
r.setData(data);
return r;
}
public static JsonResult fail(String msg) {
return fail(ResponseCode.FAIL_CODE.getCode(), msg,null);
}
public static JsonResult fail(int code, String msg,Object data) {
JsonResult r = new JsonResult();
r.setCode(code);
r.setMsg(msg);
r.setSuccess(false);
r.setData(data);
return r;
}
public static JsonResult fail(ResponseCode resultCode) {
return fail(resultCode.getCode(), resultCode.getMsg(), null);
}
public static JsonResult fail(ResponseCode resultCode, Object data) {
return fail(resultCode.getCode(), resultCode.getMsg(), data);
}
}
package com.fedex.connect.manager.service;
import com.fedex.connect.common.dao.log.UserLoginInfoMapper;
import com.fedex.connect.common.dao.sys.RoleMapper;
import com.fedex.connect.common.dao.sys.UserMapper;
import com.fedex.connect.common.dao.sys.UserRoleMapper;
import com.fedex.connect.common.dependencies.i18n.LocaleMessageUtil;
import com.fedex.connect.manager.dao.repository.log.IUserLoginLogRepository;
import com.fedex.connect.manager.dao.repository.sys.*;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
public class AbstractEtService {
@Resource
protected LocaleMessageUtil localeMessageUtil;
/**
* repository
*/
@Autowired
public IUserLoginLogRepository userLoginLogRepository;
@Autowired
public IRedisSlabRepository redisSlabRepository;
@Autowired
public IRoleRepository roleRepository;
@Autowired
public IUserRoleRepository userRoleRepository;
@Autowired
public IUserRepository userRepository;
@Autowired
public IDictionaryEntriesRepository dictionaryEntriesRepository;
/**
* Mapper---------------------------------------------
*/
@Autowired
protected UserMapper userMapper;
@Autowired
protected UserRoleMapper userRoleMapper;
@Autowired
protected RoleMapper roleMapper;
@Autowired
protected UserLoginInfoMapper userLoginInfoMapper;
/**
* MapperExt---------------------------------------------
*/
}
package com.fedex.connect.manager.service.base;
import com.fedex.connect.common.model.base.DictionaryEntries;
import java.util.List;
public interface IInitDictionaryEntriesService {
List<DictionaryEntries> findAll();
void initializeDictionary();
}
package com.fedex.connect.manager.service.base.impl;
import com.fedex.connect.common.dependencies.config.DictionaryProvider;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.model.base.DictionaryEntries;
import com.fedex.connect.common.model.base.DictionaryEntriesExample;
import com.fedex.connect.manager.data.model.LogShowModel;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.base.IInitDictionaryEntriesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Order(value = 1)
public class InitInitDictionaryEntriesServiceImpl extends AbstractEtService implements IInitDictionaryEntriesService {
private static Logger log = LoggerFactory.getLogger(InitInitDictionaryEntriesServiceImpl.class);
public List<DictionaryEntries> findAll() {
try{
DictionaryEntriesExample example = new DictionaryEntriesExample();
DictionaryEntriesExample.Criteria criteria = example.createCriteria();
criteria.andStatusEqualTo(DatabaseConstants.GLOBAL_STATUS_VALID);
example.setOrderByClause("CREATE_TIME DESC");
return dictionaryEntriesRepository.selectByExample(example);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
public void initializeDictionary() {
List<DictionaryEntries> data = findAll(); // 获取字典数据
DictionaryProvider.setDictionaryData(data); // 将数据设置到字典提供者中
}
}
package com.fedex.connect.manager.service.system;
import com.fedex.connect.common.model.sys.RedisSlab;
public interface IRedisUtilService {
Boolean set(String key, String value,int expireTimeH);
Boolean set(String key, String value);
RedisSlab get(String key, String value);
RedisSlab get(String key);
<T> T get(String key, Class<T> clazz);
int del(String key);
}
package com.fedex.connect.manager.service.system;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.manager.data.dto.LoginRequest;
import com.fedex.connect.manager.data.vo.JsonResult;
import com.google.gson.JsonObject;
public interface ISysAuthService {
JsonResult createAccessToken(LoginRequest loginRequest, User user);
JsonResult createFclToken(JsonObject token);
JsonObject getFclToken(String tokenKey);
}
package com.fedex.connect.manager.service.system;
import com.fedex.connect.common.model.sys.Role;
public interface ISysRoleService {
Role findRoleByCode(String roleCode);
}
package com.fedex.connect.manager.service.system;
public interface ISysUserRoleService {
int save(Long userId,Long roleId);
}
package com.fedex.connect.manager.service.system;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.manager.data.dto.SysUserDto;
public interface ISysUserService {
User findUserByFcl(String fclUuid);
User save(SysUserDto dto);
int update(User dao);
}
package com.fedex.connect.manager.service.system.impl;
import com.fedex.connect.common.dependencies.util.GsonUtils;
import com.fedex.connect.common.model.sys.RedisSlab;
import com.fedex.connect.common.model.sys.RedisSlabExample;
import com.fedex.connect.manager.data.bo.RedisSlabBo;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.system.IRedisUtilService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.Optional;
@Service
public class RedisUtilServiceImpl extends AbstractEtService implements IRedisUtilService {
private static Logger logger = LoggerFactory.getLogger(RedisUtilServiceImpl.class);
@Transactional(rollbackFor = Exception.class)
public Boolean set(String key, String value,int expireTimeH) {
RedisSlab dao = RedisSlabBo.toDao(key,value, expireTimeH);
RedisSlab redisSlab = get(key);
if (redisSlab != null){
del(key);
}
try {
int ct = redisSlabRepository.insert(dao);
if (ct > 0) {
return true;
}
return false;
} catch (Exception e) {
logger.error("REDIS SLAB 异常 [SET]: " + e);
throw e;
}
}
public Boolean set(String key, String value) {
return set(key,value, 1);
}
public RedisSlab get(String key,String value){
try {
RedisSlabExample example = new RedisSlabExample();
RedisSlabExample.Criteria criteria = example.createCriteria();
criteria.andRedisKeyEqualTo(key);
criteria.andRedisMsgEqualTo(value);
return CollectionUtils.firstElement(redisSlabRepository.selectByExample(example));
}catch (Exception e){
logger.error("REDIS SLAB 异常 [GET]: " + e);
throw e;
}
}
public RedisSlab get(String key){
try {
RedisSlabExample example = new RedisSlabExample();
RedisSlabExample.Criteria criteria = example.createCriteria();
criteria.andRedisKeyEqualTo(key);
return CollectionUtils.firstElement(redisSlabRepository.selectByExample(example));
}catch (Exception e){
logger.error("REDIS SLAB 异常 [GET]: " + e);
throw e;
}
}
public <T> T get(String key, Class<T> clazz) {
try {
RedisSlab redisSlab = get(key);
String str = redisSlab != null ? Optional.ofNullable(redisSlab.getRedisMsg()).orElse(null): null;
T t = GsonUtils.stringToBean(str, clazz);
return t;
}catch (Exception e){
logger.error("REDIS SLAB 异常 [GET]: " + e);
throw e;
}
}
@Transactional(rollbackFor = Exception.class)
public int del(String key){
try {
logger.info("del db redis key:{}",key);
RedisSlab redisSlab = get(key);
logger.info("del db redis key get info:{}", new Gson().toJson(redisSlab));
if (redisSlab != null){
logger.info("get info not null");
int delct = redisSlabRepository.deleteByPrimaryKey(redisSlab.getId());
logger.info("redisSlabRepository.deleteByPrimaryKey result :{}", delct);
return delct;
}
return 0;
}catch (Exception e){
logger.error("REDIS SLAB 异常 [DEL]: " + e);
throw e;
}
}
}
package com.fedex.connect.manager.service.system.impl;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.dependencies.contants.RedisConstants;
import com.fedex.connect.common.dependencies.enums.ResponseCode;
import com.fedex.connect.common.dependencies.util.GsonUtils;
import com.fedex.connect.common.dependencies.util.JwtTokenUtils;
import com.fedex.connect.common.model.sys.RedisSlab;
import com.fedex.connect.common.model.sys.Role;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.manager.data.dto.LoginRequest;
import com.fedex.connect.manager.data.vo.JsonResult;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.system.IRedisUtilService;
import com.fedex.connect.manager.service.system.ISysAuthService;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* 处理用户相关Service
* 包括创建用户token,用户的角色设置,角色的菜单设置
* @author EDY
*/
@Service
public class SysAuthServiceImpl extends AbstractEtService implements ISysAuthService {
private Logger logger = LoggerFactory.getLogger(SysAuthServiceImpl.class);
@Autowired
private SysRoleServiceImpl sysRoleInfoService;
@Autowired
private IRedisUtilService redisUtilService;
/**
* 根据用户登录信息创建token
* @param loginRequest
* @param user
* @return
*/
public JsonResult createAccessToken(LoginRequest loginRequest, User user) {
//2、创建token
List<String> roleCodeList = new ArrayList<>();
Role roleInfo = sysRoleInfoService.findRoleByUserId(user.getId());
if (roleInfo != null && roleInfo.getStatus() != null
&& DatabaseConstants.GLOBAL_STATUS_VALID.equals(roleInfo)){
roleCodeList.add("ROLE_" + roleInfo.getCode() + roleInfo.getCode());
}else{
roleCodeList.add("ROLE_" + UUID.randomUUID().toString());
}
//存进redis的token,8小时有效期
String token = JwtTokenUtils.createAccessToken(user.getAccNo(), user.getId().toString(), roleCodeList, loginRequest.getRememberMe());
try {
int redisExpireTime = loginRequest.getRememberMe() ? 8 : 2;
redisUtilService.set(RedisConstants.REDIS_KEY_TOKEN + user.getId(), token, redisExpireTime);
} catch (NullPointerException e) {
logger.error("***************** redis 异常:{} *********************", e);
return JsonResult.fail(ResponseCode.SYSTEM_EXECEPTION_CODE.getCode(), localeMessageUtil.getMessage("service_auth_token_reeids"), null);
}
return JsonResult.succ(token);
}
/**
* 根据用户登录信息创建token
* @param token token信息
* @return token key
*/
public JsonResult createFclToken(JsonObject token) {
String tokenKey = DatabaseConstants.FCL_PREFIX + UUID.randomUUID();
try {
/*redisUtilService.set(RedisConstants.REDIS_KEY_TOKEN + tokenKey, GsonUtils.beanToString(token), RedisConstants.REDIS_EXPRIE_TIME_1W);*/
redisUtilService.set(RedisConstants.REDIS_KEY_TOKEN + tokenKey, GsonUtils.beanToString(token), 1);
} catch (NullPointerException e) {
logger.error("***************** redis 异常:{} *********************", e);
return JsonResult.fail(ResponseCode.SYSTEM_EXECEPTION_CODE.getCode(), localeMessageUtil.getMessage("service_auth_token_reeids"), null);
}
return JsonResult.succ(tokenKey);
}
/**
* 根据token key 获取token
* @param tokenKey tokenkey
* @return token
*/
public JsonObject getFclToken(String tokenKey) {
RedisSlab redisSlab = redisUtilService.get(RedisConstants.REDIS_KEY_TOKEN + tokenKey);
String token = redisSlab != null ? Optional.ofNullable(redisSlab.getRedisMsg()).orElse(null): null;
//清除登录记录
if (token != null){
redisUtilService.del(RedisConstants.REDIS_KEY_TOKEN + tokenKey);
}
return GsonUtils.stringToBean(token, JsonObject.class);
}
}
package com.fedex.connect.manager.service.system.impl;
import com.fedex.connect.common.dependencies.config.CacheSystem;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.dependencies.util.Utils;
import com.fedex.connect.common.model.base.DictionaryEntries;
import com.fedex.connect.common.model.sys.Role;
import com.fedex.connect.common.model.sys.RoleExample;
import com.fedex.connect.common.model.sys.UserRole;
import com.fedex.connect.common.model.sys.UserRoleExample;
import com.fedex.connect.manager.data.model.LogShowModel;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.system.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 处理角色相关Service
* @author EDY
*/
@Service
public class SysRoleServiceImpl extends AbstractEtService implements ISysRoleService {
private static Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class);
/**
* 根据用户ID获取用户角色
* @param userId
* @return
*/
public Role findRoleByUserId(Long userId){
try{
UserRole userRole = findUserRoleByUserId(userId);
if (userRole == null || userRole.getRoleId() == null || userRole.getRoleId() == 0){
return null;
}
return findById(userRole.getRoleId());
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
/**
* 根据用户ID获取用户角色对应关系(一个用户只允许存在一个角色)
* @param userId
* @return
*/
public UserRole findUserRoleByUserId(Long userId){
try{
UserRoleExample example = new UserRoleExample();
UserRoleExample.Criteria criteria = example.createCriteria();
criteria.andStatusEqualTo(DatabaseConstants.GLOBAL_STATUS_VALID);
criteria.andUserIdEqualTo(userId);
example.setOrderByClause("CREATE_TIME DESC");
return Utils.first(userRoleRepository.selectByExample(example));
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
/**
* 根据ID获取角色对象
* @param id
* @return
*/
public Role findById(Long id){
try{
return roleRepository.selectByPrimaryKey(id);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
/**
* 根据code获取角色信息(当前阶段,如果不存在,则创建默认角色)
* @param roleCode
* @return
*/
public Role findRoleByCode(String roleCode){
try{
RoleExample example = new RoleExample();
RoleExample.Criteria criteria = example.createCriteria();
criteria.andStatusEqualTo(DatabaseConstants.GLOBAL_STATUS_VALID);
criteria.andCodeEqualTo(roleCode);
List<Role> roleInfoList = roleRepository.selectByExample(example);
//如果不存在,创建默认角色
if (roleInfoList == null || roleInfoList.isEmpty()){
Role defaultRole = new Role();
defaultRole.setCode(DatabaseConstants.DICT_ROLE_DEFAULT_CODE);
defaultRole.setName(DatabaseConstants.DICT_ROLE_DEFAULT_CODE.toUpperCase());
defaultRole.setRoleDesc(DatabaseConstants.DICT_ROLE_DEFAULT_CODE.toUpperCase());
//从数据字典获取角色类型
List<DictionaryEntries> userTypeList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_ROLE_GOOUP_CODE);
if (userTypeList != null && !userTypeList.isEmpty()){
Map<String,DictionaryEntries> userTypeDictMap = Utils.listOf(userTypeList).stream().filter(Objects::nonNull)
.collect(Collectors.toMap(DictionaryEntries::getCode, d -> d));
DictionaryEntries dictionary = userTypeDictMap.get(DatabaseConstants.DICT_ROLE_DEFAULT_CODE);
defaultRole.setTypeId(dictionary == null ? 0 : dictionary.getId());
} else {
defaultRole.setTypeId(0L);
}
defaultRole.setStatus(DatabaseConstants.GLOBAL_STATUS_VALID);
defaultRole.setCreateTime(new Date());
save(defaultRole);
return defaultRole;
} else {
return roleInfoList.get(0);
}
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
/**
* 保存角色
* @param dao
* @return
*/
@Transactional(rollbackFor = Exception.class)
public int save(Role dao){
try{
return roleRepository.insert(dao);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
throw e;
}
}
}
package com.fedex.connect.manager.service.system.impl;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.model.sys.UserRole;
import com.fedex.connect.manager.data.model.LogShowModel;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.system.ISysUserRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* 处理用户角色Service
* @author EDY
*/
@Service
public class SysUserRoleServiceImpl extends AbstractEtService implements ISysUserRoleService {
private static Logger log = LoggerFactory.getLogger(SysUserRoleServiceImpl.class);
/**
* 保存用户角色关系
* @param userId
* @param roleId
* @return
*/
@Transactional(rollbackFor = Exception.class)
public int save(Long userId,Long roleId){
try{
UserRole userRole = new UserRole();
userRole.setUserId(userId);
userRole.setRoleId(roleId);
userRole.setStatus(DatabaseConstants.GLOBAL_STATUS_VALID);
userRole.setCreateTime(new Date());
userRole.setUpdateTime(new Date());
return userRoleRepository.insert(userRole);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
throw e;
}
}
}
package com.fedex.connect.manager.service.system.impl;
import com.fedex.connect.common.dependencies.arithmetic.AESUtil;
import com.fedex.connect.common.dependencies.authentication.EncryptProvider;
import com.fedex.connect.common.dependencies.config.CacheSystem;
import com.fedex.connect.common.dependencies.contants.DatabaseConstants;
import com.fedex.connect.common.dependencies.util.Utils;
import com.fedex.connect.common.model.base.DictionaryEntries;
import com.fedex.connect.common.model.sys.Role;
import com.fedex.connect.common.model.sys.User;
import com.fedex.connect.common.model.sys.UserExample;
import com.fedex.connect.manager.data.dto.SysUserDto;
import com.fedex.connect.manager.data.model.LogShowModel;
import com.fedex.connect.manager.service.AbstractEtService;
import com.fedex.connect.manager.service.system.ISysRoleService;
import com.fedex.connect.manager.service.system.ISysUserRoleService;
import com.fedex.connect.manager.service.system.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 用户相关操作
*/
@Service
public class SysUserServiceImpl extends AbstractEtService implements ISysUserService {
private static Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
@Autowired
private ISysRoleService sysRoleService;
@Autowired
private ISysUserRoleService sysUserRoleService;
/**
* 邮件过期时间
*/
@Value("${export.emailActiveTime}")
private String emailActiveTime ;
/**
* 根据FCL查询FCL用户信息
* @param fclUuid
* @return
*/
public User findUserByFcl(String fclUuid){
try{
String fcl_pwd = DatabaseConstants.FCL_PREFIX + "_" + fclUuid + "_pwd";
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
criteria.andStatusEqualTo(DatabaseConstants.GLOBAL_STATUS_VALID);
criteria.andUserSourceEqualTo(DatabaseConstants.USER_SOURCE_FCL);
criteria.andAccNoEqualTo(fclUuid);
//criteria.andFedexAccNoEqualTo(fclUuid);
example.setOrderByClause("ID DESC");
//根据账号 Fedex账户,备注查询用户信息
List<User> userList = userRepository.selectByExample(example);
//查询出来的用户信息进行密码匹配
List<User> resultUserList = Utils.listOf(userList).stream().filter(Objects::nonNull)
.filter(u -> EncryptProvider.match(fcl_pwd, u.getPassword()))
.collect(Collectors.toList());
//返回匹配出来第一个账户信息
return Utils.first(resultUserList);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
/**
* 保存
* @param dto
* @return
*/
public User save(SysUserDto dto){
try{
User user = SysUserDto.dtoToDao(dto);
//从数据字典获取用户类型
List<DictionaryEntries> userTypeList = CacheSystem.dictionaryMap.get(DatabaseConstants.DICT_USER_GOOUP_CODE);
if (Utils.isNotEmpty(userTypeList)){
//从数据字典中获取用户类型
Map<String,DictionaryEntries> userTypeDictMap = Utils.listOf(userTypeList).stream().filter(Objects::nonNull)
.collect(Collectors.toMap(DictionaryEntries::getCode, d -> d));
DictionaryEntries dictionary = userTypeDictMap.get(dto.getTypeCode());
user.setTypeId(dictionary == null ? 0 : dictionary.getId());
} else{
user.setTypeId(0L);
}
//对新增账户的密码进行加密
user.setPassword(EncryptProvider.encrypt(user.getPassword()));
//对手机号进行可逆加密
if (!StringUtils.isBlank(user.getPhone())){
user.setPhone(AESUtil.encode_default(user.getPhone()));
}
//对用户姓名进行可逆加密
if (StringUtils.isNotBlank(user.getUserName())){
user.setUserName(user.getUserName());
}
int saveUserCt = saveSysUser(user);
//当前阶段,权限采用默认权限
if (saveUserCt > 0){
Role roleInfo = sysRoleService.findRoleByCode(DatabaseConstants.DICT_ROLE_DEFAULT_CODE);
//创建用户角色对应关系
sysUserRoleService.save(user.getId(), roleInfo.getId());
}
return user;
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
return null;
}
}
@Transactional(rollbackFor = Exception.class)
public int saveSysUser(User user){
try{
return userRepository.insert(user);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
throw e;
}
}
/**
* 修改
* @param dao
* @return
*/
@Transactional(rollbackFor = Exception.class)
public int update(User dao){
try{
return userRepository.updateByPrimaryKeySelective(dao);
} catch (Exception e){
log.error(LogShowModel.showException("Exception",e));
throw e;
}
}
}