同步数据

master
yz 3 months ago
parent 6c8a97dec7
commit 073bfd45cd

@ -32,12 +32,12 @@
<poi.version>4.1.2</poi.version>
<velocity.version>2.3</velocity.version>
<jwt.version>0.9.1</jwt.version>
<!-- <jjwt.version>0.10.8</jjwt.version>-->
</properties>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>

@ -16,6 +16,60 @@
</description>
<dependencies>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.8</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.8</version>
<scope>runtime</scope>
</dependency>
<!--逆向工程-->
<dependency>
<groupId>org.mybatis.generator</groupId>
@ -71,6 +125,10 @@
<version>3.8.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
</dependencies>

@ -0,0 +1,34 @@
package com.ruoyi.web.config.exception;
public class UnAuthorizedException extends RuntimeException {
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public UnAuthorizedException(String message) {
super(message);
}
/**
* Constructs a new runtime exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public UnAuthorizedException(String message, Throwable cause) {
super(message, cause);
}
}

@ -0,0 +1,74 @@
package com.ruoyi.web.config.security;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* jwt
*/
@Getter
@Setter
@ToString
public class JwtUser implements UserDetails {
private String username;
private String password;
private String name;
private String userId;
private int roleId;
private Integer schoolId;
private int classId;
private String schoolName;
private String className;
private int majorId;
private String majorName;
private int collegeId;
private String collegeName;
private List<String> authorityCodes;
private String studentId;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof JwtUser)) return false;
JwtUser user = (JwtUser) o;
return username.equals(user.username);
}
@Override
public int hashCode() {
return Objects.hash(username);
}
}

@ -0,0 +1,79 @@
package com.ruoyi.web.config.security;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
*
*
* @author
*/
@ApiModel("用户登录结果集")
@Setter
@Getter
public class LoginResult {
@ApiModelProperty("用户ID")
private String userId;
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("访问令牌")
private String accessToken;
@ApiModelProperty("角色Id")
private int roleId;
@ApiModelProperty("用户所在班级id")
private int classId;
@ApiModelProperty("用户所在学校id")
private int schoolId;
@ApiModelProperty("用户所在学校名称")
private String schoolName;
@ApiModelProperty("用户权限")
private List<String> authorityCodes;
@ApiModelProperty("用户所在院系")
private int collegeId;
@ApiModelProperty("用户所在专业")
private int majorId;
@ApiModelProperty("用户名")
private String username;
// user.setUserId(dataObject.getStr("userId"));
// user.setName(dataObject.getStr("name"));
// user.setRoleId(dataObject.getInt("roleId"));
// user.setSchoolId(dataObject.getInt("schoolId"));
// user.setClassId(dataObject.getInt("classId"));
// user.setMajorId(dataObject.getInt("majorId"));
// user.setClassName(dataObject.getStr("className"));
// user.setMajorName(dataObject.getStr("majorName"));
// user.setSchoolName(dataObject.getStr("schoolName"));
// user.setCollegeId(dataObject.getInt("collegeId"));
// user.setCollegeName(dataObject.getStr("collegeName"));
/**
*
*
* @param jwtUser
* @param accessToken
* @return LoginResult
*/
public static LoginResult create(JwtUser jwtUser, String accessToken) {
LoginResult result = new LoginResult();
result.setUserId(jwtUser.getUserId());
result.setRoleId(jwtUser.getRoleId());
result.setName(jwtUser.getName());
result.setAccessToken(accessToken);
result.setClassId(jwtUser.getClassId());
result.setSchoolId(jwtUser.getSchoolId());
result.setAuthorityCodes(jwtUser.getAuthorityCodes());
result.setMajorId(jwtUser.getMajorId());
result.setCollegeId(jwtUser.getCollegeId());
result.setUsername(jwtUser.getUsername());
result.setSchoolName(jwtUser.getSchoolName());
return result;
}
}

