forked from kidgrow-microservices-platform

zhaoxiaohao
2021-03-11 0c9ff5198c54ec5d2f3bbb8c5a406d270df1e188
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
package com.kidgrow.oauth2.service.impl;
 
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.kidgrow.common.constant.SecurityConstants;
import com.kidgrow.common.model.PageResult;
import com.kidgrow.common.model.ResultBody;
import com.kidgrow.common.utils.StringUtils;
import com.kidgrow.oauth2.model.TokenVo;
import com.kidgrow.oauth2.service.ITokensService;
import com.kidgrow.redis.template.RedisRepository;
import com.kidgrow.redis.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: token管理服务(redis token)<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/20 09:19 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@Slf4j
@Service
public class RedisTokensServiceImpl implements ITokensService {
    @Autowired
    private RedisRepository redisRepository;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TokenStore tokenStore;
 
    @Override
    public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) {
        Integer page = MapUtils.getInteger(params, "page");
        Integer limit = MapUtils.getInteger(params, "limit");
        int[] startEnds = PageUtil.transToStartEnd(page, limit);
        //根据请求参数生成redis的key
        String redisKey = getRedisKey(params, clientId);
        long size = redisRepository.length(redisKey);
        List<TokenVo> result = new ArrayList<>(limit);
        //查询token集合
        List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1);
        if (tokenObjs != null) {
            for (Object obj : tokenObjs) {
                DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj;
                //构造token对象
                TokenVo tokenVo = new TokenVo();
                tokenVo.setTokenValue(accessToken.getValue());
                tokenVo.setExpiration(accessToken.getExpiration());
 
                //获取用户信息
                Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue());
                OAuth2Authentication authentication = (OAuth2Authentication)authObj;
                if (authentication != null) {
                    OAuth2Request request = authentication.getOAuth2Request();
                    tokenVo.setUsername(authentication.getName());
                    tokenVo.setClientId(request.getClientId());
                    tokenVo.setGrantType(request.getGrantType());
                }
 
                result.add(tokenVo);
            }
        }
        return PageResult.<TokenVo>builder().data(result).code(0).count(size).build();
    }
 
    /**
     * 根据请求参数生成redis的key
     */
    private String getRedisKey(Map<String, Object> params, String clientId) {
        String result;
        String username = MapUtils.getString(params, "username");
        if (StrUtil.isNotEmpty(username)) {
            result = SecurityConstants.REDIS_UNAME_TO_ACCESS + clientId + ":" + username;
        } else {
            result = SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId;
        }
        return result;
    }
 
    /**
     * 获取用户是否登录;
     * @param map
     * @return
     */
    @Override
    public ResultBody getBeforLogin(Map<String, Object> map) {
        String name = MapUtils.getString(map, "name");
        if (StringUtils.isBlank(name)) {
            return ResultBody.failed("请输入用户名");
        }
        String webApp = MapUtils.getString(map, "webApp");
        if (StringUtils.isBlank(webApp)) {
            return ResultBody.failed("请输入应用id");
        }
        //获取token
        Collection<OAuth2AccessToken> tokensByClientIdAndUserName = this.tokenStore.findTokensByClientIdAndUserName(webApp, name);
        List<OAuth2AccessToken> collect = tokensByClientIdAndUserName.stream().collect(Collectors.toList());
//        验证token
        if(collect!=null){
            OAuth2AccessToken oAuth2AccessToken = collect.get(collect.size() - 1);
            if(oAuth2AccessToken.isExpired()){
                return ResultBody.ok().data(true);
            }else {
                return ResultBody.ok().data(false);
            }
        }else {
            return ResultBody.ok().data(true);
        }
    }
}