提交 bf66e8d9 authored 作者: 黄夏豪's avatar 黄夏豪

项目完善

上级 c960df7b
......@@ -152,11 +152,11 @@
</dependency>
<!--eureka:注册到注册中心-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<!--<version>2.0.1.RELEASE</version>-->
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
<!-- &lt;!&ndash;<version>2.0.1.RELEASE</version>&ndash;&gt;-->
<!-- </dependency>-->
<!--admin客户端依赖-->
<dependency>
<groupId>de.codecentric</groupId>
......
......@@ -6,12 +6,8 @@ import com.example.personnelmanager.dao.SimpleJpaRepositoryImpl;
import gnu.io.CommPortIdentifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
......@@ -19,17 +15,14 @@ import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.persistence.EntityListeners;
/**
* springBoot启动类
*
* @author Huangxiahao
*/
@EnableFeignClients
@EnableAsync
@EnableScheduling
@EnableDiscoveryClient
//@EnableDiscoveryClient
@SpringBootApplication
@EnableSwagger2
@EnableJpaAuditing
......@@ -39,9 +32,11 @@ public class PersonnelmanagerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(PersonnelmanagerApplication.class, args);
//todo 初始化一个初始企业 初始化一个admin 初始化一个节点
System.out.println("程序运行成功");
DateCenterUtil dateCenterUtil = SpringUtils.getBean("dateCenterUtil");
dateCenterUtil.sendDateToCenter();
// dateCenterUtil.initUser();
}
@Bean
......
......@@ -18,6 +18,7 @@ package com.example.personnelmanager.common.authencation.filter;
import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken;
import com.example.personnelmanager.common.exception.GlobalException;
import com.example.personnelmanager.common.utils.CipherUtil;
import com.example.personnelmanager.common.utils.JwtUtils;
import com.example.personnelmanager.common.utils.RsaUtils;
import com.example.personnelmanager.common.utils.UTF8ToString;
......@@ -26,6 +27,7 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
......@@ -59,10 +61,9 @@ public class CustomJwtAuthenticationFilter extends
*/
String jwtFilePath;
public CustomJwtAuthenticationFilter(String jwtFilePath) {
public CustomJwtAuthenticationFilter() {
//设置用户接口的路径以及访问方式
super(new AntPathRequestMatcher("/api/user/login", "GET"));
this.jwtFilePath = jwtFilePath;
}
/***
......@@ -81,7 +82,7 @@ public class CustomJwtAuthenticationFilter extends
//通过请求头获取jwt凭证中的用户信息
userByJwt = getuserbyjwt(request);
authRequest = new JwtAuthencationToken(
userByJwt.getUsername().trim());
userByJwt);
//为用于验证的用户注入session信息
setDetails(request, authRequest);
//进行验证
......@@ -89,10 +90,6 @@ public class CustomJwtAuthenticationFilter extends
} else {
throw new GlobalException("未设置token");
}
//以下为测试代码
// JwtAuthencationToken authRequest ;
// authRequest = new JwtAuthencationToken("admin");
// return getAuthenticationManager().authenticate(authRequest);
}
......@@ -114,28 +111,21 @@ public class CustomJwtAuthenticationFilter extends
* @Return : com.example.personnelmanager.entity.User
*/
public User getuserbyjwt(HttpServletRequest request) {
String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJcz+ZlYYNQVfAap+Qyj7A7izqRVcDYLInB35mKe3Vqo/dN/0bDSTLKibu3wf4DigTszxZ7I7B2jkWrIB0V4RX56clWWGwfneLLTM9WDcNav6QDpt7ioBCdMdkJiOGgGQ9nIBHZI1WQAeRhjffNELa2pi3VffiSEoODEQ61+N3DfAgMBAAECgYBBBanlptrk+WQ/nWKra+a8tA53HwLFSt6BjR429Oht71RQWpw7NQSkoTOhARZjv4QhiG8IjJD1YfzL9b8iwcjoI8Na+aZN3Ugx5tc+PZzAXA22S4EXVl8RBlLOwhak7R37Ildikm2pBY2UC1iI/Uh2tK4jIAr6i+cYlc6DAo66sQJBANxolsi7WNvmgZSNUPF0HYF1kY9WylmFaDWpH5lcbZxj0EmEkaM+T54P6iYj2ivTHsSJIPSi/T3Ss/oEmLTNKNcCQQCvnoRgj2K2GEpORdLHye3CKn3LOCW/f8dCuwggITsGz7rdUUJhjX4RopCPXt92SDED8JdqZFFe3JhZODvhqU85AkAv99cxEozxNsZmxSajlejB/wtRzcq2FvGqFAebgeEdEyAGkAJ+K5Z6SO5lpJHbzdO5ZDq24y4IIW4n8I4ncyr7AkADbhUnzaUf6VmKLdLwFAGQyUOrtG0IUHaT1xNRjVSZzXTY3b1uKlVMAuDP7ApxRPewHALZERyFvck79N02ixgBAkEAzjHNWU5lCbQeqgHF8jwHMN/08c3tMZvJRRyFjFiExiNn1Qj2iqRd1FiyVt1nSJ8jeDbFxPn6McDk5vAZslSRvQ==";
String signPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPepqt/IABL0roOaP4PWFnSBBfQlHae1ojeSxZMK7rcPhXRjg/xahs/qtLe4gblJ1dnUOWwZhcky2Q+jyHCaeSO8TWqnH/+OWsYQDHT7jSzYj9GETqQaxmIm2b919RITfBwsh4lTnar9ZUPvJD6HGrfZUY7RvuMapDwRSo8UUy8wIDAQAB";
String jwt = request.getHeader("jwt");
logger.info("接收到的头部信息:"+jwt);
jwt = jwt.replace("\"","");
logger.info("处理过后的头部信息:"+jwt);
PublicKey publicKey = null;
try {
publicKey = RsaUtils.getPublicKey(jwtFilePath);
} catch (Exception e) {
e.printStackTrace();
}
try {
logger.info("公钥为:"+publicKey);
Jws<Claims> claimsJws = JwtUtils.parseToken(publicKey, jwt);
String decrypt = CipherUtil.decrypt(jwt, CipherUtil.string2PrivateKey(rsaPrivateKey));
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(CipherUtil.string2PublicKey(signPublicKey)).parseClaimsJws(decrypt);
logger.info("接收到的用户信息为:"+claimsJws.getBody());
User userRight = new User();
Claims body = claimsJws.getBody();
userRight.setUsername((String) body.get("username"));
userRight.setPhone((String) body.get("phone"));
return userRight;
}catch (Exception e){
logger.error("用户凭证无效");
throw new UsernameNotFoundException("用户凭证无效");
}
}
}
......@@ -2,6 +2,8 @@ package com.example.personnelmanager.common.authencation.provider;
import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken;
import com.example.personnelmanager.common.authencation.checks.DefaultPreAuthenticationChecks;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.service.impl.UserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
......@@ -25,14 +27,14 @@ import org.springframework.util.Assert;
@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {
private final UserDetailsService userDetailsService;
private final UserDetailsServiceImpl userDetailsService;
/**
* 用户可用性检查类
*/
private final UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();
public JwtAuthenticationProvider(UserDetailsService userDetailsService) {
public JwtAuthenticationProvider(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
......@@ -47,8 +49,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider {
Assert.isInstanceOf(JwtAuthencationToken.class, authentication,
"错误的凭证");
String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
: authentication.getName();
UserDetails user = retrieveUser(username);
: ((User)authentication.getPrincipal()).getUsername();
UserDetails user = retrieveUser(username,((User)authentication.getPrincipal()).getPhone());
preAuthenticationChecks.check(user);
return createSuccessAuthentication(user,authentication,user);
}
......@@ -70,8 +72,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider {
* @param username
* @Return : org.springframework.security.core.userdetails.UserDetails
*/
protected final UserDetails retrieveUser(String username) {
UserDetails loadedUser = userDetailsService.loadUserByUsername(username);
protected final UserDetails retrieveUser(String username,String phone) {
UserDetails loadedUser = userDetailsService.loadUserByUsername(username,phone);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
......
......@@ -35,6 +35,8 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
*/
private final PasswordEncoder passwordEncoder;
private final UserDetailsService userDetailsService;
/**
......
......@@ -73,4 +73,6 @@ public class JwtAuthencationToken extends AbstractAuthenticationToken {
credentials = null;
}
}
package com.example.personnelmanager.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 描述:跨域处理
*
* @author HuangXiahao
* @version V1.0
* @class CorsConfig
* @packageName com.example.demo.common.config
* @data 2020/4/21
**/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
\ No newline at end of file
package com.example.personnelmanager.common.config;
import com.example.personnelmanager.common.authencation.filter.JWTAuthorizationFilter;
import com.example.personnelmanager.common.authencation.provider.JwtAuthenticationProvider;
import com.example.personnelmanager.common.authencation.provider.UsernamePasswordAuthenticationProvider;
import com.example.personnelmanager.common.authencation.filter.CustomJwtAuthenticationFilter;
......@@ -23,6 +24,7 @@ import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
......@@ -60,8 +62,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
/**
* jwt公钥存储路径
**/
@Value("${file.jwtFilePath}")
String jwtFilePath;
// @Value("${file.jwtFilePath}")
// String jwtFilePath;
public SecurityWebConfig(JwtAuthenticationProvider jwtAuthenticationProvider, UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider) {
this.jwtAuthenticationProvider = jwtAuthenticationProvider;
......@@ -90,11 +92,11 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
"/swagger-ui.html",
"/webjars/**").permitAll()
.anyRequest()
.permitAll()
.authenticated()
.and()
.logout()
//登出接口权限开放
.logoutUrl("/user/logout").permitAll()
.logoutUrl("/api/user/logout").permitAll()
.and()
.sessionManagement()
.and()
......@@ -104,7 +106,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
//添加自定义用户验证拦截器至UsernamePasswordAuthenticationFilter的位置
http.addFilterAt(customUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
http.addFilterAt(customJwtUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
// http.addFilterAt(customJwtUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
// http.addFilterAt(new JWTAuthorizationFilter(authenticationManager()), BasicAuthenticationFilter.class);
}
/***
......@@ -128,7 +131,7 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
*/
@Bean
CustomJwtAuthenticationFilter customJwtUsernamePasswordAuthenticationFilter() throws Exception {
CustomJwtAuthenticationFilter filter = new CustomJwtAuthenticationFilter(jwtFilePath);
CustomJwtAuthenticationFilter filter = new CustomJwtAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
......
......@@ -2,6 +2,7 @@ package com.example.personnelmanager.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
......@@ -19,6 +20,20 @@ public class WebMvcConfig implements WebMvcConfigurer {
@Value("${file.imagePath}")
String imagePath;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("PUT", "DELETE", "GET", "POST", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(true).maxAge(3600);
}
/**
* 静态资源配置
*
......
package com.example.personnelmanager.common.utils;
import com.example.personnelmanager.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
* @author HuangXiahao
* @version V1.0
* @class encryptionUtil
* @packageName com.tykj.support.misc.util
**/
@Slf4j
public class CipherUtil {
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
private static String getPublicKeyString(PublicKey publicKey) {
return new String(Base64.getEncoder().encode(publicKey.getEncoded()));
}
private static String getPrivateKeyString(PrivateKey privateKey) {
return new String(Base64.getEncoder().encode(privateKey.getEncoded()));
}
/**
* 获取私钥
*
* @param str 私钥字符串
* @return
*/
public static PrivateKey string2PrivateKey(String str) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.getDecoder().decode(str.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new GlobalException("解析私钥错误");
}
}
/**
* 获取公钥
*
* @param str 公钥字符串
* @return
*/
public static PublicKey string2PublicKey(String str) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.getDecoder().decode(str.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new GlobalException("解析公钥错误");
}
}
/**
* RSA加密
*
* @param data 待加密数据
* @param publicKey 公钥
* @return
*/
public static String encrypt(String data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return Base64.getEncoder().encodeToString(encryptedData);
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
throw new GlobalException("加密失败");
}
}
/**
* RSA解密
*
* @param data 待解密数据
* @param privateKey 私钥
* @return
*/
public static String decrypt(String data, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.getDecoder().decode(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
throw new GlobalException("加密失败");
}
}
}
......@@ -45,7 +45,7 @@ public class DateCenterJsonUtil {
*/
public String initAllPeopleJsonStr(List<People> allPeople){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tableId",1308221225377472514L);
jsonObject.addProperty("tableId",1320331389656211458L);
jsonObject.addProperty("primaryKeyName","people_id");
JsonArray jsonElements = new JsonArray();
allPeople.forEach(people -> {
......@@ -64,6 +64,16 @@ public class DateCenterJsonUtil {
jsonElementPeopleData.addProperty("post_id", people.getPeoplePosts().get(0).getPost().getPostId());
jsonElementPeopleData.addProperty("node_id", people.getPeoplePosts().get(0).getPost().getOrganizationNode().getNodeId());
}
if (people.getSex()!=null){
jsonElementPeopleData.addProperty("sex", people.getSex());
}
if (people.getPhone()!=null){
jsonElementPeopleData.addProperty("phone", people.getPhone());
}
if (people.getCurrentResidence()!=null){
jsonElementPeopleData.addProperty("current_residence", people.getCurrentResidence());
}
jsonElementPeopleData.addProperty("delete_tag", people.getDeleteTag());
jsonElementPeopleData.addProperty("icon",people.getIcon());
jsonElementPeople.add("dataMap",jsonElementPeopleData);
......@@ -96,14 +106,14 @@ public class DateCenterJsonUtil {
*/
public String initAllOrganizationNodeJsonStr(List<OrganizationNode> allNode){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tableId",1308222142906638337L);
jsonObject.addProperty("tableId",1320331411160408065L);
jsonObject.addProperty("primaryKeyName","node_id");
JsonArray jsonElements = new JsonArray();
allNode.forEach(node -> {
JsonObject jsonElementPeople = new JsonObject();
jsonElementPeople.addProperty("primaryKeyValue",node.getNodeId());
JsonObject jsonElementPeopleData = new JsonObject();
jsonElementPeopleData.addProperty("name",node.getNodeName());
jsonElementPeopleData.addProperty("node_name",node.getNodeName());
jsonElementPeopleData.addProperty("parent_node",node.getParentNode());
jsonElementPeopleData.addProperty("delete_tag",node.getDeleteTag());
jsonElementPeople.add("dataMap",jsonElementPeopleData);
......@@ -112,4 +122,49 @@ public class DateCenterJsonUtil {
jsonObject.add("data",jsonElements);
return jsonObject.toString();
}
/**
* People 生成Json字符串 向数据中心提交数据
* Json结构
* {
* "tableId": 1308221225377472514,
* "primaryKeyName": "people_id",
* "data": [
* {
* "primaryKeyValue": 1,
* "dataMap": {
* "node_id":1
* "name": "开发部",
* "parent_node": "1",
* "delete_tag":"0",
* }
* }
* ]
* }
* @param peoples
* @return
*/
public String initUserJsonStr(List<People> peoples){
JsonArray jsonArray = new JsonArray();
peoples.forEach(people -> {
JsonObject jsonObject = new JsonObject();
if (people.getIdCardNumber()!=null){
jsonObject.addProperty("idCard",people.getIdCardNumber());
}
if (people.getSex()!=null){
if (people.getSex().equals("男")){
jsonObject.addProperty("sex",0);
}else {
jsonObject.addProperty("sex",1);
}
}
jsonObject.addProperty("des",people.getName());
jsonObject.addProperty("name",people.getName());
jsonObject.addProperty("phone",people.getPhone());
jsonObject.addProperty("username",people.getName());
jsonArray.add(jsonObject);
});
return jsonArray.toString();
}
}
......@@ -2,11 +2,22 @@ package com.example.personnelmanager.common.utils;
import com.example.personnelmanager.dao.OrganizationNodeRepository;
import com.example.personnelmanager.dao.PeopleRepository;
import com.example.personnelmanager.dao.UserRepository;
import com.example.personnelmanager.entity.OrganizationNode;
import com.example.personnelmanager.entity.People;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.entity.commonEntity.CustomOrder;
import com.example.personnelmanager.entity.commonEntity.CustomPage;
import com.example.personnelmanager.service.UserServer;
import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
/**
......@@ -30,6 +41,12 @@ public class DateCenterUtil {
@Autowired
DateCenterJsonUtil jsonUtil;
@Autowired
UserServer userServer;
@Autowired
UserRepository userRepository;
public void sendDateToCenter(){
// 将数据库中的人员数据存放到数据中心
List<People> allPeople = peopleRepository.findAll();
......@@ -38,4 +55,34 @@ public class DateCenterUtil {
List<OrganizationNode> allNode = organizationNodeRepository.findAll();
httpClientUtil.post("http://124.70.194.194:8090/opt/data", jsonUtil.initAllOrganizationNodeJsonStr(allNode), "utf-8");
};
public void initUser(){
List<People> all = peopleRepository.findAll();
//初始化登录中心的用户
// httpClientUtil.post("http://127.0.0.1:12346/user/addUserList", jsonUtil.initUserJsonStr(all), "utf-8");
//初始化本系统用户
for (int i = 0; i < all.size(); i++) {
People people = all.get(i);
User user = new User();
user.setUsername(people.getName());
//判断用户名字是否在数据库中重复,如果重复则为用户名后面加上对应的重复次数,例如张三01
PredicateBuilder<User> and = Specifications.and();
and.eq("name",user.getName());
CustomPage customPage = new CustomPage();
customPage.setOrders(Arrays.asList(new CustomOrder("name", Sort.Direction.DESC)));
Page<User> users = userRepository.findAll(and.build(), customPage.getPageable());
if (users.getContent().size()>0){
User userRepeat = users.getContent().get(0);
user.setUsername(user.getName()+(userRepeat.getRepeatsNum()+1));
}
user.setAdministrator(false);
user.setCreateDate(Instant.now());
user.setName(people.getName());
user.setPassword("qwer1234");
user.setEnterprise(people.getEnterprise());
user.setPhone(people.getPhone());
userServer.addEntity(user);
}
}
}
package com.example.personnelmanager.common.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.util.Map;
/**
* @author HuangXiahao
* @version V1.0
* @class jwtUtil
* @packageName com.tykj.support.misc.util
**/
public class JwtUtil {
public static String generateToken(Map<String,Object> payloadMap, int expireMinutes, PrivateKey privateKey) {
return Jwts.builder()
.setClaims(payloadMap)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
public static String generateToken(Claims claims, int expireMinutes, PrivateKey privateKey) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
}
......@@ -7,7 +7,8 @@ import java.io.IOException;
import java.io.InputStream;
public class ResponseEntityUtil {
public static String entityToString(CloseableHttpResponse response,String encode) throws IOException {
public static String entityToString(CloseableHttpResponse response,String encode) {
EntityThread entityThread = new EntityThread(response,encode);
entityThread.start();
try {
......@@ -22,6 +23,7 @@ public class ResponseEntityUtil {
}
return result;
}
static class EntityThread extends Thread{
CloseableHttpResponse response;
......
......@@ -76,41 +76,7 @@ public class RsaUtils {
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
writeFile(privateKeyFilename, privateKeyBytes);
}
public static void test(String pubKeyStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
new BASE64Decoder().decodeBuffer(pubKeyStr));
// RSA对称加密算法
java.security.KeyFactory keyFactory;
keyFactory = java.security.KeyFactory.getInstance("RSA");
// 取公钥匙对象
PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
FileOutputStream fsPubkey = new FileOutputStream("G:/other/rsa.pub");
fsPubkey.write(publicKey.getEncoded());
fsPubkey.close();
}
/**
* 向目标路径写入文件
......
package com.example.personnelmanager.controller;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.personnelmanager.common.utils.DownloadFile;
import com.example.personnelmanager.common.utils.ExceptionMessage;
import com.example.personnelmanager.dao.CertificateRepository;
import com.example.personnelmanager.entity.Certificate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author HuangXiahao
* @version V1.0
* @class JwtController
* @packageName com.example.personnelmanager.controller
* @data 2020/6/11
**/
@RestController
public class JwtController {
protected final Log logger = LogFactory.getLog(getClass());
/**
* Jwt公钥保存路径
*/
@Value("${file.jwtFilePath}")
String jwtFilePath;
@RequestMapping(value = "/acceptSignature",method = RequestMethod.POST)
public Map acceptSignature(@RequestBody String s){
logger.info("接收到的公钥信息:"+s);
JSONObject jsonObject = JSONObject.parseObject(s);
try {
saveFile(jsonObject.getString("publicKey"));
Map result = new HashMap();
result.put("msg"," 上传成功");
result.put("code",200);
logger.info("公钥信息保存成功");
return result;
} catch (Exception e) {
e.printStackTrace();
Map result = new HashMap();
result.put("msg","接收签名信息失败");
result.put("code",500);
result.put("data","接收签名信息失败"+ ExceptionMessage.getStackTraceInfo(e));
logger.info("公钥信息接收成功");
return result;
}
}
void saveFile(String publicKey){
try {
File file = new File(jwtFilePath);
PrintWriter printWriter = new PrintWriter(new FileOutputStream(file));
printWriter.write(publicKey);
printWriter.flush();
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//package com.example.personnelmanager.controller;
//
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.TypeReference;
//import com.example.personnelmanager.common.utils.DownloadFile;
//import com.example.personnelmanager.common.utils.ExceptionMessage;
//import com.example.personnelmanager.dao.CertificateRepository;
//import com.example.personnelmanager.entity.Certificate;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.security.core.parameters.P;
//import org.springframework.web.bind.annotation.*;
//
//import javax.validation.Valid;
//import javax.validation.constraints.NotEmpty;
//import javax.validation.constraints.NotNull;
//import java.io.*;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author HuangXiahao
// * @version V1.0
// * @class JwtController
// * @packageName com.example.personnelmanager.controller
// * @data 2020/6/11
// **/
//@RestController
//public class JwtController {
//
// protected final Log logger = LogFactory.getLog(getClass());
//
//
// /**
// * Jwt公钥保存路径
// */
// @Value("${file.jwtFilePath}")
// String jwtFilePath;
//
// @RequestMapping(value = "/acceptSignature",method = RequestMethod.POST)
// public Map acceptSignature(@RequestBody String s){
// logger.info("接收到的公钥信息:"+s);
// JSONObject jsonObject = JSONObject.parseObject(s);
// try {
// saveFile(jsonObject.getString("publicKey"));
// Map result = new HashMap();
// result.put("msg"," 上传成功");
// result.put("code",200);
// logger.info("公钥信息保存成功");
// return result;
// } catch (Exception e) {
// e.printStackTrace();
// Map result = new HashMap();
// result.put("msg","接收签名信息失败");
// result.put("code",500);
// result.put("data","接收签名信息失败"+ ExceptionMessage.getStackTraceInfo(e));
// logger.info("公钥信息接收成功");
// return result;
// }
// }
//
// void saveFile(String publicKey){
// try {
// File file = new File(jwtFilePath);
// PrintWriter printWriter = new PrintWriter(new FileOutputStream(file));
// printWriter.write(publicKey);
// printWriter.flush();
// printWriter.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
//}
......@@ -8,6 +8,7 @@ import com.example.personnelmanager.entity.commonEntity.ResultObj;
import com.example.personnelmanager.entity.vo.PeopleVo;
import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo;
import com.example.personnelmanager.service.CertificateService;
import com.example.personnelmanager.service.PeoplePostService;
import com.example.personnelmanager.service.PeopleService;
import io.swagger.models.auth.In;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
......@@ -15,7 +16,12 @@ import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
......@@ -24,15 +30,14 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.*;
/**
* @author HuangXiahao
......@@ -58,6 +63,9 @@ public class PeopleController {
final CertificateService certificateService;
@Autowired
PeoplePostService peoplePostService;
public PeopleController(PeopleService peopleService, CertificateService certificateService) {
this.peopleService = peopleService;
this.certificateService = certificateService;
......@@ -70,35 +78,89 @@ public class PeopleController {
}
@RequestMapping(value = "/excel",method = RequestMethod.POST)
public ResultObj AddPeopleByexcel(@RequestParam("file") MultipartFile file) throws IOException, ParseException {
Workbook workbook = WorkbookFactory.create(file.getInputStream());
// 获得工作表个数
int sheetCount = workbook.getNumberOfSheets();
// 遍历工作表
for (int i = 0; i < sheetCount; i++)
{
Sheet sheet = workbook.getSheetAt(i);
// 获得行数
int rows = sheet.getLastRowNum() + 1;
Calendar calendar = Calendar.getInstance();
for (int j = 1; j < rows; j++) {
Row row = sheet.getRow(j);
String name = row.getCell(0).getStringCellValue();
String sex = row.getCell(1).getStringCellValue();
String phone = row.getCell(2).getStringCellValue();
String idCardNumber = row.getCell(3).getStringCellValue();
public ResultObj AddPeopleByExcel() throws IOException {
HashMap hashMap = new HashMap();
XSSFWorkbook xssfWorkbook = new XSSFWorkbook("C:\\Users\\admin\\Desktop\\浙江泰源科技有限公司资料整理\\泰源科技人员信息.xlsx");
XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
for (int i = 0; i < sheetAt.getLastRowNum(); i++) {
XSSFRow row = sheetAt.getRow(i);
XSSFCell cellName = row.getCell(0);
XSSFCell celPhone = row.getCell(2);
hashMap.put(cellName.getStringCellValue(),celPhone.getStringCellValue());
}
File file = new File("G:\\front.sql");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
boolean flag = false;
int i = 0;
People people = new People();
people.setName(name);
people.setSex(sex);
people.setPhone(phone);
people.setIdCardNumber(idCardNumber);
PeoplePost peoplePost = new PeoplePost();
while ((tempStr = reader.readLine()) != null) {
if (tempStr.contains("INSERT")&&tempStr.contains("personnelManager_people_info")){
flag = true;
i = 0;
}
if (tempStr.contains("at")){
flag = false;
}
if (flag){
i++;
if (i>=3){
tempStr = tempStr.substring(tempStr.indexOf("=")+1);
tempStr = tempStr.replaceAll("\'","");
}
if (i==3){
people.setPeopleId(Long.valueOf(tempStr));
}
if (i==4){
people.setName(tempStr);
if (hashMap.containsKey(tempStr)){
people.setPhone(hashMap.get(tempStr).toString());
}
}
if (i==10){
people.setIdCardNumber(tempStr);
}
if (i==11){
if (!tempStr.equals("NULL")){
Post post = new Post();
post.setPostId(Long.valueOf(tempStr));
peoplePost.setPeople(people);
peoplePost.setPost(post);
}
}
if (i==13){
people.setIcon(tempStr.substring(tempStr.indexOf("/")+1));
try {
people.setEntryTime(Instant.now());
peopleService.addEntity(people);
peoplePostService.addEntity(peoplePost);
}catch (Exception e){
System.out.println("1");
}
}
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return new ResultObj("成功");
}
@RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResultObj getPeoplePage(@RequestBody PeoplePageableVo peopleDto){
return new ResultObj(peopleService.getList(peopleDto),"success");
......
......@@ -25,7 +25,6 @@ public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificat
@Query("update Post o set o.deleteTag = 1 where o.organizationNode.nodeId=:nodeId or o.nodeLevel like concat('%.',:nodeId,'.%') ")
void deletePostByNodeId(Long nodeId);
@Query(value = "select new com.example.personnelmanager.entity.vo.PostVo(p.postId,p.postName,p.postIntroduction,p.organizationNode,count(ps.people.peopleId)) from " +
"Post p left join PeoplePost ps on p.postId = ps.post.postId where " +
"p.enterprise.enterpriseId =:enterpriseId and p.deleteTag=0 and p.organizationNode.nodeId =:organizationNodeId " +
......
......@@ -28,7 +28,6 @@ import java.util.List;
@Table(name = "organization_node")
@ToString(exclude = {"enterprise","posts","duties","legalEntity","legalEntity"})
@EntityListeners(AuditingEntityListener.class)
@Where(clause = "delete_tag = 0")
public class OrganizationNode {
@Max(value = 0,groups = {GroupSave.class} )
......
......@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity;
import com.example.personnelmanager.common.validIGroup.GroupSave;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.ToString;
......@@ -34,7 +35,6 @@ import java.util.List;
public class People {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "people_id",columnDefinition = "bigint comment '人员编号' ")
private Long peopleId;
......
......@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity;
import com.example.personnelmanager.common.validIGroup.GroupSave;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.DynamicInsert;
......@@ -48,6 +49,10 @@ public class User {
@Column(name = "administrator",columnDefinition = "bool comment '是否超级管理员'")
private boolean administrator;
@Column(name = "repeats_num",columnDefinition = " int(11) not null COMMENT ' 如果用户姓名在数据库内重复,当第二个重复的用户姓名,注册进系统时,该数字加1。例如:张三张三2张三3 '")
@ApiModelProperty(value = "如果用户姓名在数据库内重复,当第二个重复的用户姓名,注册进系统时,该数字加1。例如:张三张三2张三3")
private Integer repeatsNum = 0;
@Column(name = "delete_tag",columnDefinition = "int default 0 comment '删除标记(0为正常,1为被删除)'")
private int deleteTag;
......
package com.example.personnelmanager.entity.commonEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Sort;
/**
......@@ -11,6 +13,8 @@ import org.springframework.data.domain.Sort;
* @data 2020/5/13
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomOrder {
private String coulmn;
......
......@@ -7,12 +7,16 @@ import com.example.personnelmanager.common.utils.HttpClientUtil;
import com.example.personnelmanager.dao.OrganizationNodeRepository;
import com.example.personnelmanager.dao.PostRepository;
import com.example.personnelmanager.entity.OrganizationNode;
import com.example.personnelmanager.entity.Post;
import com.example.personnelmanager.entity.WorkExperience;
import com.example.personnelmanager.entity.vo.OrganizationNodeListVo;
import com.example.personnelmanager.entity.UserDetail;
import com.example.personnelmanager.entity.vo.PostVo;
import com.example.personnelmanager.service.OrganizationNodeService;
import com.example.personnelmanager.service.PostService;
import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
......@@ -42,6 +46,9 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService {
@Autowired
PostRepository postRepository;
@Autowired
PostService postService;
@Autowired
DateCenterJsonUtil dateCenterJsonUtil;
......@@ -194,7 +201,13 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService {
//删除节点以及所有子节点
organizationNodeRepository.deleteorganizationNode(id);
//删除所有被删除节点下的岗位
postRepository.deletePostByNodeId(id);
PredicateBuilder<Post> or = Specifications.or();
or.eq("organizationNode.nodeId",id);
or.like("nodeLevel","%."+id+"%");
List<Post> all = postRepository.findAll(or.build());
all.forEach(post -> {
postService.delete(post.getPostId());
});
//向数据中心修改旧的数据
executorService.submit(() -> {
httpClientUtil.put("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllOrganizationNodeJsonStr(Arrays.asList(one)), "utf-8");
......
......@@ -9,10 +9,7 @@ import com.example.personnelmanager.dao.PeopleRepository;
import com.example.personnelmanager.entity.*;
import com.example.personnelmanager.entity.vo.PeopleVo;
import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo;
import com.example.personnelmanager.service.AgainEntryInformationService;
import com.example.personnelmanager.service.BecomeRegularWorkerService;
import com.example.personnelmanager.service.LeaveInformationService;
import com.example.personnelmanager.service.PeopleService;
import com.example.personnelmanager.service.*;
import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.BeanUtils;
......@@ -65,10 +62,14 @@ public class PeopleServiceImpl implements PeopleService {
@Autowired
ExecutorService executorService;
@Autowired
UserServer userServer;
@Override
public People addEntity(People people) {
UserDetail userDetails = AuthenticationUtils.getAuthentication();
if (peopleRepository.findByPhoneAndEnterprise(people.getPhone(),userDetails.getEnterprise().getEnterpriseId()).size()>0){
List<People> byPhoneAndEnterprise = peopleRepository.findByPhoneAndEnterprise(people.getPhone(), userDetails.getEnterprise().getEnterpriseId());
if (byPhoneAndEnterprise!=null&&byPhoneAndEnterprise.size()>0){
throw new GlobalException("手机号码与其他人员重复");
}
if (people.getTrialEndTime()!=null&&people.getInternshipEndTime().compareTo(Instant.now())>0){
......@@ -95,10 +96,20 @@ public class PeopleServiceImpl implements PeopleService {
}
people.setEnterprise(userDetails.getEnterprise());
People save = peopleRepository.save(people);
//向数据中心插入新的数据
executorService.submit(() -> {
httpClientUtil.post("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllPeopleJsonStr(Arrays.asList(save)), "utf-8");
});
//为新的人员创建账号
User user = new User();
user.setUsername(people.getPhone());
user.setAdministrator(false);
user.setCreateDate(Instant.now());
user.setName(people.getName());
user.setPassword("qwer1234");
user.setEnterprise(people.getEnterprise());
user.setPhone(people.getPhone());
userServer.addEntity(user);
// //向数据中心插入新的数据
// executorService.submit(() -> {
// httpClientUtil.post("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllPeopleJsonStr(Arrays.asList(save)), "utf-8");
// });
return save;
}
......
......@@ -81,6 +81,8 @@ public class PostServiceImpl implements PostService {
return null;
}
@Override
public Post update(Post post) {
Post after = postRepository.save(post);
......
package com.example.personnelmanager.service.impl;
import com.example.personnelmanager.entity.Enterprise;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.entity.UserDetail;
import com.example.personnelmanager.service.UserServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.Instant;
/**
* 自定义用户详情Service
* @author HuangXiahao
......@@ -17,17 +24,46 @@ import org.springframework.stereotype.Service;
* @data 2020/5/20
**/
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserServer userServer;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//如果用户存在数据库中,则直接返回用户
//如果用户不存在数据库中则为用户新建一个用户,并返回
UserDetail userDetail = userServer.selectByUserName(username);
if (userDetail==null){
throw new UsernameNotFoundException("用户名或者密码错误");
}
return userDetail;
}
public UserDetails loadUserByUsername(String username,String phone) throws UsernameNotFoundException {
//如果用户存在数据库中,则直接返回用户
//如果用户不存在数据库中则为用户新建一个用户,并返回
UserDetail userDetail = userServer.selectByUserName(username);
if (userDetail==null){
User user = new User();
user.setUsername(username);
user.setCreateDate(Instant.now());
Enterprise enterprise = new Enterprise();
enterprise.setEnterpriseId(1L);
user.setEnterprise(enterprise);
user.setName(username);
user.setPassword(passwordEncoder.encode("qwer1234"));
user.setPhone(phone);
log.info("用户为:"+user);
User user1 = userServer.addEntity(user);
userDetail = new UserDetail();
BeanUtils.copyProperties(user1,userDetail);
return userDetail;
}
return userDetail;
}
}
......@@ -19,6 +19,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
......@@ -41,6 +42,7 @@ public class UserServerImpl implements UserServer {
@Override
public User addEntity(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setCreateDate(Instant.now());
User addUser = userRepository.save(user);
return addUser;
}
......
......@@ -8,51 +8,52 @@ file:
otherDir: G:/other/
jwtFilePath: G:/other/rsa
center:
ip: 124.70.194.194
serve: http://124.70.194.194:12346
#Eureka设置
eureka:
instance:
#服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
#注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
lease-expiration-duration-in-seconds: 15
lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
instance-id: ${spring.application.name}:${server.port}
prefer-ip-address: true # 是否显示ip前缀
client:
registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
serviceUrl:
defaultZone: http://${center.ip}:10087/eureka/
# 监控页面配置
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
#ribbon负载均衡
ribbon:
ConnectTimeout: 250 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数
ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 20000
feign:
hystrix:
enabled: true
#center:
# ip: 124.70.194.194
# serve: http://124.70.194.194:12346
##Eureka设置
#eureka:
# instance:
# #服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
# #注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
# lease-expiration-duration-in-seconds: 15
# lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
# instance-id: ${spring.application.name}:${server.port}
# prefer-ip-address: true # 是否显示ip前缀
# client:
# registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
# serviceUrl:
# defaultZone: http://${center.ip}:10087/eureka/
## 监控页面配置
#management:
# endpoints:
# web:
# exposure:
# include: '*'
# endpoint:
# health:
# show-details: always
##ribbon负载均衡
#ribbon:
# ConnectTimeout: 250 # 连接超时时间(ms)
# ReadTimeout: 2000 # 通信超时时间(ms)
# OkToRetryOnAllOperations: true # 是否对所有操作重试
# MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
# MaxAutoRetries: 1 # 同一实例的重试次数
# ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
#
#
#hystrix:
# command:
# default:
# execution:
# isolation:
# thread:
# timeoutInMilliseconds: 20000
#feign:
# hystrix:
# enabled: true
# 日志文件相关配置
# level: {com.zity: trance }
#showSql
......@@ -62,4 +63,13 @@ logging:
# 指定包名与日志级别
com.zjty: debug
spring:
datasource:
username: root
password: Huang123+
url: jdbc:mysql://47.106.142.73:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# dao: debug
center:
ip: 124.70.194.194
serve: http://124.70.194.194:11324
\ No newline at end of file
......@@ -4,64 +4,70 @@
# 文件存储路径
file:
imagePath: /opt/jar/workbench/personnel/image/
otherDir: /opt/jar/workbench/personnel/other/
jwtFilePath: /opt/jar/workbench/personnel/other/rsa
server:
serverAddress: 124.70.194.194:${server.port}
imagePath: /opt/jar/personnelManager/image/
#server:
# serverAddress: 124.70.194.194:${server.port}
#
center:
ip: 124.70.194.194
serve: http://124.70.194.194:12346
#Eureka设置
eureka:
instance:
#服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
#注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
lease-expiration-duration-in-seconds: 15
lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
instance-id: ${spring.application.name}:${server.port}
prefer-ip-address: true # 是否显示ip前缀
client:
registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
serviceUrl:
defaultZone: http://${center.ip}:10087/eureka/
# 监控页面配置
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
#ribbon负载均衡
ribbon:
ConnectTimeout: 250 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数
ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
serve: http://124.70.194.194:11324
##Eureka设置
#eureka:
# instance:
# #服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
# #注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
# lease-expiration-duration-in-seconds: 15
# lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
# instance-id: ${spring.application.name}:${server.port}
# prefer-ip-address: true # 是否显示ip前缀
# client:
# registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
# serviceUrl:
# defaultZone: http://${center.ip}:10087/eureka/
## 监控页面配置
#management:
# endpoints:
# web:
# exposure:
# include: '*'
# endpoint:
# health:
# show-details: always
##ribbon负载均衡
#ribbon:
# ConnectTimeout: 250 # 连接超时时间(ms)
# ReadTimeout: 2000 # 通信超时时间(ms)
# OkToRetryOnAllOperations: true # 是否对所有操作重试
# MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
# MaxAutoRetries: 1 # 同一实例的重试次数
# ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
#
#
#hystrix:
# command:
# default:
# execution:
# isolation:
# thread:
# timeoutInMilliseconds: 20000
#feign:
# hystrix:
# enabled: true
## 日志文件相关配置
## level: {com.zity: trance }
##showSql
#logging:
# file: ./log/workbench.log
# level:
# # 指定包名与日志级别
# com.zjty: debug
# dao: debug
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 20000
feign:
hystrix:
enabled: true
# 日志文件相关配置
# level: {com.zity: trance }
#showSql
logging:
file: ./log/workbench.log
level:
# 指定包名与日志级别
com.zjty: debug
spring:
datasource:
username: hxh
password: Qwert123123
url: jdbc:mysql://124.70.145.101:3306/personnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# dao: debug
\ No newline at end of file
......@@ -6,12 +6,12 @@ spring:
application:
name: 人员管理系统
profiles:
active: prod
active: dev
datasource:
url: jdbc:mysql://124.70.194.194:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# url: jdbc:mysql://124.70.194.194:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# url: jdbc:mysql://124.70.194.194:3306/personnelManagerTest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
password: root
username: canal
# password: root
# username: canal
driver-class-name: com.mysql.jdbc.Driver
hikari:
auto-commit: false
......@@ -29,4 +29,3 @@ spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论