-
Notifications
You must be signed in to change notification settings - Fork 261
/
DemoController.java
1743 lines (1550 loc) · 63.3 KB
/
DemoController.java
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
package apijson.boot;
import static apijson.RequestMethod.DELETE;
import static apijson.RequestMethod.GET;
import static apijson.RequestMethod.GETS;
import static apijson.RequestMethod.HEAD;
import static apijson.RequestMethod.HEADS;
import static apijson.RequestMethod.POST;
import static apijson.RequestMethod.PUT;
import static apijson.framework.APIJSONConstant.ACCESS_;
import static apijson.framework.APIJSONConstant.COUNT;
import static apijson.framework.APIJSONConstant.FORMAT;
import static apijson.framework.APIJSONConstant.FUNCTION_;
import static apijson.framework.APIJSONConstant.ID;
import static apijson.framework.APIJSONConstant.REQUEST_;
import static apijson.framework.APIJSONConstant.USER_ID;
import static apijson.framework.APIJSONConstant.VERSION;
import static org.springframework.http.HttpHeaders.COOKIE;
import static org.springframework.http.HttpHeaders.SET_COOKIE;
import java.net.URLDecoder;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.LRUMap;
import apijson.JSON;
import apijson.JSONResponse;
import apijson.Log;
import apijson.RequestMethod;
import apijson.StringUtil;
import apijson.demo.DemoFunctionParser;
import apijson.demo.DemoParser;
import apijson.demo.DemoVerifier;
import apijson.demo.model.Privacy;
import apijson.demo.model.User;
import apijson.demo.model.Verify;
import apijson.framework.APIJSONController;
import apijson.framework.BaseModel;
import apijson.orm.JSONRequest;
import apijson.orm.exception.ConditionErrorException;
import apijson.orm.exception.ConflictException;
import apijson.orm.exception.NotExistException;
import apijson.orm.exception.OutOfRangeException;
/**请求路由入口控制器,包括通用增删改查接口等,转交给 APIJSON 的 Parser 来处理
* 具体见 SpringBoot 文档
* https://www.springcloud.cc/spring-boot.html#boot-features-spring-mvc
* 以及 APIJSON 通用文档 3.设计规范 3.1 操作方法
* https://github.com/Tencent/APIJSON/blob/master/Document.md#3.1
* <br > 建议全通过HTTP POST来请求:
* <br > 1.减少代码 - 客户端无需写HTTP GET,PUT等各种方式的请求代码
* <br > 2.提高性能 - 无需URL encode和decode
* <br > 3.调试方便 - 建议使用 APIAuto(http://apijson.cn/api) 或 Postman
* @author Lemon
*/
@Service
@RestController
@RequestMapping("")
public class DemoController extends APIJSONController<Long> {
private static final String TAG = "DemoController";
// 可以更方便地通过日志排查错误
@Override
public String getRequestURL() {
return httpServletRequest.getRequestURL().toString();
}
// 通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**增删改查统一入口,这个一个方法可替代以下 7 个方法,牺牲一些路由解析性能来提升一点开发效率
* @param method
* @param tag
* @param params
* @param request
* @param session
* @return
*/
@PostMapping(value = "crud/{method}") // 直接 {method} 或 apijson/{method} 会和内置网页的路由有冲突
@Override
public String crud(@PathVariable String method, @RequestBody String request, HttpSession session) {
return super.crud(method, request, session);
}
/**获取
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#GET}
*/
@PostMapping(value = "get")
@Override
public String get(@RequestBody String request, HttpSession session) {
return super.get(request, session);
}
/**计数
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#HEAD}
*/
@PostMapping("head")
@Override
public String head(@RequestBody String request, HttpSession session) {
return super.head(request, session);
}
/**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#GETS}
*/
@PostMapping("gets")
@Override
public String gets(@RequestBody String request, HttpSession session) {
return super.gets(request, session);
}
/**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#HEADS}
*/
@PostMapping("heads")
@Override
public String heads(@RequestBody String request, HttpSession session) {
return super.heads(request, session);
}
/**新增
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#POST}
*/
@PostMapping("post")
@Override
public String post(@RequestBody String request, HttpSession session) {
return super.post(request, session);
}
/**修改
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#PUT}
*/
@PostMapping("put")
@Override
public String put(@RequestBody String request, HttpSession session) {
return super.put(request, session);
}
/**删除
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#DELETE}
*/
@PostMapping("delete")
@Override
public String delete(@RequestBody String request, HttpSession session) {
return super.delete(request, session);
}
// 通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// 以上接口对应的简版接口,格式为 {method}/{tag}?format=true&@explain=true.. <<<<<<<<<<<<<<<<<<<<<<<<<
/**增删改查统一接口,这个一个接口可替代 7 个万能通用接口,牺牲一些路由解析性能来提升一点开发效率
* @param method
* @param tag
* @param params
* @param request
* @param session
* @return
*/
@PostMapping("crud/{method}/{tag}") // 直接 {method}/{tag} 或 apijson/{method}/{tag} 会和内置网页的路由有冲突
@Override
public String crudByTag(@PathVariable String method, @PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.crudByTag(method, tag, params, request, session);
}
/**获取
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#GET}
*/
@PostMapping("get/{tag}") // 虽然看起来 APIAuto 更好识别是否为 APIJSON 万能接口,但 tag 导致空格截断前 Host 不固定不方便批量测试 {tag}/get")
@Override
public String getByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.getByTag(tag, params, request, session);
}
/**计数
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#HEAD}
*/
@PostMapping("head/{tag}")
@Override
public String headByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.headByTag(tag, params, request, session);
}
/**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#GETS}
*/
@PostMapping("gets/{tag}")
@Override
public String getsByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.getsByTag(tag, params, request, session);
}
/**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#HEADS}
*/
@PostMapping("heads/{tag}")
@Override
public String headsByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.headsByTag(tag, params, request, session);
}
/**新增
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#POST}
*/
@PostMapping("post/{tag}")
@Override
public String postByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.postByTag(tag, params, request, session);
}
/**修改
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#PUT}
*/
@PostMapping("put/{tag}")
@Override
public String putByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.putByTag(tag, params, request, session);
}
/**删除
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#DELETE}
*/
@PostMapping("delete/{tag}")
@Override
public String deleteByTag(@PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) {
return super.deleteByTag(tag, params, request, session);
}
// 以上接口对应的简版接口,格式为 {method}/{tag}?format=true&@explain=true.. >>>>>>>>>>>>>>>>>>>>>>>>>
/**获取
* 只为兼容HTTP GET请求,推荐用HTTP POST,可删除
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#GET}
*/
@GetMapping("get/{request}")
public String openGet(@PathVariable String request, HttpSession session) {
try {
request = URLDecoder.decode(request, StringUtil.UTF_8);
} catch (Exception e) {
// Parser会报错
}
return get(request, session);
}
/**计数
* 只为兼容HTTP GET请求,推荐用HTTP POST,可删除
* @param request 只用String,避免encode后未decode
* @param session
* @return
* @see {@link RequestMethod#HEAD}
*/
@GetMapping("head/{request}")
public String openHead(@PathVariable String request, HttpSession session) {
try {
request = URLDecoder.decode(request, StringUtil.UTF_8);
} catch (Exception e) {
// Parser会报错
}
return head(request, session);
}
//通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public static final String USER_;
public static final String PRIVACY_;
public static final String VERIFY_; //加下划线后缀是为了避免 Verify 和 verify 都叫VERIFY,分不清
static {
USER_ = User.class.getSimpleName();
PRIVACY_ = Privacy.class.getSimpleName();
VERIFY_ = Verify.class.getSimpleName();
}
public static final String CURRENT_USER_ID = "currentUserId";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String PASSWORD = "password";
public static final String _PASSWORD = "_password";
public static final String _PAY_PASSWORD = "_payPassword";
public static final String OLD_PASSWORD = "oldPassword";
public static final String VERIFY = "verify";
public static final String TYPE = "type";
public static final String VALUE = "value";
/**重新加载配置
* @param request
* @return
* @see
* <pre>
{
"type": "ALL", //重载对象,ALL, FUNCTION, REQUEST, ACCESS,非必须
"phone": "13000082001",
"verify": "1234567", //验证码,对应类型为 Verify.TYPE_RELOAD
"value": { // 自定义增量更新条件
"id": 1 // 过滤条件,符合 APIJSON 查询功能符即可
}
}
* </pre>
*/
@PostMapping("reload")
@Override
public JSONObject reload(@RequestBody String request) {
JSONObject requestObject = null;
String type;
JSONObject value;
String phone;
String verify;
try {
requestObject = DemoParser.parseRequest(request);
type = requestObject.getString(TYPE);
value = requestObject.getJSONObject(VALUE);
phone = requestObject.getString(PHONE);
verify = requestObject.getString(VERIFY);
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
JSONResponse response = new JSONResponse(headVerify(Verify.TYPE_RELOAD, phone, verify));
response = response.getJSONResponse(VERIFY_);
if (JSONResponse.isExist(response) == false) {
return DemoParser.extendErrorResult(requestObject, new ConditionErrorException("手机号或验证码错误"));
}
JSONObject result = DemoParser.newSuccessResult();
boolean reloadAll = StringUtil.isEmpty(type, true) || "ALL".equals(type);
if (reloadAll || "ACCESS".equals(type)) {
try {
result.put(ACCESS_, DemoVerifier.initAccess(false, null, value));
} catch (ServerException e) {
e.printStackTrace();
result.put(ACCESS_, DemoParser.newErrorResult(e));
}
}
if (reloadAll || "FUNCTION".equals(type)) {
try {
result.put(FUNCTION_, DemoFunctionParser.init(false, null, value));
} catch (ServerException e) {
e.printStackTrace();
result.put(FUNCTION_, DemoParser.newErrorResult(e));
}
}
if (reloadAll || "REQUEST".equals(type)) {
try {
result.put(REQUEST_, DemoVerifier.initRequest(false, null, value));
} catch (ServerException e) {
e.printStackTrace();
result.put(REQUEST_, DemoParser.newErrorResult(e));
}
}
return result;
}
/**生成验证码,修改为post请求
* @param request
* @see
* <pre>
{
"type": 0, //类型,0,1,2,3,4,非必须
"phone": "13000082001"
}
* </pre>
*/
@PostMapping("post/verify")
public JSONObject postVerify(@RequestBody String request) {
JSONObject requestObject = null;
int type;
String phone;
try {
requestObject = DemoParser.parseRequest(request);
type = requestObject.getIntValue(TYPE);
phone = requestObject.getString(PHONE);
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
new DemoParser(DELETE, false).parse(newVerifyRequest(type, phone, null));
JSONObject response = new DemoParser(POST, false).parseResponse(
newVerifyRequest(type, phone, "" + (new Random().nextInt(9999) + 1000))
);
if (JSONResponse.isSuccess(response) == false) {
new DemoParser(DELETE, false).parseResponse(new JSONRequest(new Verify(type, phone)));
return response;
}
//TODO 这里直接返回验证码,方便测试。实际上应该只返回成功信息,验证码通过短信发送
JSONObject object = new JSONObject();
object.put(TYPE, type);
object.put(PHONE, phone);
return getVerify(JSON.toJSONString(object));
}
/**获取验证码
* @param request
* @see
* <pre>
{
"type": 0, //类型,0,1,2,3,4,非必须
"phone": "13000082001"
}
* </pre>
*/
@PostMapping("gets/verify")
public JSONObject getVerify(@RequestBody String request) {
JSONObject requestObject = null;
int type;
String phone;
try {
requestObject = DemoParser.parseRequest(request);
type = requestObject.getIntValue(TYPE);
phone = requestObject.getString(PHONE);
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
return new DemoParser(GETS, false).parseResponse(newVerifyRequest(type, phone, null));
}
/**校验验证码
* @param request
* @see
* <pre>
{
"type": 0, //类型,0,1,2,3,4,非必须
"phone": "13000082001",
"verify": "123456"
}
* </pre>
*/
@PostMapping("heads/verify")
public JSONObject headVerify(@RequestBody String request) {
JSONObject requestObject = null;
int type;
String phone;
String verify;
try {
requestObject = DemoParser.parseRequest(request);
type = requestObject.getIntValue(TYPE);
phone = requestObject.getString(PHONE);
verify = requestObject.getString(VERIFY);
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
return headVerify(type, phone, verify);
}
/**校验验证码
* @author Lemon
* @param type
* @param phone
* @param code
* @return
*/
public JSONObject headVerify(int type, String phone, String code) {
JSONResponse response = new JSONResponse(
new DemoParser(GETS, false).parseResponse(
new JSONRequest(
new Verify(type, phone)
.setVerify(code)
).setTag(VERIFY_)
)
);
Verify verify = response.getObject(Verify.class);
if (verify == null) {
return DemoParser.newErrorResult(StringUtil.isEmpty(code, true)
? new NotExistException("验证码不存在!") : new ConditionErrorException("手机号或验证码错误!"));
}
//验证码过期
long time = BaseModel.getTimeMillis(verify.getDate());
long now = System.currentTimeMillis();
if (now > 60*1000 + time) {
new DemoParser(DELETE, false).parseResponse(
new JSONRequest(new Verify(type, phone)).setTag(VERIFY_)
);
return DemoParser.newErrorResult(new TimeoutException("验证码已过期!"));
}
return new JSONResponse(
new DemoParser(HEADS, false).parseResponse(
new JSONRequest(new Verify(type, phone).setVerify(code)).setFormat(true)
)
);
}
/**新建一个验证码请求
* @param phone
* @param verify
* @return
*/
private apijson.JSONRequest newVerifyRequest(int type, String phone, String verify) {
return new JSONRequest(new Verify(type, phone).setVerify(verify)).setTag(VERIFY_).setFormat(true);
}
public static final String LOGIN = "login";
public static final String REMEMBER = "remember";
public static final String DEFAULTS = "defaults";
public static final int LOGIN_TYPE_PASSWORD = 0;//密码登录
public static final int LOGIN_TYPE_VERIFY = 1;//验证码登录
/**用户登录
* @param request 只用String,避免encode后未decode
* @return
* @see
* <pre>
{
"type": 0, //登录方式,非必须 0-密码 1-验证码
"phone": "13000082001",
"password": "1234567",
"version": 1 //全局版本号,非必须
}
* </pre>
*/
@PostMapping(LOGIN)
public JSONObject login(@RequestBody String request, HttpSession session) {
JSONObject requestObject = null;
boolean isPassword;
String phone;
String password;
int version;
Boolean format;
boolean remember;
JSONObject defaults;
try {
requestObject = DemoParser.parseRequest(request);
isPassword = requestObject.getIntValue(TYPE) == LOGIN_TYPE_PASSWORD;//登录方式
phone = requestObject.getString(PHONE);//手机
password = requestObject.getString(PASSWORD);//密码
if (StringUtil.isPhone(phone) == false) {
throw new IllegalArgumentException("手机号不合法!");
}
if (isPassword) {
if (StringUtil.isPassword(password) == false) {
throw new IllegalArgumentException("密码不合法!");
}
} else {
if (StringUtil.isVerify(password) == false) {
throw new IllegalArgumentException("验证码不合法!");
}
}
version = requestObject.getIntValue(VERSION);
format = requestObject.getBoolean(FORMAT);
remember = requestObject.getBooleanValue(REMEMBER);
defaults = requestObject.getJSONObject(DEFAULTS); //默认加到每个请求最外层的字段
requestObject.remove(VERSION);
requestObject.remove(FORMAT);
requestObject.remove(REMEMBER);
requestObject.remove(DEFAULTS);
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
//手机号是否已注册
JSONObject phoneResponse = new DemoParser(HEADS, false).parseResponse(
new JSONRequest(
new Privacy().setPhone(phone)
)
);
if (JSONResponse.isSuccess(phoneResponse) == false) {
return DemoParser.newResult(phoneResponse.getIntValue(JSONResponse.KEY_CODE), phoneResponse.getString(JSONResponse.KEY_MSG));
}
JSONResponse response = new JSONResponse(phoneResponse).getJSONResponse(PRIVACY_);
if(JSONResponse.isExist(response) == false) {
return DemoParser.newErrorResult(new NotExistException("手机号未注册"));
}
//根据phone获取User
JSONObject privacyResponse = new DemoParser(GETS, false).parseResponse(
new JSONRequest(
new Privacy().setPhone(phone)
).setFormat(true)
);
response = new JSONResponse(privacyResponse);
Privacy privacy = response == null ? null : response.getObject(Privacy.class);
long userId = privacy == null ? 0 : BaseModel.value(privacy.getId());
if (userId <= 0) {
return privacyResponse;
}
//校验凭证
if (isPassword) {//password密码登录
response = new JSONResponse(
new DemoParser(HEADS, false).parseResponse(
new JSONRequest(new Privacy(userId).setPassword(password))
)
);
} else {//verify手机验证码登录
response = new JSONResponse(headVerify(Verify.TYPE_LOGIN, phone, password));
}
if (JSONResponse.isSuccess(response) == false) {
return response;
}
response = response.getJSONResponse(isPassword ? PRIVACY_ : VERIFY_);
if (JSONResponse.isExist(response) == false) {
return DemoParser.newErrorResult(new ConditionErrorException("账号或密码错误"));
}
response = new JSONResponse(
new DemoParser(GETS, false).parseResponse(
new JSONRequest( // 兼容 MySQL 5.6 及以下等不支持 json 类型的数据库
USER_, // User 里在 setContactIdList(List<Long>) 后加 setContactIdList(String) 没用
new apijson.JSONObject( // fastjson 查到一个就不继续了,所以只能加到前面或者只有这一个,但这样反过来不兼容 5.7+
new User(userId) // 所以就用 @json 来强制转为 JSONArray,保证有效
).setJson("contactIdList,pictureList")
).setFormat(true)
)
);
User user = response.getObject(User.class);
if (user == null || BaseModel.value(user.getId()) != userId) {
return DemoParser.newErrorResult(new NullPointerException("服务器内部错误"));
}
//登录状态保存至session
super.login(session, user, version, format, defaults);
session.setAttribute(USER_ID, userId); //用户id
session.setAttribute(TYPE, isPassword ? LOGIN_TYPE_PASSWORD : LOGIN_TYPE_VERIFY); //登录方式
session.setAttribute(USER_, user); //用户
session.setAttribute(PRIVACY_, privacy); //用户隐私信息
session.setAttribute(REMEMBER, remember); //是否记住登录
session.setMaxInactiveInterval(60*60*24*(remember ? 7 : 1)); //设置session过期时间
response.put(REMEMBER, remember);
response.put(DEFAULTS, defaults);
return response;
}
/**退出登录,清空session
* @param session
* @return
*/
@PostMapping("logout")
@Override
public JSONObject logout(HttpSession session) {
SESSION_MAP.remove(session.getId());
long userId;
try {
userId = DemoVerifier.getVisitorId(session);//必须在session.invalidate();前!
Log.d(TAG, "logout userId = " + userId + "; session.getId() = " + (session == null ? null : session.getId()));
super.logout(session);
} catch (Exception e) {
return DemoParser.newErrorResult(e);
}
JSONObject result = DemoParser.newSuccessResult();
JSONObject user = DemoParser.newSuccessResult();
user.put(ID, userId);
user.put(COUNT, 1);
result.put(StringUtil.firstCase(USER_), user);
return result;
}
private static final String REGISTER = "register";
/**注册
* @param request 只用String,避免encode后未decode
* @return
* @see
* <pre>
{
"Privacy": {
"phone": "13000082222",
"_password": "123456"
},
"User": {
"name": "APIJSONUser"
},
"verify": "1234"
}
* </pre>
*/
@PostMapping(REGISTER)
public JSONObject register(@RequestBody String request) {
JSONObject requestObject = null;
JSONObject privacyObj;
String phone;
String verify;
String password;
try {
requestObject = DemoParser.parseRequest(request);
privacyObj = requestObject.getJSONObject(PRIVACY_);
phone = StringUtil.getString(privacyObj.getString(PHONE));
verify = requestObject.getString(VERIFY);
password = privacyObj.getString(_PASSWORD);
if (StringUtil.isPhone(phone) == false) {
return newIllegalArgumentResult(requestObject, PRIVACY_ + "/" + PHONE);
}
if (StringUtil.isPassword(password) == false) {
return newIllegalArgumentResult(requestObject, PRIVACY_ + "/" + _PASSWORD);
}
if (StringUtil.isVerify(verify) == false) {
return newIllegalArgumentResult(requestObject, VERIFY);
}
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
JSONResponse response = new JSONResponse(headVerify(Verify.TYPE_REGISTER, phone, verify));
if (JSONResponse.isSuccess(response) == false) {
return response;
}
//手机号或验证码错误
if (JSONResponse.isExist(response.getJSONResponse(VERIFY_)) == false) {
return DemoParser.extendErrorResult(response, new ConditionErrorException("手机号或验证码错误!"));
}
//生成User和Privacy
if (StringUtil.isEmpty(requestObject.getString(JSONRequest.KEY_TAG), true)) {
requestObject.put(JSONRequest.KEY_TAG, REGISTER);
}
requestObject.put(JSONRequest.KEY_FORMAT, true);
response = new JSONResponse(
new DemoParser(POST).setNeedVerifyLogin(false).parseResponse(requestObject)
);
//验证User和Privacy
User user = response.getObject(User.class);
long userId = user == null ? 0 : BaseModel.value(user.getId());
Privacy privacy = response.getObject(Privacy.class);
long userId2 = privacy == null ? 0 : BaseModel.value(privacy.getId());
Exception e = null;
if (userId <= 0 || userId != userId2) { //id不同
e = new Exception("服务器内部错误!写入User或Privacy失败!");
}
if (e != null) { //出现错误,回退
new DemoParser(DELETE, false).parseResponse(
new JSONRequest(new User(userId))
);
new DemoParser(DELETE, false).parseResponse(
new JSONRequest(new Privacy(userId2))
);
}
return response;
}
/**
* @param requestObject
* @param key
* @return
*/
public static JSONObject newIllegalArgumentResult(JSONObject requestObject, String key) {
return newIllegalArgumentResult(requestObject, key, null);
}
/**
* @param requestObject
* @param key
* @param msg 详细说明
* @return
*/
public static JSONObject newIllegalArgumentResult(JSONObject requestObject, String key, String msg) {
return DemoParser.extendErrorResult(requestObject
, new IllegalArgumentException(key + ":value 中value不合法!" + StringUtil.getString(msg)));
}
/**设置密码
* @param request 只用String,避免encode后未decode
* @return
* @see
* <pre>
使用旧密码修改
{
"oldPassword": 123456,
"Privacy":{
"id": 13000082001,
"_password": "1234567"
}
}
或使用手机号+验证码修改
{
"verify": "1234",
"Privacy":{
"phone": "13000082001",
"_password": "1234567"
}
}
* </pre>
*/
@PostMapping("put/password")
public JSONObject putPassword(@RequestBody String request){
JSONObject requestObject = null;
String oldPassword;
String verify;
int type = Verify.TYPE_PASSWORD;
JSONObject privacyObj;
long userId;
String phone;
String password;
try {
requestObject = DemoParser.parseRequest(request);
oldPassword = StringUtil.getString(requestObject.getString(OLD_PASSWORD));
verify = StringUtil.getString(requestObject.getString(VERIFY));
requestObject.remove(OLD_PASSWORD);
requestObject.remove(VERIFY);
privacyObj = requestObject.getJSONObject(PRIVACY_);
if (privacyObj == null) {
throw new IllegalArgumentException(PRIVACY_ + " 不能为空!");
}
userId = privacyObj.getLongValue(ID);
phone = privacyObj.getString(PHONE);
password = privacyObj.getString(_PASSWORD);
if (StringUtil.isEmpty(password, true)) { //支付密码
type = Verify.TYPE_PAY_PASSWORD;
password = privacyObj.getString(_PAY_PASSWORD);
if (StringUtil.isNumberPassword(password) == false) {
throw new IllegalArgumentException(PRIVACY_ + "/" + _PAY_PASSWORD + ":value 中value不合法!");
}
} else { //登录密码
if (StringUtil.isPassword(password) == false) {
throw new IllegalArgumentException(PRIVACY_ + "/" + _PASSWORD + ":value 中value不合法!");
}
}
} catch (Exception e) {
return DemoParser.extendErrorResult(requestObject, e);
}
if (StringUtil.isPassword(oldPassword)) {
if (userId <= 0) { //手机号+验证码不需要userId
return DemoParser.extendErrorResult(requestObject, new IllegalArgumentException(ID + ":value 中value不合法!"));
}
if (oldPassword.equals(password)) {
return DemoParser.extendErrorResult(requestObject, new ConflictException("新旧密码不能一样!"));
}
//验证旧密码
Privacy privacy = new Privacy(userId);
if (type == Verify.TYPE_PASSWORD) {
privacy.setPassword(oldPassword);
} else {
privacy.setPayPassword(oldPassword);
}
JSONResponse response = new JSONResponse(
new DemoParser(HEAD, false).parseResponse(
new JSONRequest(privacy).setFormat(true)
)
);
if (JSONResponse.isExist(response.getJSONResponse(PRIVACY_)) == false) {
return DemoParser.extendErrorResult(requestObject, new ConditionErrorException("账号或原密码错误,请重新输入!"));
}
}
else if (StringUtil.isPhone(phone) && StringUtil.isVerify(verify)) {
JSONResponse response = new JSONResponse(headVerify(type, phone, verify));
if (JSONResponse.isSuccess(response) == false) {
return response;
}
if (JSONResponse.isExist(response.getJSONResponse(VERIFY_)) == false) {
return DemoParser.extendErrorResult(response, new ConditionErrorException("手机号或验证码错误!"));
}
response = new JSONResponse(
new DemoParser(GET, false).parseResponse(
new JSONRequest(
new Privacy().setPhone(phone)
)
)
);
Privacy privacy = response.getObject(Privacy.class);
long id = privacy == null ? 0 : BaseModel.value(privacy.getId());
privacyObj.remove(PHONE);
privacyObj.put(ID, id);