@ -0,0 +1,217 @@
package com.ruoyi.web.config.security;
import com.ruoyi.web.config.exception.UnAuthorizedException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
@Component
public class TokenProvider {
private final static String SECRET = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAghgsx+OLLThi7c+/HgCaRla8n+/QLHt++uscoK22dMeaVa3WJvRb5C5qtHGzj9V74pI96JpxdWWCN3Zr1QtanQIDAQABAkB2fWRUD1jVMBVS+rPctLnPNPMKTRdzXGv0SC5D3tRfGZqdcfsmZg8hzBVndHxngmwZS73d+hPjofcdefDDnXq1AiEAz/r1AMF7fweN70mbKgBJuTja37puJMsH2Szwrvb5jlcCIQCgIaLZ5d9J7OomL0NwH8ghba/xgBEpKzErfGbFnTfeKwIgc8ptczFFV1DWZb2eJIEqinOr79l0jwl2YiQSD+cyw1sCIHqxCvv1Wx5jPgy/zeYNE+Q5DMP3Ii7u/x+Yk436JiI9AiEAio84hFm44YTUuV7YCYsbyvnCn/vtcAaqZlczbeHlP1I=";
private final static long EXP_TIME = 1000 * 60 * 60 * 4;
private final static String SECRET_ZHIYUN = "zy_wh_mnjy_fp76ckwuczzmb67w0a8x0";
private final static String CURRENT_TO_ZHIYUN = "jVzvfoZU_eFN0CJcFARg0K6DlzTLa7oMWB7lV_y2s7bkv2Bem0281wEwlJp5afhsmM-Ynwvh3mAUTpwblGEz1A";
/**
* jwtToken
*
* @param jwtToken jwtToken
* @return jwt
*/
public static JwtUser getJWTUser(String jwtToken) {
jwtToken = jwtToken.replace("Bearer ", "");
try {
Claims claims = Jwts.parser()
.setSigningKey(
new SecretKeySpec(
SECRET.getBytes("UTF-8"),
SignatureAlgorithm.HS512.getJcaName()
)
)
.parseClaimsJws(jwtToken)
.getBody();
JwtUser jwtUser = new JwtUser();
jwtUser.setName(claims.get("name") == null ? "" : claims.get("name").toString());
jwtUser.setUserId(claims.get("userId") == null ? "" : claims.get("userId").toString());
jwtUser.setRoleId(Integer.valueOf(claims.get("roleId") == null ? "0" : claims.get("roleId").toString()));
jwtUser.setClassId(Integer.valueOf(claims.get("classId") == null ? "0" : claims.get("classId").toString()));
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId") == null ? "0" : claims.get("schoolId").toString()));
jwtUser.setUsername(claims.get("username") == null ? "" : claims.get("username").toString());
jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
return jwtUser;
} catch (ExpiredJwtException e1) {
throw new ExpiredJwtException(null, null, "token过期");
} catch (UnsupportedJwtException e2) {
throw new UnsupportedJwtException("不支持的token");
} catch (MalformedJwtException e3) {
throw new MalformedJwtException("token格式错误");
} catch (SignatureException e4) {
throw new SignatureException("签名失败");
} catch (Exception e) {
throw new UnAuthorizedException("无效token");
}
}
public static String createToken(JwtUser jwtUser) {
Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
return Jwts.builder()
.claim("userId", jwtUser.getUserId())
.claim("roleId", jwtUser.getRoleId())
.claim("name", jwtUser.getName())
.claim("classId", jwtUser.getClassId())
.claim("schoolId", jwtUser.getSchoolId())
.claim("username", jwtUser.getUsername())
.claim("authorityCodes", jwtUser.getAuthorityCodes())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expiration)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
public static String createZHIYUNToken(JwtUser jwtUser) {
Key key = Keys.hmacShaKeyFor(CURRENT_TO_ZHIYUN.getBytes());
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
return Jwts.builder()
.claim("userId", jwtUser.getUserId())
.claim("roleId", jwtUser.getRoleId())
.claim("name", jwtUser.getName())
.claim("classId", jwtUser.getClassId())
.claim("schoolId", jwtUser.getSchoolId())
.claim("username", jwtUser.getUsername())
.claim("majorId", jwtUser.getMajorId())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expiration)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
public static void main(String[] args) {
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiMTgyOCIsInN0dWRlbnRJZCI6IjQ2MzciLCJwYXNzd29yZCI6IjEyM3F3ZSIsImNsYXNzSWQiOiIyMTYiLCJpY2lidENsYXNzSWQiOjIwOSwibWFqb3IiOiLkuqflk4HmvJTnpLrkuJPkuJoiLCJzY2hvb2wiOiLlpKnmi6nlpKflraYiLCJzY2hvb2xJZCI6IjIzMiIsIm5hbWUiOiJ0enMwMDgiLCJzdHVkZW50Tm8iOiJ0enMwMDgiLCJhcHBsaWNhdGlvbklkIjoiNDYiLCJjbGFzcyI6IuWkqeaLqea8lOekujbnj60iLCJ1c2VybmFtZSI6InR6czAwOCJ9.R7D6B9zDbtqb2lXnZMG3iAo-6zBwTfOi1BFbwMzqKfI");
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiIzIiwic2V4Ijoi55S3IiwidXNlcklkIjoiMTg0NSIsInBhc3N3b3JkIjoiMTIzcXdlIiwidGVhY2hlcklkIjoiMzIzIiwibWFqb3IiOiLkuqflk4HmvJTnpLrkuJPkuJoiLCJzY2hvb2wiOiLlpKnmi6nlpKflraYiLCJzY2hvb2xJZCI6IjIzMiIsIm5hbWUiOiJ0enQwMDEiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwidXNlcm5hbWUiOiJ0enQwMDEifQ.rLKb20eOCN4KkyFQ5ZH8E56TsUVjBl2865nwnxYpsyk");
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiNDg3Iiwic3R1ZGVudElkIjoiNDA0OCIsInBhc3N3b3JkIjoiMTIzcXdlIiwiY2xhc3NJZCI6IjIxMSIsImljaWJ0Q2xhc3NJZCI6MjA0LCJtYWpvciI6IuS6p-WTgea8lOekuuS4k-S4miIsInNjaG9vbCI6IuWkqeaLqeWkp-WtpiIsInNjaG9vbElkIjoiMjMyIiwibmFtZSI6InR6czAwMSIsInN0dWRlbnRObyI6InR6czAwMSIsImFwcGxpY2F0aW9uSWQiOiIxMTkiLCJjbGFzcyI6IuWkqeaLqea8lOekujHnj60iLCJ1c2VybmFtZSI6InR6czAwMSJ9.p6Uu15B1zNzuuCMOkDTkMksvjU6EOvGWprMWuJB0OII");
JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiNDg3Iiwic3R1ZGVudElkIjoiNDA0OCIsInBhc3N3b3JkIjoiMTIzcXdlIiwiY2xhc3NJZCI6IjIxMSIsImljaWJ0Q2xhc3NJZCI6MjA0LCJtYWpvciI6IuS6p-WTgea8lOekuuS4k-S4miIsInNjaG9vbCI6IuWkqeaLqeWkp-WtpiIsInNjaG9vbElkIjoiMjMyIiwibmFtZSI6InR6czAwMSIsInN0dWRlbnRObyI6InR6czAwMSIsImFwcGxpY2F0aW9uSWQiOiI0NiIsImNsYXNzIjoi5aSp5oup5ryU56S6MeePrSIsInVzZXJuYW1lIjoidHpzMDAxIn0.DSjkZUCc7115znVNGZda6ZBXWfDGoL60MKpJZrwmBv8");
// JwtUser jwtUser = getJWTUserByZhiYun("");
System.out.println(jwtUser);
}
/**
* token
*/
public static JwtUser getJWTUserByZhiYun(String token) {
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi57uP566h5a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6MjI4LCJtZDVQd2QiOiI0Ni1GOS00Qy04RC1FMS00Ri1CMy02Ni04MC04NS0wNy02OC1GRi0xQi03Ri0yQSIsInJvbGVpZCI6IjQiLCJzZXgiOiLnlLciLCJ1c2VySWQiOiIzOTYxOCIsInN0dWRlbnRJZCI6IjMzNzczIiwicGFzc3dvcmQiOiIxMjNxd2UiLCJjbGFzc0lkIjoiMTg1MSIsImljaWJ0Q2xhc3NJZCI6MTIyMCwibWFqb3IiOiLph5Hono3kuJPkuJoiLCJzY2hvb2wiOiLlub_lt57ljY7llYbogYzkuJrlrabpmaIiLCJzY2hvb2xJZCI6IjEyMSIsIm5hbWUiOiIzMjE3NjA0MTMiLCJzdHVkZW50Tm8iOiIzMjE3NjA0MTMiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwiY2xhc3MiOiIyMemHkeiejeacjeWKoeS4jueuoeeQhjTnj60iLCJ1c2VybmFtZSI6IjMyMTc2MDQxMyJ9.0fgpRXUVl664QUFv96Cb7VJu-V8ea8mPB7RZ1UnWqq0";
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi57uP566h5a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6MjI4LCJtZDVQd2QiOiI0Ni1GOS00Qy04RC1FMS00Ri1CMy02Ni04MC04NS0wNy02OC1GRi0xQi03Ri0yQSIsInJvbGVpZCI6IjQiLCJzZXgiOiLnlLciLCJ1c2VySWQiOiIzOTYxOCIsInN0dWRlbnRJZCI6IjMzNzczIiwicGFzc3dvcmQiOiIxMjNxd2UiLCJjbGFzc0lkIjoiMTg1MSIsImljaWJ0Q2xhc3NJZCI6MTIyMCwibWFqb3IiOiLph5Hono3kuJPkuJoiLCJzY2hvb2wiOiLlub_lt57ljY7llYbogYzkuJrlrabpmaIiLCJzY2hvb2xJZCI6IjEyMSIsIm5hbWUiOiIzMjE3NjA0MTMiLCJzdHVkZW50Tm8iOiIzMjE3NjA0MTMiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwiY2xhc3MiOiIyMemHkeiejeacjeWKoeS4jueuoeeQhjTnj60iLCJ1c2VybmFtZSI6IjMyMTc2MDQxMyJ9.0fgpRXUVl664QUFv96Cb7VJu-V8ea8mPB7RZ1UnWqq0";
try {
Claims claims = Jwts.parser()
.setSigningKey(Keys.hmacShaKeyFor(SECRET_ZHIYUN.getBytes()))
.parseClaimsJws(token)
.getBody();
JwtUser jwtUser = new JwtUser();
System.out.println(claims.toString());
jwtUser.setName(claims.get("name") == null ? null : claims.get("name").toString());
jwtUser.setUserId(claims.get("userId") == null ? null : claims.get("userId").toString());
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid") == null ? "0" : claims.get("roleid").toString()));
jwtUser.setClassId(Integer.valueOf(claims.get("classId") == null ? "0" : claims.get("classId").toString()));
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId") == null ? "0" : claims.get("schoolId").toString()));
jwtUser.setClassName(claims.get("class") == null ? null : claims.get("class").toString());
jwtUser.setSchoolName(claims.get("school") == null ? "0" : claims.get("school").toString());
jwtUser.setUsername(claims.get("username").toString());
jwtUser.setPassword(claims.get("password").toString());
if (org.apache.commons.lang3.StringUtils.isNotBlank((String) claims.get("studentNo"))) {
String studentNo = (String) claims.get("studentNo");
jwtUser.setStudentId(studentNo);
}
return jwtUser;
} catch (Exception e) {
throw new UnAuthorizedException("token解析失败");
}
}
//生成智云平台32字节密钥
// public static void main(String[] args) {
//// String prefix = "zy_wh_mnjy_";
//// String generatedKey = generateKey(prefix);
//// System.out.println("Generated Key: " + generatedKey);
//// getJWTUserByZhiYun(null);
//
//
////生成一个新的长度为512字节的随机密钥供智云平台解析token
//// int keyLength = 512; // 根据您的要求进行调整
//// KeyGenerator keyGenerator;
//// try {
//// keyGenerator = KeyGenerator.getInstance("HmacSHA512");
//// keyGenerator.init(keyLength);
//// SecretKey secretKey = keyGenerator.generateKey();
//// byte[] secretBytes = secretKey.getEncoded();
//// String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
////
//// System.out.println("Generated Secret: " + secret);
//// } catch (NoSuchAlgorithmException e) {
//// e.printStackTrace();
//// }
//
// JwtUser user = new JwtUser();
// user.setUserId("486");
// user.setRoleId(3);
// user.setUsername("tzt006");
// user.setSchoolId(1);
// user.setSchoolName("天择大学");
// user.setCollegeId(1);
// user.setCollegeName("演示学院");
// user.setMajorId(1);
// user.setMajorName("产品演示专业");
// String token = createZHIYUNToken(user);
// System.out.println(token);
// }
public static String generateKey(String prefix) {
String characters = "0123456789abcdefghijklmnopqrstuvwxyz";
SecureRandom random = new SecureRandom();
StringBuilder keyBuilder = new StringBuilder(prefix);
while (keyBuilder.length() < 32) {
int randomIndex = random.nextInt(characters.length());
char randomChar = characters.charAt(randomIndex);
keyBuilder.append(randomChar);
}
return keyBuilder.toString();
}
/**
*
*
* @param request request
* @return JwtUser
*/
public static JwtUser getJWTUser(HttpServletRequest request) {
if (!(request.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken)) {
throw new UnAuthorizedException("身份认证失败");
}
String jwtToken = request.getHeader("Authorization");
if (StringUtils.hasText(jwtToken)) {
return getJWTUser(jwtToken);
}
throw new UnAuthorizedException("身份认证失败");
}
}

