🎨 Improving structure / format of the code. 代码格式化

This commit is contained in:
lbw 2021-07-30 08:54:34 +08:00
parent 67ed0368f1
commit fefdc8db32
22 changed files with 157 additions and 133 deletions

View File

@ -73,4 +73,5 @@ public class ConsoleConfig {
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() { public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(ZoneId.systemDefault().toString()); return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(ZoneId.systemDefault().toString());
} }
} }

View File

@ -51,10 +51,10 @@ public class HealthController {
} }
/** /**
* Whether the Nacos is in broken states or not, and cannot recover except by being restarted. * Whether the Nacos is in broken states or not, and cannot recover except by being
* * restarted.
* @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code equal to 500 indicates that * @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code
* Nacos is in broken states. * equal to 500 indicates that Nacos is in broken states.
*/ */
@GetMapping("/liveness") @GetMapping("/liveness")
public ResponseEntity<String> liveness() { public ResponseEntity<String> liveness() {
@ -63,9 +63,8 @@ public class HealthController {
/** /**
* Ready to receive the request or not. * Ready to receive the request or not.
* * @return HTTP code equal to 200 indicates that Nacos is ready. HTTP code equal to
* @return HTTP code equal to 200 indicates that Nacos is ready. HTTP code equal to 500 indicates that Nacos is not * 500 indicates that Nacos is not ready.
* ready.
*/ */
@GetMapping("/readiness") @GetMapping("/readiness")
public ResponseEntity<String> readiness(HttpServletRequest request) { public ResponseEntity<String> readiness(HttpServletRequest request) {
@ -77,7 +76,8 @@ public class HealthController {
} }
if (!isConfigReadiness && !isNamingReadiness) { if (!isConfigReadiness && !isNamingReadiness) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config and Naming are not in readiness"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Config and Naming are not in readiness");
} }
if (!isConfigReadiness) { if (!isConfigReadiness) {
@ -92,7 +92,8 @@ public class HealthController {
try { try {
persistService.configInfoCount(""); persistService.configInfoCount("");
return true; return true;
} catch (Exception e) { }
catch (Exception e) {
LOGGER.error("Config health check fail.", e); LOGGER.error("Config health check fail.", e);
} }
return false; return false;
@ -102,9 +103,11 @@ public class HealthController {
try { try {
apiCommands.metrics(request); apiCommands.metrics(request);
return true; return true;
} catch (Exception e) { }
catch (Exception e) {
LOGGER.error("Naming health check fail.", e); LOGGER.error("Naming health check fail.", e);
} }
return false; return false;
} }
} }

View File

@ -75,8 +75,7 @@ public class NamespaceController {
/** /**
* Get namespace list. * Get namespace list.
* * @param request request
* @param request request
* @param response response * @param response response
* @return namespace list * @return namespace list
*/ */
@ -84,8 +83,8 @@ public class NamespaceController {
public RestResult<List<Namespace>> getNamespaces(HttpServletRequest request, HttpServletResponse response) { public RestResult<List<Namespace>> getNamespaces(HttpServletRequest request, HttpServletResponse response) {
// TODO 获取用kp // TODO 获取用kp
List<TenantInfo> tenantInfos = persistService.findTenantByKp(DEFAULT_KP); List<TenantInfo> tenantInfos = persistService.findTenantByKp(DEFAULT_KP);
Namespace namespace0 = new Namespace("", DEFAULT_NAMESPACE, DEFAULT_QUOTA, persistService.configInfoCount(DEFAULT_TENANT), Namespace namespace0 = new Namespace("", DEFAULT_NAMESPACE, DEFAULT_QUOTA,
NamespaceTypeEnum.GLOBAL.getType()); persistService.configInfoCount(DEFAULT_TENANT), NamespaceTypeEnum.GLOBAL.getType());
List<Namespace> namespaces = new ArrayList<Namespace>(); List<Namespace> namespaces = new ArrayList<Namespace>();
namespaces.add(namespace0); namespaces.add(namespace0);
for (TenantInfo tenantInfo : tenantInfos) { for (TenantInfo tenantInfo : tenantInfos) {
@ -99,32 +98,32 @@ public class NamespaceController {
/** /**
* get namespace all info by namespace id. * get namespace all info by namespace id.
* * @param request request
* @param request request * @param response response
* @param response response
* @param namespaceId namespaceId * @param namespaceId namespaceId
* @return namespace all info * @return namespace all info
*/ */
@GetMapping(params = "show=all") @GetMapping(params = "show=all")
public NamespaceAllInfo getNamespace(HttpServletRequest request, HttpServletResponse response, public NamespaceAllInfo getNamespace(HttpServletRequest request, HttpServletResponse response,
@RequestParam("namespaceId") String namespaceId) { @RequestParam("namespaceId") String namespaceId) {
// TODO 获取用kp // TODO 获取用kp
if (StringUtils.isBlank(namespaceId)) { if (StringUtils.isBlank(namespaceId)) {
return new NamespaceAllInfo(namespaceId, DEFAULT_NAMESPACE_SHOW_NAME, DEFAULT_QUOTA, persistService.configInfoCount(DEFAULT_TENANT), return new NamespaceAllInfo(namespaceId, DEFAULT_NAMESPACE_SHOW_NAME, DEFAULT_QUOTA,
NamespaceTypeEnum.GLOBAL.getType(), DEFAULT_NAMESPACE_DESCRIPTION); persistService.configInfoCount(DEFAULT_TENANT), NamespaceTypeEnum.GLOBAL.getType(),
} else { DEFAULT_NAMESPACE_DESCRIPTION);
}
else {
TenantInfo tenantInfo = persistService.findTenantByKp(DEFAULT_KP, namespaceId); TenantInfo tenantInfo = persistService.findTenantByKp(DEFAULT_KP, namespaceId);
int configCount = persistService.configInfoCount(namespaceId); int configCount = persistService.configInfoCount(namespaceId);
return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), DEFAULT_QUOTA, configCount, NamespaceTypeEnum.CUSTOM.getType(), return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), DEFAULT_QUOTA, configCount,
tenantInfo.getTenantDesc()); NamespaceTypeEnum.CUSTOM.getType(), tenantInfo.getTenantDesc());
} }
} }
/** /**
* create namespace. * create namespace.
* * @param request request
* @param request request * @param response response
* @param response response
* @param namespaceName namespace Name * @param namespaceName namespace Name
* @param namespaceDesc namespace Desc * @param namespaceDesc namespace Desc
* @return whether create ok * @return whether create ok
@ -132,12 +131,13 @@ public class NamespaceController {
@PostMapping @PostMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(HttpServletRequest request, HttpServletResponse response, public Boolean createNamespace(HttpServletRequest request, HttpServletResponse response,
@RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName, @RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) { @RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) {
// TODO 获取用kp // TODO 获取用kp
if (StringUtils.isBlank(namespaceId)) { if (StringUtils.isBlank(namespaceId)) {
namespaceId = UUID.randomUUID().toString(); namespaceId = UUID.randomUUID().toString();
} else { }
else {
namespaceId = namespaceId.trim(); namespaceId = namespaceId.trim();
if (!namespaceIdCheckPattern.matcher(namespaceId).matches()) { if (!namespaceIdCheckPattern.matcher(namespaceId).matches()) {
return false; return false;
@ -149,14 +149,13 @@ public class NamespaceController {
return false; return false;
} }
} }
persistService.insertTenantInfoAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc, DEFAULT_CREATE_SOURCE, persistService.insertTenantInfoAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc,
System.currentTimeMillis()); DEFAULT_CREATE_SOURCE, System.currentTimeMillis());
return true; return true;
} }
/** /**
* check namespaceId exist. * check namespaceId exist.
*
* @param namespaceId namespace id * @param namespaceId namespace id
* @return true if exist, otherwise false * @return true if exist, otherwise false
*/ */
@ -170,17 +169,16 @@ public class NamespaceController {
/** /**
* edit namespace. * edit namespace.
* * @param namespace namespace
* @param namespace namespace
* @param namespaceShowName namespace ShowName * @param namespaceShowName namespace ShowName
* @param namespaceDesc namespace Desc * @param namespaceDesc namespace Desc
* @return whether edit ok * @return whether edit ok
*/ */
@PutMapping @PutMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean editNamespace(@RequestParam("namespace") String namespace, public Boolean editNamespace(@RequestParam("namespace") String namespace,
@RequestParam("namespaceShowName") String namespaceShowName, @RequestParam("namespaceShowName") String namespaceShowName,
@RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) { @RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) {
// TODO 获取用kp // TODO 获取用kp
persistService.updateTenantNameAtomic(DEFAULT_KP, namespace, namespaceShowName, namespaceDesc); persistService.updateTenantNameAtomic(DEFAULT_KP, namespace, namespaceShowName, namespaceDesc);
return true; return true;
@ -188,16 +186,15 @@ public class NamespaceController {
/** /**
* del namespace by id. * del namespace by id.
* * @param request request
* @param request request * @param response response
* @param response response
* @param namespaceId namespace Id * @param namespaceId namespace Id
* @return whether del ok * @return whether del ok
*/ */
@DeleteMapping @DeleteMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse response, public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse response,
@RequestParam("namespaceId") String namespaceId) { @RequestParam("namespaceId") String namespaceId) {
persistService.removeTenantInfoAtomic(DEFAULT_KP, namespaceId); persistService.removeTenantInfoAtomic(DEFAULT_KP, namespaceId);
return true; return true;
} }

View File

@ -45,25 +45,23 @@ public class PermissionController {
/** /**
* Query permissions of a role. * Query permissions of a role.
* * @param role the role
* @param role the role * @param pageNo page index
* @param pageNo page index
* @param pageSize page size * @param pageSize page size
* @return permission of a role * @return permission of a role
*/ */
@GetMapping @GetMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.READ) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.READ)
public Object getPermissions(@RequestParam int pageNo, @RequestParam int pageSize, public Object getPermissions(@RequestParam int pageNo, @RequestParam int pageSize,
@RequestParam(name = "role", defaultValue = StringUtils.EMPTY) String role) { @RequestParam(name = "role", defaultValue = StringUtils.EMPTY) String role) {
return nacosRoleService.getPermissionsFromDatabase(role, pageNo, pageSize); return nacosRoleService.getPermissionsFromDatabase(role, pageNo, pageSize);
} }
/** /**
* Add a permission to a role. * Add a permission to a role.
* * @param role the role
* @param role the role
* @param resource the related resource * @param resource the related resource
* @param action the related action * @param action the related action
* @return ok if succeed * @return ok if succeed
*/ */
@PostMapping @PostMapping
@ -75,17 +73,17 @@ public class PermissionController {
/** /**
* Delete a permission from a role. * Delete a permission from a role.
* * @param role the role
* @param role the role
* @param resource the related resource * @param resource the related resource
* @param action the related action * @param action the related action
* @return ok if succeed * @return ok if succeed
*/ */
@DeleteMapping @DeleteMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE)
public Object deletePermission(@RequestParam String role, @RequestParam String resource, public Object deletePermission(@RequestParam String role, @RequestParam String resource,
@RequestParam String action) { @RequestParam String action) {
nacosRoleService.deletePermission(role, resource, action); nacosRoleService.deletePermission(role, resource, action);
return RestResultUtils.success("delete permission ok!"); return RestResultUtils.success("delete permission ok!");
} }
} }

View File

@ -47,8 +47,7 @@ public class RoleController {
/** /**
* Get roles list. * Get roles list.
* * @param pageNo number index of page
* @param pageNo number index of page
* @param pageSize page size * @param pageSize page size
* @param username optional, username of user * @param username optional, username of user
* @return role list * @return role list
@ -56,13 +55,12 @@ public class RoleController {
@GetMapping @GetMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ)
public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize, public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize,
@RequestParam(name = "username", defaultValue = "") String username) { @RequestParam(name = "username", defaultValue = "") String username) {
return roleService.getRolesFromDatabase(username, pageNo, pageSize); return roleService.getRolesFromDatabase(username, pageNo, pageSize);
} }
/** /**
* Fuzzy matching role name . * Fuzzy matching role name .
*
* @param role role id * @param role role id
* @return role list * @return role list
*/ */
@ -75,9 +73,10 @@ public class RoleController {
/** /**
* Add a role to a user * Add a role to a user
* *
* <p>This method is used for 2 functions: 1. create a role and bind it to GLOBAL_ADMIN. 2. bind a role to an user. * <p>
* * This method is used for 2 functions: 1. create a role and bind it to GLOBAL_ADMIN.
* @param role role name * 2. bind a role to an user.
* @param role role name
* @param username username * @param username username
* @return Code 200 and message 'add role ok!' * @return Code 200 and message 'add role ok!'
*/ */
@ -90,18 +89,18 @@ public class RoleController {
/** /**
* Delete a role. If no username is specified, all users under this role are deleted. * Delete a role. If no username is specified, all users under this role are deleted.
* * @param role role
* @param role role
* @param username username * @param username username
* @return ok if succeed * @return ok if succeed
*/ */
@DeleteMapping @DeleteMapping
@Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE)
public Object deleteRole(@RequestParam String role, public Object deleteRole(@RequestParam String role,
@RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) { @RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) {
if (StringUtils.isBlank(username)) { if (StringUtils.isBlank(username)) {
roleService.deleteRole(role); roleService.deleteRole(role);
} else { }
else {
roleService.deleteRole(role, username); roleService.deleteRole(role, username);
} }
return RestResultUtils.success("delete role of user " + username + " ok!"); return RestResultUtils.success("delete role of user " + username + " ok!");

View File

@ -37,7 +37,6 @@ public class ServerStateController {
/** /**
* Get server state of current server. * Get server state of current server.
*
* @return state json. * @return state json.
*/ */
@GetMapping("/state") @GetMapping("/state")

View File

@ -65,7 +65,7 @@ import java.util.Objects;
* @author nkorange * @author nkorange
*/ */
@RestController("user") @RestController("user")
@RequestMapping({"/v1/auth", "/v1/auth/users"}) @RequestMapping({ "/v1/auth", "/v1/auth/users" })
public class UserController { public class UserController {
@Autowired @Autowired
@ -88,7 +88,6 @@ public class UserController {
/** /**
* Create a new user. * Create a new user.
*
* @param username username * @param username username
* @param password password * @param password password
* @return ok if create succeed * @return ok if create succeed
@ -109,7 +108,6 @@ public class UserController {
/** /**
* Delete an existed user. * Delete an existed user.
*
* @param username username of user * @param username username of user
* @return ok if deleted succeed, keep silent if user not exist * @return ok if deleted succeed, keep silent if user not exist
* @since 1.2.0 * @since 1.2.0
@ -131,8 +129,7 @@ public class UserController {
/** /**
* Update an user. * Update an user.
* * @param username username of user
* @param username username of user
* @param newPassword new password of user * @param newPassword new password of user
* @param response http response * @param response http response
* @param request http request * @param request http request
@ -143,7 +140,7 @@ public class UserController {
@PutMapping @PutMapping
@Secured(resource = NacosAuthConfig.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE) @Secured(resource = NacosAuthConfig.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE)
public Object updateUser(@RequestParam String username, @RequestParam String newPassword, public Object updateUser(@RequestParam String username, @RequestParam String newPassword,
HttpServletResponse response, HttpServletRequest request) throws IOException { HttpServletResponse response, HttpServletRequest request) throws IOException {
// admin or same user // admin or same user
if (!hasPermission(username, request)) { if (!hasPermission(username, request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!");
@ -178,8 +175,7 @@ public class UserController {
/** /**
* Get paged users. * Get paged users.
* * @param pageNo number index of page
* @param pageNo number index of page
* @param pageSize size of page * @param pageSize size of page
* @return A collection of users, empty set if no user is found * @return A collection of users, empty set if no user is found
* @since 1.2.0 * @since 1.2.0
@ -193,21 +189,21 @@ public class UserController {
/** /**
* Login to Nacos * Login to Nacos
* *
* <p>This methods uses username and password to require a new token. * <p>
* * This methods uses username and password to require a new token.
* @param username username of user * @param username username of user
* @param password password * @param password password
* @param response http response * @param response http response
* @param request http request * @param request http request
* @return new token of the user * @return new token of the user
* @throws AccessException if user info is incorrect * @throws AccessException if user info is incorrect
*/ */
@PostMapping("/login") @PostMapping("/login")
public Object login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, public Object login(@RequestParam String username, @RequestParam String password, HttpServletResponse response,
HttpServletRequest request) throws AccessException { HttpServletRequest request) throws AccessException {
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType()) || AuthSystemTypes.LDAP if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())
.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { || AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
NacosUser user = (NacosUser) authManager.login(request); NacosUser user = (NacosUser) authManager.login(request);
response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, NacosAuthConfig.TOKEN_PREFIX + user.getToken()); response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, NacosAuthConfig.TOKEN_PREFIX + user.getToken());
@ -220,12 +216,14 @@ public class UserController {
return result; return result;
} }
// create Authentication class through username and password, the implement class is UsernamePasswordAuthenticationToken // create Authentication class through username and password, the implement class
// is UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
password); password);
try { try {
// use the method authenticate of AuthenticationManager(default implement is ProviderManager) to valid Authentication // use the method authenticate of AuthenticationManager(default implement is
// ProviderManager) to valid Authentication
Authentication authentication = authenticationManager.authenticate(authenticationToken); Authentication authentication = authenticationManager.authenticate(authenticationToken);
// bind SecurityContext to Authentication // bind SecurityContext to Authentication
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
@ -234,22 +232,23 @@ public class UserController {
// write Token to Http header // write Token to Http header
response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token); response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token);
return RestResultUtils.success("Bearer " + token); return RestResultUtils.success("Bearer " + token);
} catch (BadCredentialsException authentication) { }
catch (BadCredentialsException authentication) {
return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), null, "Login failed"); return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), null, "Login failed");
} }
} }
/** /**
* Update password. * Update password.
*
* @param oldPassword old password * @param oldPassword old password
* @param newPassword new password * @param newPassword new password
* @return Code 200 if update successfully, Code 401 if old password invalid, otherwise 500 * @return Code 200 if update successfully, Code 401 if old password invalid,
* otherwise 500
*/ */
@PutMapping("/password") @PutMapping("/password")
@Deprecated @Deprecated
public RestResult<String> updatePassword(@RequestParam(value = "oldPassword") String oldPassword, public RestResult<String> updatePassword(@RequestParam(value = "oldPassword") String oldPassword,
@RequestParam(value = "newPassword") String newPassword) { @RequestParam(value = "newPassword") String newPassword) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails) principal).getUsername(); String username = ((UserDetails) principal).getUsername();
User user = userDetailsService.getUserFromDatabase(username); User user = userDetailsService.getUserFromDatabase(username);
@ -262,15 +261,14 @@ public class UserController {
return RestResultUtils.success("Update password success"); return RestResultUtils.success("Update password success");
} }
return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), "Old password is invalid"); return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), "Old password is invalid");
} catch (Exception e) { }
catch (Exception e) {
return RestResultUtils.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Update userpassword failed"); return RestResultUtils.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Update userpassword failed");
} }
} }
/** /**
* Fuzzy matching username. * Fuzzy matching username.
*
* @param username username * @param username username
* @return Matched username * @return Matched username
*/ */
@ -279,4 +277,5 @@ public class UserController {
public List<String> searchUsersLikeUsername(@RequestParam String username) { public List<String> searchUsersLikeUsername(@RequestParam String username) {
return userDetailsService.findUserLikeUsername(username); return userDetailsService.findUserLikeUsername(username);
} }
} }

