UserController.java
23 KB
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
package com.uccc.admin.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.uccc.admin.domain.Permission;
import com.uccc.admin.exception.ApiException;
import com.uccc.admin.service.PermissionService;
import com.uccc.admin.service.UserService;
import com.uccc.pretty.common.*;
import com.uccc.pretty.constants.ErrorCode;
import com.uccc.pretty.constants.StoreEnum;
import com.uccc.pretty.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.uccc.pretty.constants.ActionEnum.*;
import static com.uccc.pretty.constants.ResultEnum.RESULT_ERR;
import static com.uccc.pretty.constants.ResultEnum.RESULT_OK;
import static com.uccc.pretty.constants.UserStatusEnum.*;
/**
* Created by bert on 2021-09-11 11:50
*/
@RestController
@RequestMapping("/admin/")
public class UserController {
private Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@Autowired
private PermissionService permissionService;
@Value("${store.logo.url}")
private String storeLogoUrl;
@Value("${store.service.url}")
private String storeServiceUrl;
@Value("${store.logo.prefix}")
private String logoPrefix;
@Value("${store.service.prefix}")
private String servicePrefix;
/**
* login in
* @param user
* @param ip
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "login",method = RequestMethod.POST)
public Result doLogin(@RequestBody User user, @RequestParam String ip) throws NullPointerException{
if (ip == null) throw new ApiException(ErrorCode.IP_NOT_FOUND);
Result result = new Result();
if (user == null) {
throw new ApiException(ErrorCode.USER_LOGIN_WRONG);
}else {
logger.info("user:{}", user.toString());
if (user.getAccount() == null) {
throw new ApiException(ErrorCode.USER_ACCOUNT_NOT_FOUND);
}else if (user.getPassword() == null){
throw new ApiException(ErrorCode.USER_PASSWORD_NOT_FOUND);
}
byte[] pwdBytes = user.getPassword().getBytes();
//base64 encode
String pwdEncoded = Base64.getEncoder().encodeToString(pwdBytes);
user.setPassword(pwdEncoded);
user = userService.getUserByCondition(user);
if (user == null) throw new ApiException(ErrorCode.USER_PASSWORD_WRONG);
if (user.getStatus() == USER_STATUS_OFF.getCode() || user.getStatus() == USER_STATUS_FROZEN.getCode()) {
throw new ApiException(ErrorCode.LOGIN_ACCOUNT_CLOSE);
}
//get user permission
List<Permission> permissionList = permissionService.getPermissionByUserId(user.getId());
if (permissionList.size() == 0) {
throw new ApiException(ErrorCode.USER_PERMISSION_NOT_FOUND);
}else {
// String[] permissions = permissionService.formatPermissions(permissionList);
JSONArray jsonArray = permissionService.formatPermissions(permissionList);
user.setPermission(jsonArray);
int[] roleIds = permissionService.formatRoleIds(permissionList);
user.setRoleIds(roleIds);
}
User updateUser = new User();
updateUser.setId(user.getId());
updateUser.setLastLoginIp(ip);
updateUser.setLastLoginTime(new Date());
userService.updateUser(updateUser);
SystemLog systemLog = new SystemLog(user.getId(),USER_LOGIN.getMessage(),USER_LOGIN.getMessage(),new Date(),"",ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
}
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
if (user.getStoreId() != null) {
Store store = userService.checkStoreByMid(Long.valueOf(user.getStoreId()));
user.setStore(store);
}
String jsonString = JSONObject.toJSONString(user);
UserEntity userEntity = JSONObject.parseObject(jsonString,UserEntity.class);
//签发token
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR,12);
Date date = calendar.getTime();
String token= JWT.create().withAudience(userEntity.getId().toString(),user.getPassword()).withExpiresAt(date) // 将有效期放入token中
.sign(Algorithm.HMAC256(user.getPassword()));
userEntity.setToken(token);
result.setData(userEntity);
return result;
}
/**
* logout
* @param ip
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "logout",method = RequestMethod.POST)
public Result logout(@RequestParam String ip,
HttpServletRequest request) throws NullPointerException{
Result result = new Result();
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
String token = request.getHeader("token");
String userId = JWT.decode(token).getAudience().get(0);
SystemLog systemLog = new SystemLog(Long.parseLong(userId),USER_LOGOUT.getMessage(),USER_LOGOUT.getMessage(),new Date(),"logout userId is: " + userId,ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
return result;
}
/**
* update user
* @param user
* @param ip
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "user",method = RequestMethod.PUT)
public Result modifyUser (@RequestBody User user, @RequestParam String ip, HttpServletRequest request) throws NullPointerException{
if (ip == null) throw new ApiException(ErrorCode.IP_NOT_FOUND);
Result result = new Result();
if (user.getId() == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);
if (user.getPassword() != null) {
byte[] pwdBytes = user.getPassword().getBytes();
//base64 encode
String pwdEncoded = Base64.getEncoder().encodeToString(pwdBytes);
user.setPassword(pwdEncoded);
}
//check user exist
User check = new User();
check.setId(user.getId());
check = userService.getUserByCondition(check);
if (check == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);
String token = request.getHeader("token");
String userId = JWT.decode(token).getAudience().get(0);
SystemLog systemLog = new SystemLog(Long.parseLong(userId),USER_INFO_MODIFY.getMessage(),USER_INFO_MODIFY.getMessage(),new Date(),"modify user id is"+user.getId(),ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
boolean updateResult = userService.updateUser(user);
if (updateResult) {
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
}else {
throw new ApiException(ErrorCode.USER_INFO_UPDATE_FAILED);
}
return result;
}
/**
* search users or admin
* @param
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "users",method = RequestMethod.GET)
public Result findUsers (@RequestParam(name = "limit", required = false) Integer limit,
@RequestParam(name = "page", required = false) Integer page,
@RequestParam(name = "keywords", required = false) String keywords,
@RequestParam(name = "admin_level", required = false) Integer adminLevel,
@RequestParam(name = "status", required = false) Integer status,
@RequestParam(name = "delete", required = false) Integer delete) throws NullPointerException{
Result result = new Result();
User user = new User();
user.setLimit(limit);
user.setAdminLevel(adminLevel);
if (page != null) {
page = page-1;
}
user.setPage(page);
user.setStatus(status);
user.setDelete(delete);
user.setKeywords(keywords);
List<UserEntity> userEntities = userService.getUserListByCondition(user);
int userEntitiesCount = userService.getUserListCountByCondition(user);
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
JSONObject json = new JSONObject();
json.put("count", userEntitiesCount);
json.put("rows", userEntities);
result.setData(json);
return result;
}
/**
* search user by id
* @param id
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "user/{id}",method = RequestMethod.GET)
public Result findUser (@PathVariable Long id) throws NullPointerException{
Result result = new Result();
User user = new User();
user.setId(id);
List<UserEntity> userEntities = userService.getUserListByCondition(user);
if (userEntities.size() == 1) {
//get user permission
List<Permission> permissionList = permissionService.getPermissionByUserId(user.getId());
if (permissionList.size() > 0) {
int[] roleIds = permissionService.formatRoleIds(permissionList);
userEntities.get(0).setRoleIds(roleIds);
}
result.setData(userEntities.get(0));
}else {
throw new ApiException(ErrorCode.SEARCH_FAILED);
}
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
return result;
}
/**
* add user
* @param user
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "add_user",method = RequestMethod.POST)
public Result createUser (@RequestBody User user) throws NullPointerException{
Result result = new Result();
if (user.getAccount().equals("")) {
throw new ApiException(ErrorCode.USER_ACCOUNT_NOT_FOUND);
}else if (user.getPassword().equals("")){
throw new ApiException(ErrorCode.USER_PASSWORD_NOT_FOUND);
}else if (user.getName().equals("")) {
throw new ApiException(ErrorCode.USER_NAME_NOT_FOUND);
}else if (user.getPhone().equals("")) {
throw new ApiException(ErrorCode.USER_PHONE_NOT_FOUND);
}else if (user.getRoleIds().length == 0) {
throw new ApiException(ErrorCode.USER_ROLE_NOT_FOUND);
}
//check account repeat
int accountCount = userService.checkAccountRepeat(user.getAccount());
if (accountCount > 0) throw new ApiException(ErrorCode.USER_ACCOUNT_REPEAT);
byte[] pwdBytes = user.getPassword().getBytes();
//base64 encode
String pwdEncoded = Base64.getEncoder().encodeToString(pwdBytes);
user.setPassword(pwdEncoded);
user.setCts(new Date());
user.setUts(new Date());
boolean createResult = userService.createUser(user, user.getRoleIds());
if (createResult) {
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
}else {
result.setCode(RESULT_ERR.getCode());
result.setMessage(RESULT_ERR.getMessage());
}
return result;
}
/**
* delete user
* @param id
* @param ip
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "user",method = RequestMethod.DELETE)
public Result deleteUser (@RequestParam Long id, @RequestParam String ip, HttpServletRequest request) throws NullPointerException{
if (ip == null) throw new ApiException(ErrorCode.IP_NOT_FOUND);
Result result = new Result();
User user = new User();
user.setId(id);
if (user.getId() == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);
boolean updateResult = userService.deleteUser(user);
if (updateResult) {
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
}else {
throw new ApiException(ErrorCode.USER_INFO_UPDATE_FAILED);
}
String token = request.getHeader("token");
String userId = JWT.decode(token).getAudience().get(0);
SystemLog systemLog = new SystemLog(Long.parseLong(userId),USER_INFO_MODIFY.getMessage(),USER_INFO_MODIFY.getMessage(),new Date(),"delete user id is"+user.getId(),ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
return result;
}
/**
* check is store by mid
*/
@RequestMapping(value = "check_mid/{mid}",method = RequestMethod.GET)
public Result checkMid(@PathVariable Long mid) throws NullPointerException{
Result result = new Result();
//mid start with 10000
logger.info("mid:{}", mid);
Store store = userService.checkStoreByMid(mid);
if (store == null) {
throw new ApiException(ErrorCode.STORE_CLOSE);
}else {
if (store.getId() > 0) {
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
result.setData(store);
}else {
result.setCode(RESULT_ERR.getCode());
result.setMessage(RESULT_ERR.getMessage());
}
}
return result;
}
/**
* api for mall
* @param userId
* @param logoFile
* @param serviceFile
* @param name
* @return
* @throws NullPointerException
*/
@RequestMapping(value = "apply_store/{userId}",method = RequestMethod.POST)
public Result applyStore(@PathVariable Long userId,
@RequestParam(name="logoFile", required = false) MultipartFile logoFile,
@RequestParam(name="serviceFile", required = false) MultipartFile serviceFile,
@RequestParam("name") String name,
@RequestParam String ip) throws NullPointerException{
Result result = new Result();
User user = new User();
user.setId(userId);
user = userService.getUserByCondition(user);
if (user == null) throw new ApiException(ErrorCode.LOGIN_ACCOUNT_CLOSE);
if (user.getStoreId() != null) throw new ApiException(ErrorCode.USER_STORE_EXIST);
Store store = new Store();
store.setName(name);
if (store.getName() == null || store.getName().equals("")) throw new ApiException(ErrorCode.INVALID_PARAM);
int storeNameRepeat = userService.checkStoreNameRepeat(store.getName());
if (storeNameRepeat > 0) throw new ApiException(ErrorCode.STORE_NAME_REPEAT);
store.setCts(new Date());
store.setUts(new Date());
store.setKeeper(userId);
store.setStatus(StoreEnum.STORE_APPLYING.getCode());
int createStore = userService.createStore(store);
if (createStore > 0) {
store = userService.findStoreByName(store.getName());
logger.info("store:{}", store.toString());
if (logoFile != null) {
if (!logoFile.isEmpty()) { //logo upload & update logo_url
String fileType = logoFile.getOriginalFilename().substring(logoFile.getOriginalFilename().lastIndexOf("."));
boolean upLoadRes = FileUtil.approvalFile(logoFile, storeLogoUrl, "logo" + "_" + store.getId() + fileType);
if (upLoadRes) {//update logo_url
store.setLogoUrl(logoPrefix + "logo" + "_" + store.getId() + fileType);
userService.updateStore(store);
}
}
}
if (serviceFile != null) {
if (!serviceFile.isEmpty()) { //img upload & update service_url
String fileType = serviceFile.getOriginalFilename().substring(serviceFile.getOriginalFilename().lastIndexOf("."));
boolean upLoadRes = FileUtil.approvalFile(serviceFile, storeServiceUrl, "csd" + "_" + store.getId() + fileType);
if (upLoadRes) {//update service_url
store.setServiceUrl(servicePrefix + "csd" + "_" + store.getId() + fileType);
userService.updateStore(store);
}
}
}
user.setStoreId(store.getId());
boolean updateUser = userService.updateUser(user);
if (!updateUser) throw new ApiException(ErrorCode.UPDATE_FAILED);
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
SystemLog systemLog = new SystemLog(userId,APPLY_STORE.getMessage(),APPLY_STORE.getMessage(),new Date(),"用户 id:"+userId + "申请开店",ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
}else {
throw new ApiException(ErrorCode.CREATE_FAILED);
}
return result;
}
@RequestMapping(value = "store_list",method = RequestMethod.GET)
public Result storeList(@RequestParam(name = "limit", required = false) Integer limit,
@RequestParam(name = "page", required = false) Integer page,
@RequestParam(name = "status", required = false) String status,
@RequestParam(name = "keeper", required = false) String keeper,
@RequestParam(name = "name", required = false) String name) throws NullPointerException{
Result result = new Result();
Store store = new Store();
if (status != null) {
store.setStatus(Integer.parseInt(status));
}
if (keeper != null) {
store.setKeeper(Long.parseLong(keeper));
}
if (name != null) {
store.setName(name);
}
List<StoreEntity> storeEntities = userService.getStoreByCondition(store, limit, page-1);
int storeEntitiesCount = userService.getStoreCountByCondition(store);
JSONObject json = new JSONObject();
json.put("count", storeEntitiesCount);
json.put("rows", storeEntities);
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
result.setData(json);
return result;
}
@RequestMapping(value = "store/{storeId}",method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result modifyStore (@PathVariable Integer storeId,
@RequestParam(value= "name", required = false) String name,
@RequestParam(value= "status", required = false) String status,
@RequestParam(value= "failReason", required = false) String failReason,
@RequestParam(value= "ip") String ip, HttpServletRequest request,
@RequestParam(value= "logoFile", required = false) MultipartFile logoFile,
@RequestParam(value= "serviceFile", required = false) MultipartFile serviceFile) throws NullPointerException{
Result result = new Result();
Store store = new Store();
if (storeId==null) throw new ApiException(ErrorCode.INVALID_PARAM);
store.setId(storeId);
if (name != null) {
store.setName(name);
}
if (status != null) {
store.setStatus(Integer.valueOf(status));
}
if (store.getStatus() != null) {
if (store.getStatus() == StoreEnum.STORE_RUNNING.getCode()) {//申请通过
//允许开店 查询到完整的store信息后 根据keeper对应user表id 把store表id赋值user表store_id
Store checkStore = userService.checkStoreByMid(Long.valueOf(store.getId()));
if (checkStore == null) throw new ApiException(ErrorCode.UPDATE_FAILED);
User user = new User();
user.setId(checkStore.getKeeper());
user.setStoreId(store.getId());
boolean updateUser = userService.updateUser(user);
if (!updateUser) throw new ApiException(ErrorCode.UPDATE_FAILED);
//修改该用户权限,从role_id3改为4
User changeRole = new User();
changeRole.setId(checkStore.getKeeper());
changeRole.setRoleIds(new int[]{4});//暂时写死申请通过后的权限
boolean changeRoleRes = userService.updateUser(changeRole);
if (!changeRoleRes) throw new ApiException(ErrorCode.UPDATE_FAILED);
}
if (store.getStatus() == StoreEnum.STORE_FAILED.getCode()) {//申请失败
if (failReason != null) {
store.setFailReason(failReason);
}
}
}
if (logoFile != null) {
if (!logoFile.isEmpty()) { //logo upload & update logo_url
String fileType = logoFile.getOriginalFilename().substring(logoFile.getOriginalFilename().lastIndexOf("."));
boolean upLoadRes = FileUtil.approvalFile(logoFile, storeLogoUrl, "logo" + "_" + store.getId() + fileType);
if (upLoadRes) {//update logo_url
store.setLogoUrl(logoPrefix + "logo" + "_" + store.getId() + fileType);
}
}
}
if (serviceFile != null) {
if (!serviceFile.isEmpty()) { //img upload & update service_url
String fileType = serviceFile.getOriginalFilename().substring(serviceFile.getOriginalFilename().lastIndexOf("."));
boolean upLoadRes = FileUtil.approvalFile(serviceFile, storeServiceUrl, "csd" + "_" + store.getId() + fileType);
if (upLoadRes) {//update service_url
store.setServiceUrl(servicePrefix + "csd" + "_" + store.getId() + fileType);
}
}
}
int res = userService.updateStore(store);
String token = request.getHeader("token");
String userId = JWT.decode(token).getAudience().get(0);
SystemLog systemLog = new SystemLog(Long.parseLong(userId),MODIFY_STORE.getMessage(),MODIFY_STORE.getMessage(),new Date(),"修改店铺id为:" + store.getId(),ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
if (res > 0) {
result.setCode(RESULT_OK.getCode());
result.setMessage(RESULT_OK.getMessage());
}else {
result.setCode(RESULT_ERR.getCode());
result.setMessage(RESULT_ERR.getMessage());
}
return result;
}
}