@ -1,20 +1,32 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import java.util.Set;
import java.util.*;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.biemo.business.domain.ZYUserInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.web.config.exception.UnAuthorizedException;
import com.ruoyi.web.config.security.JwtUser;
import com.ruoyi.web.config.security.LoginResult;
import com.ruoyi.web.config.security.TokenProvider;
import com.ruoyi.web.util.RsaUtil;
import com.ruoyi.web.util.TzApi;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
@ -25,6 +37,9 @@ import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
*
*
@ -50,6 +65,9 @@ public class SysLoginController {
@Autowired
private SysUserMapper sysUserMapper;
@Resource
private AuthenticationManagerBuilder authenticationManagerBuilder;
/**
*
*
@ -57,12 +75,16 @@ public class SysLoginController {
* @return
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody) {
@ApiOperation("登录接口")
public AjaxResult login(@RequestBody(required = false) LoginBody loginBody,
@RequestParam(required = false) String TOKEN) {
if (StringUtils.isBlank(TOKEN)) {
String username = loginBody.getUsername();
SysUser sysUser = sysUserMapper.selectUserByStudentNumber(username);
// SysUser sysUser = sysUserMapper.selectUserByUserName(loginBody.getUsername());
String roleId= String.valueOf(sysUserRoleMapper.selectRoleIdByUserId(sysUser.getUserId()));
if (("student".equals(loginBody.getRole()) && "2".equals(roleId))
|| ("teacher".equals(loginBody.getRole()) && "100".equals(roleId)) || "admin".equals(loginBody.getUsername())) {
if (("student".equals(loginBody.getRole()) && "2".equals(roleId)) || ("teacher".equals(loginBody.getRole()) && "100".equals(roleId)) || "admin".equals(loginBody.getUsername())) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
@ -74,6 +96,37 @@ public class SysLoginController {
return ajax;
}
return new AjaxResult(403,"用户权限不正确");
} else { // 2、智云单点登录
JwtUser jwtUser;
jwtUser = TokenProvider.getJWTUserByZhiYun(TOKEN);
jwtUser = TzApi.foreignExchangeTradingLogin(jwtUser.getUsername(), jwtUser.getPassword());
if (jwtUser == null) {
throw new UnAuthorizedException("用户名或密码错误");
}
Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenProvider.createToken(jwtUser);
LoginResult loginResult = LoginResult.create(jwtUser, token);
Map<String, Object> map = new HashMap<>();
map.put("name", loginResult.getName());
map.put("username", loginResult.getUsername());
map.put("roleId", loginResult.getRoleId());
map.put("schoolId", loginResult.getSchoolId());
if (StringUtils.isNotBlank(loginResult.getUserId())) {
map.put("classId", loginResult.getClassId());
}
map.put("userId", loginResult.getUserId());
map.put("token", token);
SysUser sysUser = sysUserMapper.selectUserByUserName(String.valueOf(map.get("username")));
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String tokenWbdsj = loginService.login(sysUser.getUserName(), "123456", "1",
String.valueOf(UUID.randomUUID()));
ajax.put(Constants.TOKEN, tokenWbdsj);
ajax.put("deptId",sysUser.getDeptId());
ajax.put("UserId",sysUser.getUserId());
return ajax;
}
}
/**
@ -115,4 +168,44 @@ public class SysLoginController {
List<SysMenu> menus = menuService.selectTeacherMenuTreeByUserId(user);
return AjaxResult.success(menuService.buildMenus(menus));
}
// @ApiOperation("根据用户Code查询该用户是否存在个人赛用户数据存在则返回不存在则新增后返回用于智云3.0创建用户后调用该接口创建用户个人赛")
// @PostMapping("/checkOrCreateForexSimulationUser")
// public String checkOrCreateForexSimulationUser(@RequestBody List<ZYUserInfo> zyUserInfoList,
// @RequestParam String systemOwner) {
// System.out.println(systemOwner);
// List<SysUser> users = new ArrayList<>();
// for (int i = 0; i < zyUserInfoList.size(); i++) {
// ZYUserInfo zyUserInfo = zyUserInfoList.get(i);
// Integer zyUserId = zyUserInfo.getUserId();
// String username = zyUserInfo.getUsername(); // studentid
// String name = zyUserInfo.getName();
// String password = zyUserInfo.getPassword();
// Integer roleId = zyUserInfo.getRoleId(); //3教师 4学生
//
// SysUser userInfo = sysUserMapper.selectUserById(Long.valueOf(zyUserId));
// if (userInfo!=null) {
// continue;
// }
// SysUser stuUser = new SysUser();
// stuUser.setUserid(IdUtil.randomUUID());
// stuUser.setStudentId(zyUserInfo.getUsername());
// stuUser.setName(name);
// stuUser.setUsername(username);
// stuUser.setClassId(zyUserInfo.getClassId().toString());
// stuUser.setPassword(password);
// stuUser.setPhone(zyUserInfo.getPhone());
// stuUser.setMajor(zyUserInfo.getMajorName());
// stuUser.setRoleId(roleId);
// stuUser.setSchoolId(zyUserInfo.getSchoolId().toString());
// stuUser.setSchoolName(zyUserInfo.getSchoolName());
// stuUser.setCreateTime(new Date());
// users.add(stuUser);
// }
// if (users.isEmpty()) {
// return "账号已全部存在";
// }
// userInfoMapper.batchInsertUserInfo(users);
// return "ok";
// }
}

@ -0,0 +1,46 @@
package com.ruoyi.web.util;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
public class CacheProvider {
private Cache<String, Object> cache = null;
public CacheProvider(Integer expire, Integer maxSize) {
/**
* expireAfterAccess(long, TimeUnit) 访
*         expireAfterWrite(long, TimeUnit)
*/
if(cache==null){
cache = Caffeine.newBuilder()
.expireAfterWrite(expire, TimeUnit.SECONDS)
.maximumSize(maxSize)
.build();
}
}
public long getSize(){
return cache.estimatedSize();
}
public void put(String key,String value){
cache.put(key, value);
}
public void put(String key,Object value){
cache.put(key, value);
}
public Object get(String key){
return cache.getIfPresent(key);
}
public Object get(String key, Function<? super String, ? extends Object> fc){
return cache.get(key,fc);
}
public void remove(String key){
cache.invalidate(key);
}
}