View File

@ -17,8 +17,8 @@
package com.alibaba.nacos.enums; package com.alibaba.nacos.enums;
/** /**
* the enum of namespace. * the enum of namespace. 0 : Global configuration 1 : Default private namespace 2 :
* 0 : Global configuration 1 : Default private namespace 2 : Custom namespace. * Custom namespace.
* *
* @author chenglu * @author chenglu
* @date 2021-05-25 17:01 * @date 2021-05-25 17:01
@ -62,4 +62,5 @@ public enum NamespaceTypeEnum {
public String getDescription() { public String getDescription() {
return description; return description;
} }
} }

View File

@ -51,4 +51,5 @@ public class ConsoleExceptionHandler {
LOGGER.error("CONSOLE", e); LOGGER.error("CONSOLE", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ExceptionUtil.getAllExceptionMsg(e)); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ExceptionUtil.getAllExceptionMsg(e));
} }
} }

View File

@ -73,4 +73,5 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
} }
return null; return null;
} }
} }

View File

@ -37,7 +37,7 @@ public class NamespaceAllInfo extends Namespace {
} }
public NamespaceAllInfo(String namespace, String namespaceShowName, int quota, int configCount, int type, public NamespaceAllInfo(String namespace, String namespaceShowName, int quota, int configCount, int type,
String namespaceDesc) { String namespaceDesc) {
super(namespace, namespaceShowName, quota, configCount, type); super(namespace, namespaceShowName, quota, configCount, type);
this.namespaceDesc = namespaceDesc; this.namespaceDesc = namespaceDesc;
} }

View File

@ -43,4 +43,5 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
LOGGER.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI()); LOGGER.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
} }
} }

View File

@ -48,7 +48,6 @@ public class JwtTokenManager {
/** /**
* Create token. * Create token.
*
* @param authentication auth info * @param authentication auth info
* @return token * @return token
*/ */
@ -58,7 +57,6 @@ public class JwtTokenManager {
/** /**
* Create token. * Create token.
*
* @param userName auth info * @param userName auth info
* @return token * @return token
*/ */
@ -76,7 +74,6 @@ public class JwtTokenManager {
/** /**
* Get auth Info. * Get auth Info.
*
* @param token token * @param token token
* @return auth info * @return auth info
*/ */
@ -93,7 +90,6 @@ public class JwtTokenManager {
/** /**
* validate token. * validate token.
*
* @param token token * @param token token
*/ */
public void validateToken(String token) { public void validateToken(String token) {

View File

@ -89,7 +89,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
UserDetails userDetails = userDetailsService.loadUserByUsername(username); UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (PasswordEncoderUtil.matches(password, userDetails.getPassword())) { if (PasswordEncoderUtil.matches(password, userDetails.getPassword())) {
return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
} else { }
else {
return null; return null;
} }
} }
@ -101,7 +102,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
UserDetails userDetails; UserDetails userDetails;
try { try {
userDetails = userDetailsService.loadUserByUsername(LDAP_PREFIX + username); userDetails = userDetailsService.loadUserByUsername(LDAP_PREFIX + username);
} catch (UsernameNotFoundException exception) { }
catch (UsernameNotFoundException exception) {
String nacosPassword = PasswordEncoderUtil.encode(DEFAULT_PASSWORD); String nacosPassword = PasswordEncoderUtil.encode(DEFAULT_PASSWORD);
userDetailsService.createUser(LDAP_PREFIX + username, nacosPassword); userDetailsService.createUser(LDAP_PREFIX + username, nacosPassword);
User user = new User(); User user = new User();
@ -137,16 +139,20 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
LdapContext ctx = null; LdapContext ctx = null;
try { try {
ctx = new InitialLdapContext(env, null); ctx = new InitialLdapContext(env, null);
} catch (CommunicationException e) { }
catch (CommunicationException e) {
LOG.error("LDAP Service connect timeout:{}", e.getMessage()); LOG.error("LDAP Service connect timeout:{}", e.getMessage());
throw new RuntimeException("LDAP Service connect timeout"); throw new RuntimeException("LDAP Service connect timeout");
} catch (javax.naming.AuthenticationException e) { }
catch (javax.naming.AuthenticationException e) {
LOG.error("login error:{}", e.getMessage()); LOG.error("login error:{}", e.getMessage());
throw new RuntimeException("login error!"); throw new RuntimeException("login error!");
} catch (Exception e) { }
catch (Exception e) {
LOG.warn("Exception cause by:{}", e.getMessage()); LOG.warn("Exception cause by:{}", e.getMessage());
return false; return false;
} finally { }
finally {
closeContext(ctx); closeContext(ctx);
} }
return true; return true;
@ -161,9 +167,11 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
if (ctx != null) { if (ctx != null) {
try { try {
ctx.close(); ctx.close();
} catch (Exception e) { }
catch (Exception e) {
LOG.error("Exception closing context", e); LOG.error("Exception closing context", e);
} }
} }
} }
} }

View File

@ -90,7 +90,8 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
String ignoreUrls = null; String ignoreUrls = null;
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
ignoreUrls = DEFAULT_ALL_PATH_PATTERN; ignoreUrls = DEFAULT_ALL_PATH_PATTERN;
} else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { }
else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
ignoreUrls = DEFAULT_ALL_PATH_PATTERN; ignoreUrls = DEFAULT_ALL_PATH_PATTERN;
} }
if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) {
@ -107,7 +108,8 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { }
else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
auth.authenticationProvider(ldapAuthenticationProvider); auth.authenticationProvider(ldapAuthenticationProvider);
} }
} }
@ -117,11 +119,11 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) {
http.csrf().disable().cors()// We don't need CSRF for JWT based authentication http.csrf().disable().cors()// We don't need CSRF for JWT based authentication
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(LOGIN_ENTRY_POINT).permitAll() .antMatchers(LOGIN_ENTRY_POINT).permitAll().and().authorizeRequests()
.and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() .antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated().and().exceptionHandling()
.and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint()); .authenticationEntryPoint(new JwtAuthenticationEntryPoint());
// disable cache // disable cache
http.headers().cacheControl(); http.headers().cacheControl();

