UserController.java
13.5 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
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.domain.Store;
import com.uccc.admin.exception.ApiException;
import com.uccc.admin.service.PermissionService;
import com.uccc.admin.service.UserService;
import com.uccc.pretty.common.Result;
import com.uccc.pretty.common.SystemLog;
import com.uccc.pretty.common.User;
import com.uccc.pretty.common.UserEntity;
import com.uccc.pretty.constants.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
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;
/**
* 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());
String jsonString = JSONObject.toJSONString(user);
UserEntity userEntity = JSONObject.parseObject(jsonString,UserEntity.class);
//签发token
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE,30);
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) {
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, @RequestParam String ip, HttpServletRequest request) throws NullPointerException{
if (ip == null) throw new ApiException(ErrorCode.IP_NOT_FOUND);
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());
}
String token = request.getHeader("token");
String userId = JWT.decode(token).getAudience().get(0);
SystemLog systemLog = new SystemLog(Long.parseLong(userId),USER_CREATE.getMessage(),USER_CREATE.getMessage(),new Date(),"create user result is:"+createResult,ip);
userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
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;
}
}