@ -0,0 +1,202 @@
package com.ruoyi.web.util;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@Slf4j
public class HttpUtils {
public static String CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
// 发送GET请求
public static String sendGet(String url) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
// 发送POST请求
public static JSONObject sendPost(String url, String paramStr) throws IOException {
try {
JSONObject ret = new JSONObject();
HttpPost method = new HttpPost(url);
StringEntity entity = new StringEntity(paramStr, "utf-8");
entity.setContentEncoding("UTF-8");
if (StringUtils.isEmpty(CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED))
entity.setContentType("application/json");
else
entity.setContentType(CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
method.setEntity(entity);
int timeout = 60000;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.build();
method.setConfig(requestConfig);
HttpClient client = HttpClients.createDefault();
HttpResponse resp = client.execute(method);
int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
return null;
}
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
ret.set("statusCode",statusCode);
if(StringUtils.isNotEmpty(respString)){
ret.set("respString",respString);
}
return ret;
}catch (Exception e) {
e.printStackTrace();
log.info("接口请求失败,失败原因:"+e.getMessage());
}
return null;
}
// 发送POST请求
public static JSONObject sendPost(String url, String paramStr, String contentType, String token) throws IOException {
try {
JSONObject ret = new JSONObject();
HttpPost method = new HttpPost(url);
StringEntity entity = new StringEntity(paramStr, "utf-8");
entity.setContentEncoding("UTF-8");
if (StringUtils.isEmpty(contentType))
entity.setContentType("application/json");
else
entity.setContentType(contentType);
if (StringUtils.isNotEmpty(token)) {
method.setHeader("Authorization", "Bearer " + token);
}
method.setEntity(entity);
int timeout = 60000;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.build();
method.setConfig(requestConfig);
HttpClient client = HttpClients.createDefault();
HttpResponse resp = client.execute(method);
int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
return null;
}
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
ret.set("statusCode",statusCode);
if(StringUtils.isNotEmpty(respString)){
ret.set("respString",respString);
}
return ret;
}catch (Exception e) {
e.printStackTrace();
log.info("接口请求失败,失败原因:"+e.getMessage());
}
return null;
}
// 发送GET请求 携带Token
public static String sendGet(String url, String token) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
// 添加token到请求头部
connection.setRequestProperty("Authorization", "Bearer " + token);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
// public static String sendPostRequestWithMultipartFile(String url, MultipartFile file,String token) throws IOException {
public static String sendPostRequestWithMultipartFile(String url, MultipartFile file) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", "Bearer " + null);
String originalFilename = file.getOriginalFilename();
// 将MultipartFile转换为HttpEntity
HttpEntity reqEntity = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8)
.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename())
.build();
httpPost.setEntity(reqEntity);
// 执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 处理响应
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
return responseString;
} finally {
response.close();
}
}
}
}