View File

@ -74,9 +74,11 @@ public class NacosAuthManager implements AuthManager {
try { try {
tokenManager.validateToken(token); tokenManager.validateToken(token);
} catch (ExpiredJwtException e) { }
catch (ExpiredJwtException e) {
throw new AccessException("token expired!"); throw new AccessException("token expired!");
} catch (Exception e) { }
catch (Exception e) {
throw new AccessException("token invalid!"); throw new AccessException("token invalid!");
} }
@ -110,9 +112,11 @@ public class NacosAuthManager implements AuthManager {
try { try {
tokenManager.validateToken(token); tokenManager.validateToken(token);
} catch (ExpiredJwtException e) { }
catch (ExpiredJwtException e) {
throw new AccessException("token expired!"); throw new AccessException("token expired!");
} catch (Exception e) { }
catch (Exception e) {
throw new AccessException("token invalid!"); throw new AccessException("token invalid!");
} }
@ -189,16 +193,19 @@ public class NacosAuthManager implements AuthManager {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName,
rawPassword); rawPassword);
authenticate = authenticationManager.authenticate(authenticationToken); authenticate = authenticationManager.authenticate(authenticationToken);
} catch (AuthenticationException e) { }
catch (AuthenticationException e) {
throw new AccessException("unknown user!"); throw new AccessException("unknown user!");
} }
if (null == authenticate || StringUtils.isBlank(authenticate.getName())) { if (null == authenticate || StringUtils.isBlank(authenticate.getName())) {
finalName = userName; finalName = userName;
} else { }
else {
finalName = authenticate.getName(); finalName = authenticate.getName();
} }
return tokenManager.createToken(finalName); return tokenManager.createToken(finalName);
} }
} }

