1
13693261870
2022-09-16 fee60c3e25fac0982f3b8cb8feea7225c4ed22f8
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
package com.terra.proxy.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Properties;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BooleanCodec;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Objects;
import com.terra.proxy.bean.CustomerToken;
import com.terra.proxy.bean.ResActionRecord;
import com.terra.proxy.bean.ZyInfo;
import com.terra.proxy.mapper.LogMapper;
import com.terra.proxy.properties.TerraProperties;
import com.terra.proxy.service.Impl.LogServiceImpl;
import com.terra.proxy.util.HttpOperateUtils;
import com.terra.proxy.util.JedisUtils;
import com.terra.proxy.util.Result;
import com.terra.proxy.util.SpringContextUtils;
import com.terra.proxy.util.TokenUtils;
 
import redis.clients.jedis.Jedis;
 
/***
 * 资源权限管理 1、资源是否存在 2、资源是否公开 3、是否已经有权限
 * 
 * @author Administrator
 * 
 */
public class ZiyuanRightManager {
    private  static String logapipath = "";
 
 
    @Resource
    private LogMapper logMapper;
    
    
    public static Logger log=LoggerFactory.getLogger(ZiyuanRightManager.class);
    public static String getApiPath()
    {
        if (StringUtils.isEmpty(logapipath)) {
            String proFilePath = System.getProperty("user.dir");
            File file = new File(proFilePath + "\\terra.properties");
            Properties properties = new Properties();
            try {
                properties.load(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                
                e.printStackTrace();
            } catch (IOException e) {
                
                e.printStackTrace();
            }
            logapipath = properties.getProperty("logapipath");
        }
        return logapipath;
    }
     
 
    public static void save(ResActionRecord action) {
        String url = getApiPath() + "/actionrecord/adduseinfo";
    }
 
    private static void saveLogAction(CustomerToken map, String resourceId,String clientIp,String requesturl,String token) {
        try
        {
            ResActionRecord record = new ResActionRecord();
            // 解密 Token 里包含userid的取那值,没有取0
            if(map!=null){
            Long userid = Long.parseLong(StringUtils.isEmpty(map.getUserid())? "0":map.getUserid());
            record.setUserid(userid);
            if(!"null".equals(map.getAppId())){
            Integer appid =StringUtils.isEmpty(map.getAppId())?0:Integer.parseInt(map.getAppId());
            record.setAppid(appid);
            }
            }
            record.setResourceid(resourceId.length() != 0 ? Integer
                    .parseInt(resourceId) : 0);
            record.setIp(clientIp);
            record.setToken(token);
            record.setRequesturl(requesturl);
            //save
            saveResActionRecord(record);
        }
        catch (Exception e) {
            
            e.printStackTrace();
        }
        
    }
    
    
    
    /*
     * 统计不同ip调用服务次数,并将其存入入redis
     */
    private static void saveResActionRecord(ResActionRecord vb) {
        
        vb.setActiontime(new Date());
        Jedis jedis = null;
        int count = 0;
        try {
            jedis = JedisUtils.getJedis();
            jedis.sadd("TerraResActionRecord",JSONObject.toJSONStringWithDateFormat(vb, "yyyy-MM-dd HH:mm:ss", SerializerFeature.PrettyFormat));    
            jedis.sadd("TerraResActionRecordForJGPT",JSONObject.toJSONStringWithDateFormat(vb, "yyyy-MM-dd HH:mm:ss", SerializerFeature.PrettyFormat));
        } catch (Exception e) {
        
            log.error("redis包错");
        } finally {
            jedis.close();
        }
 
    }
 
 
    /***
     * 
     * @param
     */
    public static Result checkRight(String strToken, String referer,String clientIp, String resourceId,String isPublic,String requesturl) {
        Result result = null;
 
        CustomerToken objToken;
 
        // 服务器Token 判断 (公开资源可以不传入Token)
        if (!isPublic.equals("1") && strToken == null){
            result = Result.error(HttpStatus.SC_UNAUTHORIZED, "未传入token");
        }else{
            if (!StringUtils.isEmpty(strToken)) {
                try {
                    //token续期验证
                    boolean flag= CheckTokenIsExtend(strToken);
                    if(!flag) {
                        objToken = TokenUtils.getTokenInfo(strToken);
                        if (resourceId.compareTo(objToken.getResourceId()) != 0) {
                            result = Result.error(HttpStatus.SC_UNAUTHORIZED,
                                    "无效token!");
                            return result;
                        }
                        saveLogAction(objToken, resourceId,clientIp,requesturl,strToken);
                        result = TokenUtils.validate(objToken, clientIp, referer);
                        return result;
                    }else{
                        objToken = TokenUtils.getTokenInfo(strToken);
                        if(objToken==null){
                            TerraProperties bean = SpringContextUtils.getBean(TerraProperties.class);
                            int isAllow = SpringContextUtils.getBean(TerraProperties.class)    .getProxy().getTempAllowUrls().indexOf(resourceId);//-1代表不允许
                            if(!Objects.equal(isAllow, -1)) return Result.ok();
                            
                        }
                        if (JedisUtils.get(strToken)!=null &&!resourceId.equals(JedisUtils.get(strToken).toString()) && resourceId.compareTo(objToken.getResourceId()) != 0  ) {
                            result = Result.error(HttpStatus.SC_UNAUTHORIZED, "无效token!!");
                            return result;
                        }
                        saveLogAction(objToken, resourceId,clientIp,requesturl,strToken);
                        return Result.ok();
                    }
 
                } catch (Exception e) {
                    e.printStackTrace();
                    result = Result.error(HttpStatus.SC_UNAUTHORIZED,
                            "token服务器拒绝访问");
                }
            }else{
                return Result.ok();
            }
        }
        return Result.error(result.get("msg").toString());
    }
 
    public static  boolean CheckTokenIsExtend(String token){
         Jedis jedis= JedisUtils.getJedis();
         try{
             if(jedis.exists(token)||jedis.exists("zytoken:"+token)){
                 return true;
            }
         }catch (Exception e){
          log.error("redis错误");
          e.printStackTrace();
         }finally {
             jedis.close();
         }
         return false;
    }
 
 
    /**
     * 发送HTTP GET请求
     * 
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpGet(String url) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse httpResponse = client.execute(request);
        HttpEntity httpEntity = httpResponse.getEntity();
 
        return EntityUtils.toString(httpEntity, "UTF-8");
    }
}