rk
6 天以前 dc0b51b8800a31da0701c3f31a0b1460ae3c3ad9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.doumee.config.jwt;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.Constants;
import com.doumee.core.utils.HttpsUtil;
import com.doumee.dao.business.model.Member;
import com.doumee.dao.system.SystemUserMapper;
import com.doumee.dao.system.model.SystemUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
@Component
@Slf4j
public class JwtTokenUtil {
 
    public static final String HEADER_KEY = "token";
 
    public static final String MEMBER_ID = "MEMBER_ID";
 
    public static final String MEMBER_INFO = "MEMBER_INFO";
 
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
 
    @Resource
    private JwtProperties jwtProperties;
 
    //redis过期时间
    private static final Integer redisExpire = 365;
    /**
     * 生成token令牌
     *
     * @param member 令牌中携带的附加信息
     * @return 令token牌
     */
    public String generateToken(Member member) {
        if(member == null){
            return  null;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("id",member.getId());
        return generateTokenDo(member);
    }
 
 
    public Member getUserInfoByToken(String token) {
        try {
            Member member = getClaimsFromToken(token);
            return member;
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }
 
 
 
    /**
     * 生成token信息(同一用户仅保留一个有效token)
     * @param userId
     * @param userType 用户类型 0=会员;1=司机;2=店铺
     * @param userInfo
     * @param redisTemplate
     * @return
     */
    public static String generateTokenForRedis(Integer userId, Integer userType, String userInfo, RedisTemplate<String,Object> redisTemplate) {
        // 删除该用户之前登录的token
        String userTokenMappingKey = Constants.REDIS_TOKEN_KEY + "user_" + userType + "_" + userId;
        String oldToken = (String) redisTemplate.opsForValue().get(userTokenMappingKey);
        if (StringUtils.isNotBlank(oldToken)) {
            redisTemplate.delete(Constants.REDIS_TOKEN_KEY + oldToken);
        }
        // 生成新token
        String tokenKey = userType +""+ UUID.randomUUID() + "_" + userId;
        redisTemplate.opsForValue().set(Constants.REDIS_TOKEN_KEY + tokenKey, userInfo, redisExpire, TimeUnit.DAYS);
        // 记录用户与token的映射关系
        redisTemplate.opsForValue().set(userTokenMappingKey, tokenKey, redisExpire, TimeUnit.DAYS);
        return tokenKey;
    }
 
 
    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public void refreshToken(String token,Member member) {
        try {
            if(Objects.nonNull(member)){
//                redisTemplate.expire(Constants.REDIS_TOKEN_KEY+token,jwtProperties.getExpiration(), TimeUnit.MILLISECONDS);
//                redisTemplate.delete(Constants.REDIS_TOKEN_KEY+token);
//                redisTemplate.opsForValue().set(Constants.REDIS_TOKEN_KEY+token,JSONObject.toJSONString(member),jwtProperties.getExpiration(), TimeUnit.MILLISECONDS);
            }
        } catch (Exception e) {
 
        }
    }
 
 
    /**
     * 退出登陆
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public void logoutForH5(String token) {
        try {
            //删除老的token
            redisTemplate.delete(Constants.REDIS_TOKEN_KEY+token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 从claims生成令牌,如果看不懂就看谁调用它
     *
     * @return 令牌
     */
    private String generateTokenDo(Member member) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",member.getId());
        Date expirationDate = new Date(System.currentTimeMillis() + jwtProperties.getExpiration());
        String token = Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
                .compact();
        redisTemplate.opsForValue().set(Constants.REDIS_TOKEN_KEY+token,JSONObject.toJSONString(member)
//                , jwtProperties.getExpiration(), TimeUnit.MILLISECONDS
        );
        return token;
    }
 
 
    /**
     * 从令牌中获取数据声明,验证JWT签名
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Member getClaimsFromToken(String token) {
        Member claims;
        try {
            String userInfo = (String) redisTemplate.opsForValue().get(Constants.REDIS_TOKEN_KEY+token);
            claims = JSONObject.toJavaObject(JSONObject.parseObject(userInfo),Member.class);
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
 
}