夏文涛 2 年 前
コミット
54cc30efa9

+ 199 - 0
mhotel/src/com/happy/Until/AesUtils.java

@@ -0,0 +1,199 @@
+package com.happy.Until;
+
+import lombok.extern.slf4j.Slf4j;
+import org.bouncycastle.util.encoders.Base64;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * @Author: liujun
+ * @Description: Aes 加解密算法
+ * @Date Create in 上午 9:38$ 2017/12/26 0026$
+ * @Modify By:
+ */
+@Slf4j
+public class AesUtils {
+    private static String password = "52D04DC20036DBD8";
+    /**
+     * @Author liujun
+     * @Description:
+     * @params: * @param content 需要加密的内容
+     * @param password  加密密码
+     * @Date 上午 9:41 2017/12/26 0026
+     */
+    public static String encrypt(String content) {
+
+        if(password.length()<16) {
+            password = password + "0000000000000000".substring(0, 16-password.length());
+        }
+        else if(password.length()>16) {
+            password = password.substring(0, 16);
+        }
+
+        return bytes2HexString(encryptAES(content.getBytes(), password.getBytes()));
+    }
+
+
+    /**
+     * @Author liujun
+     * @Description:
+     * @params: * @param content 待解密内容
+     * @param password 解密密钥
+     * @Date 上午 9:40 2017/12/26 0026
+     */
+    public static String decrypt(String content) {
+        if(password.length()<16) {
+            password = password + "0000000000000000".substring(0, 16-password.length());
+        }
+        else if(password.length()>16) {
+            password = password.substring(0, 16);
+        }
+
+        return new String(decryptAES(hexString2Bytes(content), password.getBytes()));
+    }
+
+    /**
+     * AES 加密
+     *
+     * @param data 明文
+     * @param key  16、24、32 字节秘钥
+     * @return 密文
+     */
+    public static byte[] encryptAES(final byte[] data, final byte[] key) {
+
+        try {
+            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
+            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
+            byte[] byteContent = data;
+            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
+            byte[] result = cipher.doFinal(byteContent);
+            return result; // 加密
+        } catch (NoSuchAlgorithmException e) {
+            log.error(e.getMessage(),e);
+        } catch (NoSuchPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (InvalidKeyException e) {
+            log.error(e.getMessage(),e);
+        } catch (IllegalBlockSizeException e) {
+            log.error(e.getMessage(),e);
+        } catch (BadPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (Exception e) {
+            log.error(e.getMessage(),e);
+        }
+        return null;
+    }
+
+    /**
+     * AES 解密
+     *
+     * @param data 密文
+     * @param key  16、24、32 字节秘钥
+     * @return 明文
+     */
+    public static byte[] decryptAES(final byte[] data, final byte[] key) {
+
+        try {
+            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
+            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
+            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
+            byte[] result = cipher.doFinal(data);
+            return result; // 加密
+        } catch (NoSuchAlgorithmException e) {
+            log.error(e.getMessage(),e);
+        } catch (NoSuchPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (InvalidKeyException e) {
+            log.error(e.getMessage(),e);
+        } catch (IllegalBlockSizeException e) {
+            log.error(e.getMessage(),e);
+        } catch (BadPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (Exception e) {
+            log.error(e.getMessage(),e);
+        }
+        return null;
+    }
+
+    public static String bytes2HexString(final byte[] bytes) {
+        if (bytes == null) return null;
+        int len = bytes.length;
+        if (len <= 0) return null;
+        char[] ret = new char[len << 1];
+        for (int i = 0, j = 0; i < len; i++) {
+            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
+            ret[j++] = hexDigits[bytes[i] & 0x0f];
+        }
+        return new String(ret);
+    }
+
+    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+    public static byte[] hexString2Bytes(String hexString) {
+        if (isSpace(hexString)) return null;
+        int len = hexString.length();
+        if (len % 2 != 0) {
+            hexString = "0" + hexString;
+            len = len + 1;
+        }
+        char[] hexBytes = hexString.toUpperCase().toCharArray();
+        byte[] ret = new byte[len >> 1];
+        for (int i = 0; i < len; i += 2) {
+            ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
+        }
+        return ret;
+    }
+
+    private static int hex2Dec(final char hexChar) {
+        if (hexChar >= '0' && hexChar <= '9') {
+            return hexChar - '0';
+        } else if (hexChar >= 'A' && hexChar <= 'F') {
+            return hexChar - 'A' + 10;
+        } else {
+            throw new IllegalArgumentException();
+        }
+    }
+
+    public static byte[] base64Encode(final byte[] input) {
+        return Base64.encode(input);
+    }
+
+    public static byte[] base64Decode(final byte[] input) {
+
+        return Base64.decode(input);
+    }
+
+    private static boolean isSpace(final String s) {
+        if (s == null) return true;
+        for (int i = 0, len = s.length(); i < len; ++i) {
+            if (!Character.isWhitespace(s.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public static void main(String[] args) {
+        String s="{\n" +
+                "  \"categoryId\": \"72cf28a8789643bbbbb62d08ee91f17e\",\n" +
+                "     \"luid\": \"80A036D93CFB\",\n" +
+                "     \"type\":\"4\",\n" +
+                "     \"userName\":\"13097286670\",\n" +
+                "     \"startTime\":\"1682389484000\",\n" +
+                "     \"endTime\":\"1684981484000\",\n" +
+                "     \"password\":\"A08E87B5E777EBEE2C6EF3262F069D5A\"\n" +
+                "}";
+        //加密
+        String encryptString = AesUtils.encrypt("1550436629");
+        System.out.println("加密后字符串:"+encryptString);
+        //解密
+        String decryptString = AesUtils.decrypt(encryptString);
+        System.out.println("解密后字符串:"+decryptString);
+    }
+}

+ 70 - 1
mhotel/src/com/happy/action/AppMePageAction.java

@@ -10,12 +10,15 @@ import com.happy.Until.*;
 import com.happy.Until.Enum.B;
 import com.happy.Until.Enum.B;
 import com.happy.Until.Enum.DataType;
 import com.happy.Until.Enum.DataType;
 import com.happy.Until.Enum.TempEnum;
 import com.happy.Until.Enum.TempEnum;
+import com.happy.common.JwtUtil;
 import com.happy.common.http.HttpsClient;
 import com.happy.common.http.HttpsClient;
 import com.happy.common.wx.WxUtil;
 import com.happy.common.wx.WxUtil;
 import com.happy.constant.ConstDefault;
 import com.happy.constant.ConstDefault;
 import com.happy.constant.ResultStatusCode;
 import com.happy.constant.ResultStatusCode;
 import com.happy.dto.IPage;
 import com.happy.dto.IPage;
 import com.happy.service.*;
 import com.happy.service.*;
+import com.happy.vo.TokenUsersVo;
+import com.happy.vo.UsersVo;
 import com.opensymphony.xwork2.ActionSupport;
 import com.opensymphony.xwork2.ActionSupport;
 import net.sf.json.JSONObject;
 import net.sf.json.JSONObject;
 import org.apache.struts2.ServletActionContext;
 import org.apache.struts2.ServletActionContext;
@@ -417,6 +420,7 @@ public class AppMePageAction extends ActionSupport implements ServletRequestAwar
             resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
             resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
             resultJson.put(B.message, "未获取到OpenId");
             resultJson.put(B.message, "未获取到OpenId");
             ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
             ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+            return null;
         }
         }
 
 
         /*
         /*
@@ -476,13 +480,78 @@ public class AppMePageAction extends ActionSupport implements ServletRequestAwar
             users = userService.queryByOpenid(OPEN_ID);
             users = userService.queryByOpenid(OPEN_ID);
         }
         }
 
 
+        /**
+         * 2023-11-15 A-jax 添加token
+         */
+        String token = AesUtils.encrypt(String.valueOf(users.getId()));
+        UsersVo result = new UsersVo();
+        result.setId(users.getId());
+        result.setCard_number(users.getCard_number());
+        result.setUser_name(users.getUser_name());
+        result.setUser_phone(users.getUser_phone());
+        result.setUser_zz(users.getUser_zz());
+        result.setOpenid(users.getOpenid());
+        result.setCreate_time(users.getCreate_time());
+        result.setRemark(users.getRemark());
+        result.setIdentity_type(users.getIdentity_type());
+        result.setContactId(users.getContactId());
+        result.setContactName(users.getContactName());
+        result.setDataType(users.getDataType());
+        result.setHeadPhoto(users.getHeadPhoto());
+        result.setCollect_hotel(users.getCollect_hotel());
+        result.setLive_hotel(users.getLive_hotel());
+        result.setToken(token);
+
         resultJson.put(B.code, ResultStatusCode.OK.getStatus());
         resultJson.put(B.code, ResultStatusCode.OK.getStatus());
         resultJson.put(B.message, ResultStatusCode.OK.getMsg());
         resultJson.put(B.message, ResultStatusCode.OK.getMsg());
-        resultJson.put(B.data, users);
+        resultJson.put(B.data, result);
         ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
         ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
         return;
         return;
     }
     }
 
 
+    /**
+     * 根据token获取用户ID
+     * @return
+     */
+    public String getUserInfo(){
+        String token = request.getHeader("token");
+        JSONObject resultJson = new JSONObject();
+        if(token == null){
+            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
+            resultJson.put(B.message, "token不能为空");
+            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+            return null;
+        }
+
+        String userId = AesUtils.decrypt(token);
+
+        if(userId == null){
+            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
+            resultJson.put(B.message, "token已失效,无法获取用户信息");
+            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+            return null;
+        }
+
+        Users user = userService.queryByUserId(userId);
+        if(user == null){
+            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
+            resultJson.put(B.message, "用户信息查询失败");
+            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+            return null;
+        }
+
+        TokenUsersVo result = new TokenUsersVo();
+        result.setId(user.getId());
+        result.setUserName(user.getUser_name());
+        result.setUserPhone(user.getUser_phone());
+        result.setHeadPhoto(user.getHeadPhoto());
+
+        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
+        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
+        resultJson.put(B.data, result);
+        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+        return null;
+    }
 
 
     public String getUserCode() {
     public String getUserCode() {
         return userCode;
         return userCode;

+ 54 - 2
mhotel/src/com/happy/common/JwtUtil.java

@@ -9,6 +9,7 @@ import com.auth0.jwt.interfaces.DecodedJWT;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
 import java.io.UnsupportedEncodingException;
 import java.io.UnsupportedEncodingException;
+import java.text.ParseException;
 import java.util.Date;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map;
@@ -40,8 +41,7 @@ public class JwtUtil {
     public static boolean verify(String token) {
     public static boolean verify(String token) {
         try {
         try {
             Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
             Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
-            JWTVerifier verifier = JWT.require(algorithm)
-                    .build();
+            JWTVerifier verifier = JWT.require(algorithm).build();
             DecodedJWT jwt = verifier.verify(token);
             DecodedJWT jwt = verifier.verify(token);
             return true;
             return true;
         } catch (Exception exception) {
         } catch (Exception exception) {
@@ -107,5 +107,57 @@ public class JwtUtil {
 
 
     }
     }
 
 
+
+    /**
+     * 生成用户IDtoken
+     *
+     * @param
+     * @return 加密的token
+     */
+    public static String getToken(int userId) {
+        try {
+            //过期时间
+            long tokenExpireTime = 3153600 * 1000 * 1000;
+
+            Date date = new Date(System.currentTimeMillis() + tokenExpireTime);
+            //私钥及加密算法
+            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
+            //设置头部信息
+            Map<String, Object> header = new HashMap<>(2);
+            header.put("typ", "JWT");
+            header.put("alg", "HS256");
+            //附带username,userId信息,生成签名
+            return JWT.create()
+                    .withHeader(header)
+                    .withClaim("userId", userId)
+                    .withExpiresAt(date)
+                    .sign(algorithm);
+        } catch (Exception e) {
+            return null;
+        }
+
+    }
+
+
+    /**
+     * 获得token中的信息无需secret解密也能获得
+     *
+     * @return token中包含的用户id
+     */
+    public static String getUserId(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim("userId").asString();
+        } catch (JWTDecodeException e) {
+            return null;
+        }
+    }
+
+    public static void main(String[] args) throws ParseException {
+
+         String token = getToken(1550436629);
+        System.out.println("token:"+token);
+    }
+
 }
 }
 
 

+ 28 - 0
mhotel/src/com/happy/vo/TokenUsersVo.java

@@ -0,0 +1,28 @@
+package com.happy.vo;
+
+import lombok.Data;
+
+/**
+ * 游客表,
+ */
+@Data
+public class TokenUsersVo {
+
+    /**
+     * 用户ID
+     */
+    public int id;
+    /**
+     * 用户名称
+     */
+    public String userName;
+    /**
+     * 用户手机号
+     */
+    public String userPhone;
+
+    /**
+     * 用户头像地址
+     */
+    private String headPhoto;
+}

+ 27 - 0
mhotel/src/com/happy/vo/UsersVo.java

@@ -0,0 +1,27 @@
+package com.happy.vo;
+
+import lombok.Data;
+
+/**
+ * 游客表,
+ */
+@Data
+public class UsersVo {
+
+    public int id;
+    public String card_number;  // 身份证
+    public String user_name;
+    public String user_phone;
+    public String user_zz;   // 职务
+    public String openid;   // 微信openid
+    public String create_time;
+    public String remark;   // 备注
+    public int identity_type;   // 用户分类
+    private String contactId;   // 关联人id(用于常联系人关联)
+    private String contactName;   // 关联人姓名(用于常联系人关联)
+    private String dataType; // 数据类型
+    private String headPhoto; // 用户头像地址
+    private String collect_hotel; // 收藏酒店
+    private String live_hotel;// 住过酒店
+    private String token;
+}