@ -0,0 +1,150 @@
package com.ruoyi.web.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RsaUtil {
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRehqqa1eLnTL3BSRq3zmB+Yw7nLAMAZ0G+FpoGP0eFLc0JVC2P2sfkCJJjH2cOmoLcUFjHfDcHzMNyl4wmNTMeXhpvK3v2ha1ufZnGmoMd9d4+1R/t/pZdxXXzkQMN2012X/KIojluEJmrIXLUM0zjOTABSMlTY6TPfSrmuXyGwIDAQAB";
private static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJF6GqprV4udMvcFJGrfOYH5jDucsAwBnQb4WmgY/R4UtzQlULY/ax+QIkmMfZw6agtxQWMd8NwfMw3KXjCY1Mx5eGm8re/aFrW59mcaagx313j7VH+3+ll3FdfORAw3bTXZf8oiiOW4QmashctQzTOM5MAFIyVNjpM99Kua5fIbAgMBAAECgYBtr3fNiHOQg6z6jLkBj18nvYTbKW+fDdRcfgKEPFsURCBBw+TQFI7rVFxVwgSvN2ffSrw3RErnXOq8ehl8YK8IfPWleMTXkuGB4QDptou3S7aJ4OlK+p5YOsjVEgnzJ3J7gPUYJRGAX59G+EbEnHKvoTQQjlQ4EaFqp77ba+SN+QJBAM1rre1TSSIuZd7biS4d0znVDRA3Zv/AnpmSaLZODU6p70DnPn3WCf5LNJGsS+Bt1xkq/EHzhpspjy/IfJrZOO8CQQC1S/vrpm8+WsXp8FAlvuQ+UOR1UlMs4WMokVMSOcPcgG2Iab8f1UcD9GptjBjORKiloQBpjG/+FXp2VJPd7yGVAkBvmRRAXoLYwwQs8m+wUhuyy3/xU2ftgaOoItYoVHb+SWvlgrt8eY+sSwcgLM57+rBkx+mLmtWB7i4P84deSKyZAkBYJ5FgnXY8MLFJtoOSRwb+0iC0d4pgKVwo7rkhBJubTYt1KE458V/tqVxS1it9qN8EYowrxpDyUIlSnn+kC9IdAkAH6TkJw2tb4N7rIvcZWjd74EBNQdP0FzvZWU2rE6SGqj87yWDKOKGKWu/hz84DCSkyltII4uB+YasJhsgsJnjb";
public static void main(String[] args) throws Exception {
// System.out.println("\n");
// RsaKeyPair keyPair = generateKeyPair();
// System.out.println("公钥:" + keyPair.getPublicKey());
// System.out.println("私钥:" + keyPair.getPrivateKey());
//System.out.println("\n");
String text1 = encryptByPublicKey("123qwe");
// String text1 = encryptByPrivateKey("123");
System.out.println(text1);
//String text1 = "Bs+MJo8yrGxvwD/G5QGTihU6lh/PjaDKQNxBDs66GQrNXoX0ttzX0grYFxWh8MibHkHikkw8rLsoxXk6bQOzs0eHst/yzj823sTZRDBYdx0oYoEKeda7s7xjYheq4nBnHJn8HVkQbYtchddRRfKVcwyBrUQquhlnzmnfZQ98QiU=";
// String text1 = "CP7GpqY3Tw3DSazqwMHvlRys0/RARfjNL0fgw5IEXEHdZB2K+7G8Ro+wVAm9fiViMba3KcQidG5g244RrpD0HJc/g6PVW4kn81xx1WHjW0SgVUUrsjj4RgHUnUyY/lN0506Ng945svGrGd6pXb+XdtETv4ZKau5EHdR6L/TOR8I=";
// String text1 = "dWRzqk2DC/rm55B+m1Is4mwTnPoc3qoDIZ41Plie6s4vsJwDdHzoWhnIx1pfdFAwEZ3eQ6FV7tcfHJwHDFzNal15e1c2+EFThmWdqdgGNCXttH/c/fsmzaXda5kQRzQxqbhvF96KmJKtshzq23766iLV1Vm3KUsvB6c7bP5yKYc=";
//String text2 = decryptByPrivateKey(text1);
// String text2 = decryptByPrivateKey("R/t6KFVPbCgYSVlYJ4ULuFFwn29/RlLo/IBeXqdtwm0ulIcG0iTDqbCNcQZChE8iN/AL7S4MoGL/HWZArEqAz4BdDmYgLggykX/hhu1fue7tpefyVEnW5TF27rFBCxo1cH0kB1VP0FbwlWHDqG1GCnHOBZbS6j4yUTqu41WBmq4=");
// System.out.println(text2);
}
public static String encryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeBase64String(result);
}
/**
*
*
* @param text
* @return /
* @throws Exception /
*/
public static String encryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(result);
}
public static String decryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
public static String decryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
* RSA
*
* @return /
* @throws NoSuchAlgorithmException /
*/
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static String formatHash(String hash) {
StringBuilder formattedHash = new StringBuilder();
for (int i = 0; i < hash.length(); i += 2) {
formattedHash.append(hash.substring(i, i + 2));
if (i < hash.length() - 2) {
formattedHash.append("-");
}
}
return formattedHash.toString();
}
/**
* RSA
*/
public static class RsaKeyPair {
private final String publicKey;
private final String privateKey;
public RsaKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}

