forked from opentiny/tiny-engine-backend-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoginController.java
More file actions
296 lines (269 loc) · 11.9 KB
/
LoginController.java
File metadata and controls
296 lines (269 loc) · 11.9 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
/**
* Copyright (c) 2023 - present TinyEngine Authors.
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
*
* Use of this source code is governed by an MIT-style license.
*
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
*
*/
package com.tinyengine.it.login.controller;
import com.tinyengine.it.common.base.Result;
import com.tinyengine.it.common.context.LoginUserContext;
import com.tinyengine.it.common.exception.ExceptionEnum;
import com.tinyengine.it.common.exception.ServiceException;
import com.tinyengine.it.common.log.SystemControllerLog;
import com.tinyengine.it.login.model.*;
import com.tinyengine.it.login.utils.JwtUtil;
import com.tinyengine.it.login.utils.SM3PasswordUtil;
import com.tinyengine.it.login.config.context.DefaultLoginUserContext;
import com.tinyengine.it.login.service.ConfigurablePasswordValidator;
import com.tinyengine.it.login.service.LoginService;
import com.tinyengine.it.login.service.TokenBlacklistService;
import com.tinyengine.it.mapper.AuthUsersUnitsRolesMapper;
import com.tinyengine.it.model.entity.App;
import com.tinyengine.it.model.entity.Tenant;
import com.tinyengine.it.model.entity.User;
import com.tinyengine.it.service.app.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
import static com.tinyengine.it.login.utils.SM2EncryptionUtil.decrypt;
import static com.tinyengine.it.login.utils.SM2EncryptionUtil.getPrivateKeyFromBase64;
/**
* Login Controller
*/
@Validated
@RestController
@CrossOrigin
@RequestMapping("/platform-center/api")
public class LoginController {
/**
* The User service.
*/
@Autowired
private UserService userService;
@Autowired
private LoginService loginService;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private TokenBlacklistService tokenBlacklistService;
@Autowired
ConfigurablePasswordValidator configurablePasswordValidator;
@Autowired
AuthUsersUnitsRolesMapper authUsersUnitsRolesMapper;
@Autowired
LoginUserContext loginUserContext;
/**
* 注册
*
* @param user the user
* @return user信息 result
*/
@Operation(summary = "注册", description = "注册",
parameters = {
@Parameter(name = "user", description = "User入参对象")
}, responses = {
@ApiResponse(responseCode = "200", description = "返回信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = App.class))),
@ApiResponse(responseCode = "400", description = "请求失败")}
)
@SystemControllerLog(description = "注册")
@PostMapping("/user/register")
public Result createUser(@Valid @RequestBody User user) throws Exception {
PasswordValidationResult passwordValidationResult = configurablePasswordValidator
.validateWithPolicy(user.getPassword());
if (!passwordValidationResult.isValid()) {
return Result.failed("密码格式检验失败", passwordValidationResult.getErrorMessage());
}
PasswordResult password = SM3PasswordUtil.createPassword(user.getPassword());
user.setPassword(password.getPasswordHash());
user.setSalt(password.getSalt());
User userResult = loginService.createUser(user);
return Result.success(userResult);
}
/**
* 登录
*
* @param user the user
* @return SSOTicket result
*/
@Operation(summary = "登录", description = "登录",
parameters = {
@Parameter(name = "user", description = "User入参对象")
}, responses = {
@ApiResponse(responseCode = "200", description = "返回信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = App.class))),
@ApiResponse(responseCode = "400", description = "请求失败")
})
@SystemControllerLog(description = "登录")
@PostMapping("/user/login")
public Result<SSOTicket> login(@RequestBody User user) throws Exception {
// 验证用户名密码
User userParam = new User();
userParam.setUsername(user.getUsername());
List<User> users = userService.queryUserByCondition(userParam);
if (users == null || users.isEmpty()) {
return Result.failed(ExceptionEnum.CM338);
}
User userResult = users.get(0);
PrivateKey privateKey = getPrivateKeyFromBase64(userResult.getPrivateKey());
String salt = decrypt(userResult.getSalt(), privateKey);
if (authenticate(salt, user.getPassword(), userResult.getPassword())) {
List<Tenant> tenants = authUsersUnitsRolesMapper.queryAllTenantByUserId(Integer.valueOf(userResult.getId()));
String token = jwtUtil.generateToken(user.getUsername(), "USER", userResult.getId(),
tenants, 1);
// 创建SSO票据
SSOTicket ticket = new SSOTicket();
ticket.setToken(token);
ticket.setUsername(user.getUsername());
ticket.setExpireTime(System.currentTimeMillis() + 3600000);
return Result.success(ticket);
}
return Result.failed(ExceptionEnum.CM004);
}
/**
* 忘记密码
*
* @param user the user
* @return SSOTicket result
*/
@Operation(summary = "忘记密码", description = "忘记密码",
parameters = {
@Parameter(name = "user", description = "User入参对象")
}, responses = {
@ApiResponse(responseCode = "200", description = "返回信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = App.class))),
@ApiResponse(responseCode = "400", description = "请求失败")
})
@SystemControllerLog(description = "忘记密码")
@PostMapping("/user/forgot-password")
public Result forgotPassword(@RequestBody User user) throws Exception {
PasswordValidationResult passwordValidationResult = configurablePasswordValidator
.validateWithPolicy(user.getPassword());
if (!passwordValidationResult.isValid()) {
return Result.success(passwordValidationResult);
}
PasswordResult password = SM3PasswordUtil.createPassword(user.getPassword());
user.setPassword(password.getPasswordHash());
user.setSalt(password.getSalt());
return loginService.forgotPassword(user);
}
/**
* 验证令牌
*
* @param token the token
* @return ValidationResult result
*/
@Operation(summary = "验证令牌", description = "验证令牌",
parameters = {
@Parameter(name = "user", description = "User入参对象")
}, responses = {
@ApiResponse(responseCode = "200", description = "返回信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = App.class))),
@ApiResponse(responseCode = "400", description = "请求失败")
})
@SystemControllerLog(description = "验证令牌")
@GetMapping("/user/validate")
public Result<ValidationResult> validateToken(@RequestParam String token) {
if (jwtUtil.validateToken(token)) {
String username = jwtUtil.getUsernameFromToken(token);
return Result.success(new ValidationResult(true, username));
}
return Result.success(new ValidationResult(false, null));
}
/**
* 设置当前组织
*
* @param tenantId the tenantId
* @return result
*/
@Operation(summary = "设置当前组织", description = "设置当前组织",
parameters = {
@Parameter(name = "tenantId", description = "组织id")
}, responses = {
@ApiResponse(responseCode = "200", description = "返回信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = App.class))),
@ApiResponse(responseCode = "400", description = "请求失败")
})
@SystemControllerLog(description = "设置当前组织")
@GetMapping("/user/tenant")
public Result<SSOTicket> setTenant(@RequestParam Integer tenantId) {
int userIdInt;
String userId = loginUserContext.getLoginUserId();
try {
userIdInt = Integer.parseInt(userId);
} catch (NumberFormatException e) {
return Result.failed(ExceptionEnum.CM342);
}
List<Tenant> tenants = authUsersUnitsRolesMapper.queryAllTenantByUserId(userIdInt);
if (tenantId == null) {
return Result.failed(ExceptionEnum.CM320);
}
if (tenants == null || tenants.isEmpty()) {
return Result.failed(ExceptionEnum.CM337);
}
List<Tenant> tenantList = new ArrayList<>();
boolean found = false;
for (Tenant tenant : tenants) {
if (tenant.getId().equals(tenantId.toString())) {
tenant.setIsInUse(true);
found = true;
} else {
tenant.setIsInUse(false);
}
tenantList.add(tenant);
}
if (!found) {
return Result.failed(ExceptionEnum.CM341);
}
//存储当前组织到LoginUserContext
UserInfo currentUser = DefaultLoginUserContext.getCurrentUser();
currentUser.setTenants(tenantList);
DefaultLoginUserContext.setCurrentUser(currentUser);
// 通过 RequestContextHolder 获取请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
String authHeader = request.getHeader("Authorization");
String headerToken = jwtUtil.getTokenFromRequest(authHeader);
if (headerToken == null || headerToken.isEmpty()) {
return Result.failed(ExceptionEnum.CM336);
}
// 创建SSO票据
SSOTicket ticket = new SSOTicket();
ticket.setToken(headerToken);
ticket.setUsername(DefaultLoginUserContext.getCurrentUser().getUsername());
ticket.setExpireTime(System.currentTimeMillis() + 3600000);
return Result.success(ticket);
}
private boolean authenticate(String salt, String password, String userPassword) throws Exception {
return SM3PasswordUtil.verifyPassword(password, userPassword, salt);
}
}