Skip to content

Commit fb33845

Browse files
author
孙健
committed
up token and rpc err
1 parent c9ba8e8 commit fb33845

File tree

6 files changed

+223
-74
lines changed

6 files changed

+223
-74
lines changed

src/main/java/org/nlpcn/jcoder/controller/LoginAction.java

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,22 @@
3434
import org.slf4j.LoggerFactory;
3535

3636
@IocBean
37-
@Filters(@By(type = IpErrorCountFilter.class, args = {"20"}))
37+
@Filters(@By(type = IpErrorCountFilter.class, args = { "20" }))
3838
public class LoginAction {
39-
40-
private static final Logger LOG = LoggerFactory.getLogger(LoginAction.class) ;
39+
40+
private static final Logger LOG = LoggerFactory.getLogger(LoginAction.class);
4141

4242
public BasicDao basicDao = StaticValue.systemDao;
4343

4444
@At("/login")
45-
public void login(HttpServletRequest req,HttpServletResponse resp, @Param("name") String name, @Param("password") String password, @Param("verification_code") String verificationCode) throws Throwable {
45+
public void login(HttpServletRequest req, HttpServletResponse resp, @Param("name") String name, @Param("password") String password,
46+
@Param("verification_code") String verificationCode) throws Throwable {
4647

4748
String sessionCode = (String) req.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
48-
49-
if (StringUtil.isBlank(sessionCode)||!sessionCode.equalsIgnoreCase(verificationCode)) {
50-
new JsonView().render(req, resp, Restful.instance(false, "Login fail please validate verification code err times:"+IpErrorCountFilter.err(),null,ApiException.NotFound));
49+
50+
if (StringUtil.isBlank(sessionCode) || !sessionCode.equalsIgnoreCase(verificationCode)) {
51+
new JsonView().render(req, resp,
52+
Restful.instance(false, "Login fail please validate verification code err times:" + IpErrorCountFilter.err(), null, ApiException.NotFound));
5153
}
5254

5355
Condition con = Cnd.where("name", "=", name);
@@ -79,44 +81,52 @@ public void login(HttpServletRequest req,HttpServletResponse resp, @Param("name"
7981

8082
new JsonView().render(req, resp, Restful.OK);
8183
} else {
82-
int err = IpErrorCountFilter.err() ;
83-
LOG.info("user " + name + "login err ,times : "+err);
84-
new JsonView().render(req, resp, Restful.instance(false, "login fail please validate your name or password times : "+err,null,ApiException.NotFound));
84+
int err = IpErrorCountFilter.err();
85+
LOG.info("user " + name + "login err ,times : " + err);
86+
new JsonView().render(req, resp, Restful.instance(false, "login fail please validate your name or password times : " + err, null, ApiException.NotFound));
8587
}
8688
}
87-
88-
89+
8990
@At("/login/api")
9091
@Ok("json")
9192
public Restful loginApi(HttpServletRequest req, @Param("name") String name, @Param("password") String password) throws ExecutionException {
92-
int err = IpErrorCountFilter.err() ;// for client login to many times ,
93+
int err = IpErrorCountFilter.err();// for client login to many times ,
9394
Condition con = Cnd.where("name", "=", name);
9495
User user = basicDao.findByCondition(User.class, con);
9596
if (user != null && user.getPassword().equals(StaticValue.passwordEncoding(password))) {
9697
return Restful.instance(TokenService.regToken(user));
9798
} else {
98-
LOG.info("user " + name + "login err , times : "+err);
99-
return Restful.instance(false, "login fail please validate your name or password ,times : "+err, null, ApiException.Unauthorized);
99+
LOG.info("user " + name + "login err , times : " + err);
100+
return Restful.instance(false, "login fail please validate your name or password ,times : " + err, null, ApiException.Unauthorized);
100101
}
101102
}
102-
103+
103104
@At("/loginOut/api")
104105
@Ok("json")
105106
public Restful loginOutApi(HttpServletRequest req) {
106107
String token = req.getHeader("authorization");
107-
if(StringUtil.isBlank(token)){
108-
return Restful.instance(false,"token 'authorization' not in header ") ;
109-
}else{
110-
Token removeToken = TokenService.removeToken(token) ;
111-
if(removeToken==null){
112-
return Restful.instance(false,"token not in server ") ;
113-
}else{
114-
return Restful.instance(true,removeToken.getUser().getName()+" login out ok") ;
108+
if (StringUtil.isBlank(token)) {
109+
return Restful.instance(false, "token 'authorization' not in header ");
110+
} else {
111+
Token removeToken = TokenService.removeToken(token);
112+
if (removeToken == null) {
113+
return Restful.instance(false, "token not in server ");
114+
} else {
115+
return Restful.instance(true, removeToken.getUser().getName() + " login out ok");
115116
}
116-
117+
117118
}
118119
}
119120

121+
@At("/validation/token")
122+
public void validation(String token) throws ExecutionException {
123+
Token t = TokenService.getToken("token");
124+
if (t == null) {
125+
new JsonView(ApiException.NotFound);
126+
} else {
127+
new JsonView();
128+
}
129+
}
120130

121131
@At("/loginOut")
122132
@Ok("redirect:/login.jsp")

src/main/java/org/nlpcn/jcoder/filter/TokenFilter.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ public View match(ActionContext actionContext) {
2525

2626
if (StringUtil.isBlank(token)) {
2727
LOG.info(StaticValue.getRemoteHost(actionContext.getRequest()) + " token 'authorization' not in header");
28-
return new JsonView(Restful.instance(false, "token 'authorization' not in header ",null,ApiException.Unauthorized));
28+
return new JsonView(Restful.instance(false, "token 'authorization' not in header ", null, ApiException.Unauthorized));
2929
}
3030

3131
try {
3232
Token token2 = TokenService.getToken(token) ;
3333
if (token2==null || token2 == Token.NULL) {
3434
LOG.info(StaticValue.getRemoteHost(actionContext.getRequest()) + " token not access");
35-
return new JsonView(Restful.instance(false, "token not access",null,ApiException.Unauthorized));
35+
return new JsonView(Restful.instance(false, "token not access", null, ApiException.TokenAuthorNotFound));
3636
}
3737
} catch (ExecutionException e) {
3838
e.printStackTrace();

src/main/java/org/nlpcn/jcoder/server/rpc/client/HttpApiClient.java

Lines changed: 125 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
import java.net.URLEncoder;
66
import java.util.Collections;
77
import java.util.HashMap;
8-
import java.util.List;
98
import java.util.Map;
109
import java.util.Map.Entry;
11-
import java.util.stream.Collectors;
1210

13-
import org.nlpcn.commons.lang.util.IOUtil;
11+
import org.nlpcn.jcoder.util.ApiException;
12+
import org.nutz.http.Header;
1413
import org.nutz.http.Http;
14+
import org.nutz.http.Request;
15+
import org.nutz.http.Request.METHOD;
1516
import org.nutz.http.Response;
17+
import org.nutz.http.Sender;
1618

17-
import com.alibaba.fastjson.JSONArray;
1819
import com.alibaba.fastjson.JSONObject;
1920

2021
/**
@@ -23,15 +24,79 @@
2324
* @author Ansj
2425
*
2526
*/
27+
@Deprecated
2628
public class HttpApiClient {
29+
30+
private static final String TOKEN_HEAD = "authorization";
31+
2732
private String ip;
2833
private int port;
34+
private String name;
35+
private String password;
36+
37+
private Header header;
2938

3039
public HttpApiClient(String ip, int port) {
3140
this.ip = ip;
3241
this.port = port;
3342
}
3443

44+
/**
45+
* 具有登录的restful api 接口
46+
*
47+
* @param ip
48+
* @param port
49+
* @param name
50+
* @param password
51+
* @param autoCheck 是否自动检查token过期.检查频率为10分钟一次.保证token一直续约
52+
* @throws Exception
53+
*/
54+
public HttpApiClient(String ip, int port, String name, String password, boolean validation) throws Exception {
55+
this.ip = ip;
56+
this.port = port;
57+
this.name = name;
58+
this.password = password;
59+
login();
60+
}
61+
62+
/**
63+
* 进行登录验证
64+
*
65+
* @throws Exception
66+
*/
67+
public synchronized void login() throws Exception {
68+
69+
if (this.header != null && validation()) { //如果已经持有token ,则不再登录
70+
return;
71+
}
72+
73+
Map<String, Object> params = new HashMap<>();
74+
75+
params.put("name", name);
76+
params.put("password", password);
77+
Response response = Http.post2("http://" + ip + ":" + port + "/login/api", params, 60000);
78+
79+
JSONObject job = JSONObject.parseObject(response.getContent());
80+
81+
if (response.getStatus() == 200) {
82+
String token = job.getString("obj");
83+
Map<String, String> headMap = new HashMap<>();
84+
headMap.put(TOKEN_HEAD, token);
85+
header = Header.create(headMap);
86+
} else {
87+
throw new ApiException(ApiException.Forbidden, job.toJSONString());
88+
}
89+
}
90+
91+
private boolean validation() {
92+
Response response = Http.get("http://" + ip + ":" + port + "/validation/token");
93+
if (response.getStatus() != 200) {
94+
return true;
95+
} else {
96+
return false;
97+
}
98+
99+
}
35100

36101
/**
37102
* 通过get方式获取流
@@ -57,33 +122,40 @@ public Response get(String className, String methodName, int timeout) throws Mal
57122
* @throws IOException
58123
*/
59124
public Response get(String className, String methodName, int timeout, Map<String, Object> params) throws MalformedURLException, IOException {
60-
StringBuilder url = new StringBuilder("http://" + ip + ":" + port + "/api/" + className + "/" + methodName + "?1=1");
125+
StringBuilder paramSb = new StringBuilder();
61126

62127
if (params != null && params.size() > 0) {
63128
for (Entry<String, Object> entry : params.entrySet()) {
64-
url.append("&");
65-
url.append(entry.getKey());
66-
url.append("=");
67-
url.append(URLEncoder.encode(String.valueOf(entry.getValue()), "utf-8"));
129+
if (paramSb.length() > 0) {
130+
paramSb.append("&");
131+
}
132+
paramSb.append(entry.getKey());
133+
paramSb.append("=");
134+
paramSb.append(URLEncoder.encode(String.valueOf(entry.getValue()), "utf-8"));
68135
}
69136
}
70137

71-
return Http.get(url.toString(), timeout);
138+
return get(className, methodName, paramSb.toString(), timeout);
72139
}
73140

74141
/**
75142
* 通过get方式获取流
76143
*
77144
* @param className
78145
* @param methodName
79-
* @param params 直接拼装的sql ,不需要带开始的?号
146+
* @param params 直接拼装的http参数 ,不需要带开始的?号
80147
* @return
81148
* @throws MalformedURLException
82149
* @throws IOException
83150
*/
84-
public Response get(String className, String methodName, int timeout, String params) throws MalformedURLException, IOException {
85-
StringBuilder url = new StringBuilder("http://" + ip + ":" + port + "/api/" + className + "/" + methodName + "?" + params);
86-
return Http.get(url.toString(), timeout);
151+
public Response get(String className, String methodName, String params, int timeout) throws MalformedURLException, IOException {
152+
StringBuilder makeUrl = makeUrl(className, methodName);
153+
makeUrl.append("?").append(params);
154+
Request req = Request.get(makeUrl.toString());
155+
if (header != null) {
156+
req = req.setHeader(header);
157+
}
158+
return Sender.create(req).setTimeout(timeout).send();
87159
}
88160

89161
/**
@@ -97,7 +169,45 @@ public Response get(String className, String methodName, int timeout, String par
97169
* @throws IOException
98170
*/
99171
public Response post(String className, String methodName, int timeout, Map<String, Object> params) throws MalformedURLException, IOException {
100-
return Http.post2("http://" + ip + ":" + port + "/api/" + className + "/" + methodName.toString(), params, timeout);
172+
return Sender.create(Request.create(makeUrl(className, methodName).toString(), METHOD.POST, params, header)).setTimeout(timeout).send();
173+
}
174+
175+
/**
176+
* POST 一个字符串
177+
*
178+
* @param className
179+
* @param methodName
180+
* @param content
181+
* @param timeout
182+
* @return
183+
*/
184+
public Response post(String className, String methodName, Object body, int timeout) {
185+
return Http.post3(makeUrl(className, methodName).toString(), body, header, timeout);
186+
}
187+
188+
/**
189+
* 上传一个文件
190+
*
191+
* @param className
192+
* @param methodName
193+
* @param params
194+
* @param timeout
195+
* @return
196+
*/
197+
public Response upload(String className, String methodName, Map<String, Object> params, int timeout) {
198+
return Http.upload(makeUrl(className, methodName).toString(), params, header, timeout);
199+
}
200+
201+
private StringBuilder makeUrl(String className, String methodName) {
202+
StringBuilder sb = new StringBuilder();
203+
sb.append("http://");
204+
sb.append(ip);
205+
sb.append(":");
206+
sb.append(port);
207+
sb.append("/api/");
208+
sb.append(className);
209+
sb.append(methodName);
210+
return sb;
101211
}
102212

103213
}

src/main/java/org/nlpcn/jcoder/util/ApiException.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ public class ApiException extends ExecutionException {
3636
* 请求格式不正确
3737
*/
3838
public static final int UnprocessableEntity = 422;
39+
40+
/**
41+
* 请求格式不正确
42+
*/
43+
public static final int TokenAuthorNotFound = 450;
3944

4045
/**
4146
* 服务器错误

0 commit comments

Comments
 (0)