无关风月
2024-09-03 56dfe0d4bf81262622a1919cceb2b039fd356209
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
package com.ruoyi.common.security.service;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
 
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.exception.ManagementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
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;
 
/**
 * 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 EXPIRE_TIME = CacheConstants.EXPIRATION;
 
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    private final static String ACCESS_TOKEN_DEVICE = CacheConstants.LOGIN_TOKEN_KEY_DEVICE;
 
    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", EXPIRE_TIME);
        return rspMap;
    }
 
    /**
     * 扫描设备登录
     * @param loginUser
     * @return
     */
    public Map<String, Object> createToken1(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());
        refreshToken1(loginUser);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY_DEVICE, 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", EXPIRE_TIME);
        return rspMap;
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser()
    {
        return getLoginUser(ServletUtils.getRequest());
    }
    public LoginUser getLoginUserDevice()
    {
        return getLoginUserDevice(ServletUtils.getRequest());
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }
    public LoginUser getLoginUserDevice(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUserDevice(token);
    }
 
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token)
    {
        LoginUser user = null;
 
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                // 再次判断登录状态是否已过期 isBig不为空 证明是大屏的登录 不做单点提示
                if (null == user ) {
                    throw new ManagementException("登录信息已过期,请重新登录!", 504);
                }
                // 优先判断当前账号是否已在其他设备登录
                if (!user.getIsCanLogin() && user.getIsBig() == null) {
                    throw new ManagementException("当前登录账号在其他设备登录!", 505);
                }
                // 再次判断登录状态是否已过期
                if (System.currentTimeMillis() > user.getExpireTime() && user.getIsBig()==null) {
                    throw new ManagementException("登录信息已过期,请重新登录!", 504);
                }
                return user;
            }
        return user;
    }
    public LoginUser getLoginUserDevice(String token)
    {
        LoginUser user = null;
 
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKeyDevice(token);
                user = redisService.getCacheObject(getTokenKey1(userkey));
                // 再次判断登录状态是否已过期
                if (null == user) {
                    throw new ManagementException("登录信息已过期,请重新登录!", 504);
                }
                // 优先判断当前账号是否已在其他设备登录
                if (!user.getIsCanLogin()) {
                    throw new ManagementException("当前登录账号在其他设备登录!", 505);
                }
                // 再次判断登录状态是否已过期
                if (System.currentTimeMillis() > user.getExpireTime()) {
                    throw new ManagementException("登录信息已过期,请重新登录!", 504);
                }
                return user;
            }
        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 delLoginUserDevice(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userkey = JwtUtils.getUserKeyDevice(token);
            redisService.deleteObject(getTokenKey1(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);
        }
    }
 
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        Set redisCache = redisService.getKeysPrefix(ACCESS_TOKEN);
        for (Object key : redisCache) {
            String strKey = String.valueOf(key);
            // 根据 login_tokens:加密token 获取用户登录信息
            Object redisCacheUserInfo = redisService.getCacheObject(strKey);
            LoginUser redisUserInfo = JSONObject.parseObject(JSONObject.toJSONString(redisCacheUserInfo), LoginUser.class);
            // 单点逻辑,如果当前用户已处于登录状态并再次登录,则清除该用户上一次登录token
            if (loginUser.getUserid().equals(redisUserInfo.getUserid())) {
                // 被挤账户 可登录状态 已经为 false时,跳出循环
                if (!redisUserInfo.getIsCanLogin()) {
                    continue;
                }
                if (redisUserInfo.getIsBig()!=null) {
                    continue;
                }
                // 设置能否登录字段为 否,当该token登录时,isCanLogin为false表示账号被挤
                redisUserInfo.setIsCanLogin(Boolean.FALSE);
                redisService.setCacheObject(strKey, redisUserInfo, redisService.getExpire(strKey), TimeUnit.SECONDS);
            }
        }
        // 单点登录逻辑
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.MINUTES);
    }
    // 扫描设备单点登录
    public void refreshToken1(LoginUser loginUser)
    {
        Set redisCache = redisService.getKeysPrefix(ACCESS_TOKEN_DEVICE);
        for (Object key : redisCache) {
            String strKey = String.valueOf(key);
            // 根据 login_tokens:加密token 获取用户登录信息
            Object redisCacheUserInfo = redisService.getCacheObject(strKey);
            LoginUser redisUserInfo = JSONObject.parseObject(JSONObject.toJSONString(redisCacheUserInfo), LoginUser.class);
            // 单点逻辑,如果当前用户已处于登录状态并再次登录,则清除该用户上一次登录token
            if (loginUser.getUserid().equals(redisUserInfo.getUserid())) {
                // 被挤账户 可登录状态 已经为 false时,跳出循环
                if (!redisUserInfo.getIsCanLogin()) {
                    continue;
                }
                // 设置能否登录字段为 否,当该token登录时,isCanLogin为false表示账号被挤
                redisUserInfo.setIsCanLogin(Boolean.FALSE);
                redisService.setCacheObject(strKey, redisUserInfo, redisService.getExpire(strKey), TimeUnit.SECONDS);
            }
        }
        // 单点登录逻辑
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey1(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.MINUTES);
    }
 
    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }
    private String getTokenKey1(String token)
    {
        return ACCESS_TOKEN_DEVICE + token;
    }
}