hjl
2024-05-24 2a1e2ebb3ce800fc6aa8067db0cc3b0ab9253604
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package com.ruoyi.common.security.service;
 
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.api.model.LoginUserParent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {
    @Autowired
    private RedisService redisService;
 
    protected static final long MILLIS_SECOND = 1000;
 
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
 
    private final static long expireTime = CacheConstants.EXPIRATION;
 
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
 
    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;
 
    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken(loginUser);
 
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
 
        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }
 
    public Map<String, Object> createToken1(LoginUserParent loginUser) {
        String token = IdUtils.fastUUID();
        Integer userId = loginUser.getUserid();
        String name = loginUser.getName();
        loginUser.setToken(token);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken1(loginUser);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_PARENT_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, name);
        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }
 
    public Map<String, Object> createTokenStudy(LoginUserParent loginUser) {
        String token = IdUtils.fastUUID();
        Integer userId = loginUser.getUserid();
        String name = loginUser.getName();
        loginUser.setToken(token);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshTokenStudy(loginUser);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>(8);
        claimsMap.put(SecurityConstants.USER_STUDY_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, name);
        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }
 
    /**
     * 家长端/学习端获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUser1() {
        return getLoginUser1(ServletUtils.getRequest());
    }
 
    /**
     * 学习端获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUserStudy() {
        LoginUserParent userStudy = getLoginUserStudy(ServletUtils.getRequest());
        if (null == userStudy) {
            throw new GlobalException("登录失效,请重新登录!");
        }
        return userStudy;
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUser1(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser1(token);
    }
 
    /**
     * 学习端获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUserStudy(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUserStudy(token);
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        } catch (Exception e) {
        }
        return user;
    }
 
    /**
     * 家长端 学习端 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUser1(String token) {
        LoginUserParent user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userkey = JwtUtils.getUserKey1(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
 
    /**
     * 学习端 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserParent getLoginUserStudy(String token) {
        LoginUserParent user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userkey = JwtUtils.getUserKeyStudy(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
 
    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }
 
    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userkey = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }
 
    /**
     * 家长端删除用户缓存信息
     */
    public void delLoginUser1(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userkey = JwtUtils.getUserKey1(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }
 
    /**
     * 验证令牌有效期,相差不足120分钟,自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }
 
    /**
     * 验证令牌有效期,相差不足120分钟,自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken1(LoginUserParent loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken1(loginUser);
        }
    }
 
    /**
     * 验证令牌有效期,相差不足120分钟,自动刷新缓存
     */
    public void verifyTokenStudy(LoginUserParent loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshTokenStudy(loginUser);
        }
    }
 
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }
 
    /**
     * 家长端用户登录
     */
    public void refreshToken1(LoginUserParent dto) {
        dto.setLoginTime(System.currentTimeMillis());
        dto.setExpireTime(dto.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(dto.getToken());
        redisService.setCacheObject(userKey, dto, expireTime, TimeUnit.MINUTES);
    }
 
    /**
     * 学习端用户登录
     */
    public void refreshTokenStudy(LoginUserParent dto) {
        // 获取所有 login_tokens: 前缀的登录缓存
        Set redisCache = redisService.getKeysPrefix(ACCESS_TOKEN + "*");
        for (Object key : redisCache) {
            String strKey = String.valueOf(key);
            // 根据 login_tokens:加密token 获取用户登录信息
            Object redisCacheUserInfo = redisService.getCacheObject(strKey);
            LoginUserParent redisUserInfo = JSONObject.parseObject(JSONObject.toJSONString(redisCacheUserInfo), LoginUserParent.class);
            // 单点逻辑
            if (dto.getPhone().equals(redisUserInfo.getPhone())) {
                redisService.deleteObject(strKey);
            }
        }
        // 单点登录逻辑
        dto.setLoginTime(System.currentTimeMillis());
        dto.setExpireTime(dto.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(dto.getToken());
        redisService.setCacheObject(userKey, dto, expireTime, TimeUnit.MINUTES);
    }
 
    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}