@ -0,0 +1,248 @@
package com.ruoyi.web.util;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.web.config.security.JwtUser;
import com.ruoyi.web.config.security.TokenProvider;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TzApi {
private final static String API_URL = "http://Cloud.sztzjy.com";
private final static String NEW_API_URL = "http://zycloud.sztzjy.com:9090";
// private final static String NEW_API_URL = "http://localhost:9090";
private final static String LOGIN_URL = NEW_API_URL + "/server/account/findByUsernameAndPwd.json";
private final static String GET_CLASS = NEW_API_URL + "/server/account/findClassesBySchoolId.json";
private final static String GET_MAJOR = NEW_API_URL + "/server/account/findMajorsBySchoolId.json";
private final static String GET_CLASS_BY_MAJOR = NEW_API_URL + "/server/account/getClassListByMajorId.json";
private final static String GET_STUDENT_BY_ClALL = NEW_API_URL + "/server/account/getStudentsByClassId.json";
private final static String GET_STUDENT_BY_KEYWORD = NEW_API_URL + "/server/account/getStudentByKeyword.json";
private final static String PAGE_STUDENT_BY_KEYWORD = NEW_API_URL + "/server/account/pagedListStudentByClassId.json";
// 智云接口调用token加入缓存默认1小时过期
private static CacheProvider cacheProvider = new CacheProvider(2400, 6000);
public static JwtUser foreignExchangeTradingLogin(String userName, String password) {
try {
String requestBody = "username=" + URLEncoder.encode(userName, "UTF8") +
"&password=" + URLEncoder.encode(password, "UTF8");
JSONObject object = HttpUtils.sendPost(
LOGIN_URL,
requestBody,
HttpUtils.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED,
null);
if (object == null) {
throw new IllegalArgumentException("登录失败");
}
int code = object.getInt("statusCode");
if (code != HttpStatus.HTTP_OK) {
throw new IllegalArgumentException("登录失败");
}
JSONObject jsonObject = object.getJSONObject("respString");
JSONObject dataObject = jsonObject.getJSONObject("data");
JwtUser user = new JwtUser();
user.setUserId(dataObject.getStr("userid"));
user.setName(dataObject.getStr("name"));
String roleName = dataObject.getStr("rolename");
Integer roleId = roleName.equals("学生") ? 4 : 3;
user.setRoleId(roleId);
user.setSchoolId(dataObject.getInt("schoolid"));
if(roleId==4){
user.setClassId(dataObject.getInt("classid"));
user.setClassName(dataObject.getStr("classname"));
}
// user.setMajorId(dataObject.getStr("majorid"));
user.setMajorName(dataObject.getStr("majorname"));
user.setSchoolName(dataObject.getStr("schoolname"));
user.setCollegeId(dataObject.getInt("collegeid"));
user.setCollegeName(dataObject.getStr("collegename"));
user.setUsername(userName);
user.setPassword(password);
return user;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Map<String, Object>> GetClassBySchoolIdForForeignExchangeTrading(JwtUser user) {
String token = getToken(user);
String url = GET_CLASS+"?schoolId=" + user.getSchoolId();
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetMajorIdForForeignExchangeTrading(JwtUser user) {
String token = getToken(user);
String url = GET_MAJOR+"?schoolId=" + user.getSchoolId();
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetClassByMajorIdForForeignExchangeTrading(JwtUser user, String majorId) {
String token = getToken(user);
String url = GET_CLASS_BY_MAJOR + "?majorId=" + majorId;
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetStudentInfoByClassIdForForeignExchangeTrading(String classIds, JwtUser user) {
String token = getToken(user);
String url = GET_STUDENT_BY_ClALL + "?classList=" + classIds;
return getStudentsFromApi(url, token);
}
public static List<Map<String, Object>> GetStudentInfoByKeywordForForeignExchangeTrading(JwtUser user, String keyword) throws UnsupportedEncodingException {
String token = getToken(user);
String url = GET_STUDENT_BY_KEYWORD + "?keyword=" + URLEncoder.encode(keyword,"UTF-8") +"&schoolId="+user.getSchoolId();
return getStudentsFromApi(url, token);
}
public static PageInfo<Map<String, Object>> PagedListStudentInfoByClassIdForForeignExchangeTrading(JwtUser user, String classIds, int page, int size) {
String token = getToken(user);
String url = PAGE_STUDENT_BY_KEYWORD + "?classList=" + classIds + "&page=" + page + "&size=" + size;
return getPageDataFromApi(url, token);
}
public static List<Map<String, Object>> getDataFromApi(String url, String token) {
List<Map<String, Object>> dataList = new ArrayList<>();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode dataNode = jsonNode.get("data");
if (dataNode.isArray()) {
for (JsonNode node : dataNode) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", node.get("classid").asText());
dataMap.put("name", node.get("classname").asText());
dataList.add(dataMap);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return dataList;
}
public static List<Map<String, Object>> getStudentsFromApi(String url, String token) {
List<Map<String, Object>> dataList = new ArrayList<>();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode dataNode = jsonNode.get("data");
if (dataNode.isArray()) {
for (JsonNode node : dataNode) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", node.get("userid").asText());
dataMap.put("name", node.get("name").asText());
dataMap.put("majorName",node.get("majorname").asText());
dataMap.put("className",node.get("classname").asText());
dataMap.put("classId",node.get("classid").asText());
dataMap.put("studentNo",node.get("studentno").asText());
dataList.add(dataMap);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return dataList;
}
public static PageInfo<Map<String, Object>> getPageDataFromApi(String url, String token) {
PageInfo pageInfo = new PageInfo();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode resultNode = jsonNode.get("content");
if (resultNode != null) {
pageInfo.setPages(resultNode.get("totalPage").asInt());
pageInfo.setTotal(resultNode.get("totalRow").asInt());
pageInfo.setPageNum(resultNode.get("pageNumber").asInt());
pageInfo.setPageSize(resultNode.get("pageSize").asInt());
JsonNode retNode = resultNode.get("list");
List<Map<String,Object>> dataList = new ArrayList<>();
if(retNode.isArray()){
for(JsonNode node: retNode){
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", node.get("userid").asText());
dataMap.put("name", node.get("name").asText());
dataMap.put("studentNo", node.get("studentno").asText());
dataMap.put("className", node.get("classname").asText());
dataMap.put("majorName", node.get("majorname").asText());
dataMap.put("classId", node.get("classid").asText());
dataList.add(dataMap);
}
}
pageInfo.setList(dataList);
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return pageInfo;
}
private static String getToken(JwtUser user) {
try {
String access_token;
access_token = (String) cacheProvider.get(user.getUserId() + user.getUsername());
if (StringUtils.hasText(access_token)) {
System.out.println("-------->>> 从缓存中获取 access_token【成功】");
} else {
access_token = TokenProvider.createZHIYUNToken(user);
cacheProvider.put(user.getUserId() + user.getUsername(), access_token);
System.out.println("-------->>> 从远程获取 access_token【成功】");
}
return access_token;
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public static void main(String[] args) {
JwtUser user = new JwtUser();
user.setUserId("486");
user.setRoleId(3);
user.setUsername("tzt006");
user.setSchoolId(1);
user.setSchoolName("天择大学");
user.setCollegeId(1);
user.setCollegeName("演示学院");
user.setMajorId(1);
user.setMajorName("产品演示专业");
PagedListStudentInfoByClassIdForForeignExchangeTrading(user, "7", 1, 10);
}
}

@ -1,4 +1,4 @@
## 数据源配置
### 数据源配置
spring:
data:
mongodb:
@ -87,8 +87,8 @@ report:
#################重庆二师配置
#项目相关配置
#数据源配置
# 项目相关配置
# 数据源配置
#spring:
# data:
# mongodb:

@ -64,6 +64,7 @@ spring:
# 地址
host: 120.78.220.29
port: 6379
password: stztjy@2017.com
# host: 10.3.116.99
# port: 6379
@ -85,7 +86,8 @@ token:
# 令牌自定义标识
header: Authorization
# 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz
# secret: abcdefghijklmnopqrstuvwxyz
secret: abcdefghijklmnopqrstuvwxyzoasdhualehrgiuslvbkauhrvurbnlvkaurhblajrnblakrubnlkfjnluarnlkvbjbladfkj
# 令牌有效期默认30分钟
expireTime: 1440

@ -11,6 +11,7 @@
<!-- 生成的Java模型是否支持序列化 -->
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
<property name="commentGenerator" value="org.mybatis.generator.config.CommentGenerator"/>
</javaModelGenerator>
<!-- 配置Mapper XML文件的位置-->

@ -99,6 +99,7 @@ public class DocInfoController extends BaseController {
@GetMapping("/getWordCloudByCateId/{categoryId}")
public AjaxResult getWordCloudByCateId(@PathVariable String categoryId){
System.out.println("进来了 开始****************");
List<WordCloudItem> wordCloudItems = docInfoService.getWordCloudByCateId(categoryId);
return AjaxResult.success(wordCloudItems);

@ -0,0 +1,21 @@
package com.ruoyi.biemo.business.domain;
import lombok.Data;
@Data
public class ZYUserInfo {
private String username;
private String password;
private String name;
private Integer userId;
private Integer roleId;
private Integer schoolId;
private String schoolName;
private Integer classId;
private String className;
private String phone;
private Long collegeId;
private String collegeName;
private Long majorId;
private String majorName;
}

@ -55,7 +55,9 @@ public class DocInfoService extends EsService<DocInfo> {
@Override
protected DocInfo loadData(SearchSourceBuilder context, SearchHit hit) {
System.out.println("第八步 进入loadData");
String id = hit.getId();
System.out.println("hit.getId()222===========>:" + id);
if (Objects.isNull(id) || StringUtil.isEmpty(id)) return null;
System.out.println("hit.getId()===========>:" + id);
DocInfo byId = mongoHelper.findById(id, DocInfo.class);
@ -468,13 +470,13 @@ public class DocInfoService extends EsService<DocInfo> {
DocInfo docInfo = new DocInfo();
docInfo.setCateId(categoryId);
if (categoryId.equals("631dfec580d94e2b7b697d4a")) {
System.out.println("cateID=======>" + categoryId);
System.out.println("第一步:cateID=======>" + categoryId +"进入selectDocInfoList方法");
}
List<DocInfo> docInfoList = selectDocInfoList(docInfo);
if (docInfoList == null) {
System.out.println("docInfoList为null没有查询出来");
if (docInfoList.size()==0) {
System.out.println("最后一步:docInfoList为null没有查询出来");
} else {
System.out.println("docInfoList值为======》" + docInfoList);
System.out.println("最后一步:docInfoList值为======》" + docInfoList);
}
List<Term> termList = docInfoList.parallelStream().filter(ObjectUtils::isNotEmpty).flatMap(_docInfo -> {
try {

@ -351,14 +351,19 @@ public abstract class EsService<T> {
}
public List<T> search(SearchSourceBuilder builder) {
System.out.println("第三步 调用search方法 index:"+index);
System.out.println("第四步builder:"+builder.toString());
SearchRequest request = new SearchRequest(index);
System.out.println("第五步request:"+request.toString());
request.source(builder);
System.out.println("第六步requestSource:"+request.toString());
RestHighLevelClient client = null;
try {
client = ElasticSearchPoolUtil.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHit[] hits = response.getHits().getHits();
List<T> res = new ArrayList<>(hits.length);
System.out.println("第七步hit.size:"+hits.length);
for (SearchHit hit : hits) {
//res.add(JSON.parseObject(hit.getSourceAsString(), entity));
res.add(loadData(builder, hit));
@ -705,6 +710,7 @@ public abstract class EsService<T> {
this.searchSourceBuilder.query(funScoreBuilders);
this.boolQueryBuilder.must(funScoreBuilders);
}
System.out.println("第二步this:"+this);
return this;
}

@ -99,6 +99,7 @@ public class SecurityUtils
}
//$2a$10$u.vJlcN4vQlY5m9Tnc3jFOGeg9nrDkSZ34eXoHkt/Vw7hs3HvRMnO
/**
*
*

@ -171,6 +171,7 @@ public class TokenService
*/
private String createToken(Map<String, Object> claims)
{
System.out.println(secret);
String token = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact();

Loading…
Cancel
Save