View File

@ -75,8 +75,8 @@ public class NacosRoleServiceImpl {
@Scheduled(initialDelay = 5000, fixedDelay = 15000) @Scheduled(initialDelay = 5000, fixedDelay = 15000)
private void reload() { private void reload() {
try { try {
Page<RoleInfo> roleInfoPage = rolePersistService Page<RoleInfo> roleInfoPage = rolePersistService.getRolesByUserName(StringUtils.EMPTY, DEFAULT_PAGE_NO,
.getRolesByUserName(StringUtils.EMPTY, DEFAULT_PAGE_NO, Integer.MAX_VALUE); Integer.MAX_VALUE);
if (roleInfoPage == null) { if (roleInfoPage == null) {
return; return;
} }
@ -92,15 +92,16 @@ public class NacosRoleServiceImpl {
Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16); Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16);
for (String role : tmpRoleSet) { for (String role : tmpRoleSet) {
Page<PermissionInfo> permissionInfoPage = permissionPersistService Page<PermissionInfo> permissionInfoPage = permissionPersistService.getPermissions(role, DEFAULT_PAGE_NO,
.getPermissions(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE); Integer.MAX_VALUE);
tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems()); tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems());
} }
roleSet = tmpRoleSet; roleSet = tmpRoleSet;
roleInfoMap = tmpRoleInfoMap; roleInfoMap = tmpRoleInfoMap;
permissionInfoMap = tmpPermissionInfoMap; permissionInfoMap = tmpPermissionInfoMap;
} catch (Exception e) { }
catch (Exception e) {
Loggers.AUTH.warn("[LOAD-ROLES] load failed", e); Loggers.AUTH.warn("[LOAD-ROLES] load failed", e);
} }
} }
@ -108,15 +109,15 @@ public class NacosRoleServiceImpl {
/** /**
* Determine if the user has permission of the resource. * Determine if the user has permission of the resource.
* *
* <p>Note if the user has many roles, this method returns true if any one role of the user has the desired * <p>
* permission. * Note if the user has many roles, this method returns true if any one role of the
* * user has the desired permission.
* @param username user info * @param username user info
* @param permission permission to auth * @param permission permission to auth
* @return true if granted, false otherwise * @return true if granted, false otherwise
*/ */
public boolean hasPermission(String username, Permission permission) { public boolean hasPermission(String username, Permission permission) {
//update password // update password
if (NacosAuthConfig.UPDATE_PASSWORD_ENTRY_POINT.equals(permission.getResource())) { if (NacosAuthConfig.UPDATE_PASSWORD_ENTRY_POINT.equals(permission.getResource())) {
return true; return true;
} }
@ -147,8 +148,8 @@ public class NacosRoleServiceImpl {
for (PermissionInfo permissionInfo : permissionInfoList) { for (PermissionInfo permissionInfo : permissionInfoList) {
String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*"); String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*");
String permissionAction = permissionInfo.getAction(); String permissionAction = permissionInfo.getAction();
if (permissionAction.contains(permission.getAction()) && Pattern if (permissionAction.contains(permission.getAction())
.matches(permissionResource, permission.getResource())) { && Pattern.matches(permissionResource, permission.getResource())) {
return true; return true;
} }
} }
@ -178,7 +179,8 @@ public class NacosRoleServiceImpl {
public List<PermissionInfo> getPermissions(String role) { public List<PermissionInfo> getPermissions(String role) {
List<PermissionInfo> permissionInfoList = permissionInfoMap.get(role); List<PermissionInfo> permissionInfoList = permissionInfoMap.get(role);
if (!authConfigs.isCachingEnabled() || permissionInfoList == null) { if (!authConfigs.isCachingEnabled() || permissionInfoList == null) {
Page<PermissionInfo> permissionInfoPage = getPermissionsFromDatabase(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE); Page<PermissionInfo> permissionInfoPage = getPermissionsFromDatabase(role, DEFAULT_PAGE_NO,
Integer.MAX_VALUE);
if (permissionInfoPage != null) { if (permissionInfoPage != null) {
permissionInfoList = permissionInfoPage.getPageItems(); permissionInfoList = permissionInfoPage.getPageItems();
} }
@ -192,8 +194,7 @@ public class NacosRoleServiceImpl {
/** /**
* Add role. * Add role.
* * @param role role name
* @param role role name
* @param username user name * @param username user name
*/ */
public void addRole(String role, String username) { public void addRole(String role, String username) {
@ -226,10 +227,9 @@ public class NacosRoleServiceImpl {
/** /**
* Add permission. * Add permission.
* * @param role role name
* @param role role name
* @param resource resource * @param resource resource
* @param action action * @param action action
*/ */
public void addPermission(String role, String resource, String action) { public void addPermission(String role, String resource, String action) {
if (!roleSet.contains(role)) { if (!roleSet.contains(role)) {
@ -245,4 +245,5 @@ public class NacosRoleServiceImpl {
public List<String> findRolesLikeRoleName(String role) { public List<String> findRolesLikeRoleName(String role) {
return rolePersistService.findRolesLikeRoleName(role); return rolePersistService.findRolesLikeRoleName(role);
} }
} }

View File

@ -50,4 +50,5 @@ public class NacosUser extends User {
public String toString() { public String toString() {
return "NacosUser{" + "token='" + token + '\'' + ", globalAdmin=" + globalAdmin + '}'; return "NacosUser{" + "token='" + token + '\'' + ", globalAdmin=" + globalAdmin + '}';
} }
} }

View File

@ -71,4 +71,5 @@ public class NacosUserDetails implements UserDetails {
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
} }

View File

@ -62,7 +62,8 @@ public class NacosUserDetailsServiceImpl implements UserDetailsService {
map.put(user.getUsername(), user); map.put(user.getUsername(), user);
} }
userMap = map; userMap = map;
} catch (Exception e) { }
catch (Exception e) {
Loggers.AUTH.warn("[LOAD-USERS] load failed", e); Loggers.AUTH.warn("[LOAD-USERS] load failed", e);
} }
} }
@ -112,4 +113,5 @@ public class NacosUserDetailsServiceImpl implements UserDetailsService {
public void deleteUser(String username) { public void deleteUser(String username) {
userPersistService.deleteUser(username); userPersistService.deleteUser(username);
} }
} }

View File

@ -32,4 +32,5 @@ public class PasswordEncoderUtil {
public static String encode(String raw) { public static String encode(String raw) {
return new BCryptPasswordEncoder().encode(raw); return new BCryptPasswordEncoder().encode(raw);
} }
} }

View File

@ -70,6 +70,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId> <artifactId>spring-boot-starter-undertow</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-test</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>