Unverified Commit a0a9017d authored by gaoyan's avatar gaoyan Committed by GitHub

Add the LDAP user list interface and the test connection interface (#2045)

* fix BusException logic error if BusException.msg is empty, use I18n message * Add the LDAP user list interface and the test connection interface * Add the LDAP user list interface and the test connection interface * fix some split error
parent b198c1e8
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.context;
import org.dinky.data.enums.UserType;
import org.dinky.data.model.LdapUserIdentification;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.User;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.LdapContextSource;
public class LdapContext {
private static final SystemConfiguration configuration = SystemConfiguration.getInstances();
/**
* Get the LDAP context source object.
*
* @return LDAP context source object
*/
public static LdapContextSource getLdapContext() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(configuration.getLdapUrl().getValue());
contextSource.setBase(configuration.getLdapBaseDn().getValue());
contextSource.setUserDn(configuration.getLdapUserDn().getValue());
contextSource.setPassword(configuration.getLdapUserPassword().getValue());
contextSource.afterPropertiesSet();
return contextSource;
}
/**
* Get the search controls for LDAP search.
*
* @return Search controls for LDAP search
*/
public static SearchControls getControls() {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// controls.setCountLimit(ldapConfig.getCountLimit());
controls.setTimeLimit(configuration.getLdapTimeLimit().getValue());
return controls;
}
/** Context mapper for LDAP user identification. */
public static class UserContextMapper implements ContextMapper<LdapUserIdentification> {
/**
* Map the LDAP context to LdapUserIdentification object.
*
* @param ctx LDAP context
* @return LdapUserIdentification object
*/
public LdapUserIdentification mapFromContext(Object ctx) {
DirContextOperations adapter = (DirContextOperations) ctx;
return new LdapUserIdentification(
adapter.getNameInNamespace(),
adapter.getDn().toString(),
adapter.getAttributes());
}
}
/** Attributes mapper from LDAP user to Local user. */
public static class UserAttributesMapperMapper implements AttributesMapper<User> {
/**
* Map the LDAP attributes to User object.
*
* @param attributes LDAP attributes
* @return User object
* @throws NamingException if there is an error during mapping
*/
@Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
Attribute usernameAttr = attributes.get(configuration.getLdapCastUsername().getValue());
Attribute nicknameAttr = attributes.get(configuration.getLdapCastNickname().getValue());
if (usernameAttr != null && nicknameAttr != null) {
User user = new User();
user.setUsername(usernameAttr.get().toString());
user.setNickname(nicknameAttr.get().toString());
user.setUserType(UserType.LDAP.getCode());
return user;
}
return null;
}
}
}
...@@ -19,10 +19,15 @@ ...@@ -19,10 +19,15 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.data.enums.Status;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.User;
import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.service.LdapService; import org.dinky.service.LdapService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -39,23 +44,29 @@ public class LdapController { ...@@ -39,23 +44,29 @@ public class LdapController {
@Autowired LdapService ldapService; @Autowired LdapService ldapService;
/** Gets the LDAP configuration status */
@GetMapping("/ldapEnableStatus") @GetMapping("/ldapEnableStatus")
public Result<Boolean> ldapStatus() { public Result<Boolean> ldapStatus() {
return Result.succeed( return Result.succeed(
SystemConfiguration.getInstances().getLdapEnable().getValue(), "获取成功"); SystemConfiguration.getInstances().getLdapEnable().getValue(), "获取成功");
} }
// @PostMapping("/listUser") @GetMapping("/testConnection")
// public ProTableResult<User> listUser(@RequestBody LdapConfig ldapConfig) { public Result<Integer> testConnection() {
// List<User> users = ldapService.listUsers(ldapConfig); List<User> users = ldapService.listUsers();
// return ProTableResult.<User>builder() if (users.size() > 0) {
// .success(true) return Result.succeed(users.size());
// .data(users) } else {
// .total((long) users.size()) return Result.failed(Status.LDAP_NO_USER_FOUND);
//// .current(1) }
//// .pageSize(1) }
// .build();
// }
@GetMapping("/listUser")
public ProTableResult<User> listUser() {
List<User> users = ldapService.listUsers();
return ProTableResult.<User>builder()
.success(true)
.data(users)
.total((long) users.size())
.build();
}
} }
...@@ -23,10 +23,13 @@ import org.dinky.data.dto.LoginDTO; ...@@ -23,10 +23,13 @@ import org.dinky.data.dto.LoginDTO;
import org.dinky.data.exception.AuthException; import org.dinky.data.exception.AuthException;
import org.dinky.data.model.User; import org.dinky.data.model.User;
import java.util.List;
import javax.naming.NamingException; import javax.naming.NamingException;
public interface LdapService { public interface LdapService {
// List<User> listUsers(LdapConfig ldapConfig);
List<User> listUsers();
/** /**
* Authenticates the user based on the provided login credentials. Throws AuthException if * Authenticates the user based on the provided login credentials. Throws AuthException if
...@@ -35,5 +38,5 @@ public interface LdapService { ...@@ -35,5 +38,5 @@ public interface LdapService {
* @param loginDTO The login user info * @param loginDTO The login user info
* @return ldap user * @return ldap user
*/ */
User authenticate(LoginDTO userDTO) throws AuthException, NamingException; User authenticate(LoginDTO loginDTO) throws AuthException, NamingException;
} }
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.context.LdapContext;
import org.dinky.data.dto.LoginDTO; import org.dinky.data.dto.LoginDTO;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.exception.AuthException; import org.dinky.data.exception.AuthException;
...@@ -28,17 +29,16 @@ import org.dinky.data.model.User; ...@@ -28,17 +29,16 @@ import org.dinky.data.model.User;
import org.dinky.service.LdapService; import org.dinky.service.LdapService;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.naming.directory.Attributes; import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import org.springframework.ldap.AuthenticationException; import org.springframework.ldap.AuthenticationException;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Service @Service
...@@ -56,7 +56,7 @@ public class LdapServiceImpl implements LdapService { ...@@ -56,7 +56,7 @@ public class LdapServiceImpl implements LdapService {
*/ */
@Override @Override
public User authenticate(LoginDTO loginDTO) throws AuthException { public User authenticate(LoginDTO loginDTO) throws AuthException {
LdapTemplate ldapTemplate = new LdapTemplate(getLdapContext()); LdapTemplate ldapTemplate = new LdapTemplate(LdapContext.getLdapContext());
// Build LDAP filter, The LdapCastUsername is map to Dinky UserName // Build LDAP filter, The LdapCastUsername is map to Dinky UserName
String filter = String filter =
String.format( String.format(
...@@ -67,7 +67,8 @@ public class LdapServiceImpl implements LdapService { ...@@ -67,7 +67,8 @@ public class LdapServiceImpl implements LdapService {
// Perform search operation, we have alreday config baseDn in global // Perform search operation, we have alreday config baseDn in global
// so the param base has config "" // so the param base has config ""
List<LdapUserIdentification> result = List<LdapUserIdentification> result =
ldapTemplate.search("", filter, getControls(), new UserContextMapper()); ldapTemplate.search(
"", filter, LdapContext.getControls(), new LdapContext.UserContextMapper());
// Only if the returned result is one is correct, // Only if the returned result is one is correct,
// otherwise the corresponding exception is thrown // otherwise the corresponding exception is thrown
if (result.size() == 0) { if (result.size() == 0) {
...@@ -87,7 +88,7 @@ public class LdapServiceImpl implements LdapService { ...@@ -87,7 +88,7 @@ public class LdapServiceImpl implements LdapService {
try { try {
Attributes attributes = ldapUserIdentification.getAttributes(); Attributes attributes = ldapUserIdentification.getAttributes();
// Validate username and password // Validate username and password
getLdapContext() LdapContext.getLdapContext()
.getContext(ldapUserIdentification.getAbsoluteDn(), loginDTO.getPassword()); .getContext(ldapUserIdentification.getAbsoluteDn(), loginDTO.getPassword());
// If no exception is thrown, then the login is successful, // If no exception is thrown, then the login is successful,
// Build the User with cast // Build the User with cast
...@@ -109,31 +110,26 @@ public class LdapServiceImpl implements LdapService { ...@@ -109,31 +110,26 @@ public class LdapServiceImpl implements LdapService {
} }
} }
private LdapContextSource getLdapContext() { /**
LdapContextSource contextSource = new LdapContextSource(); * Returns a list of rule-filtered users in LDAP and for data where username and nickname fail
contextSource.setUrl(configuration.getLdapUrl().getValue()); * to be successfully matched
contextSource.setBase(configuration.getLdapBaseDn().getValue()); *
contextSource.setUserDn(configuration.getLdapUserDn().getValue()); * @return User List
contextSource.setPassword(configuration.getLdapUserPassword().getValue()); */
contextSource.afterPropertiesSet(); @Override
return contextSource; public List<User> listUsers() {
} String filter = configuration.getLdapFilter().getValue();
Assert.notBlank(filter, Status.LDAP_FILTER_INCORRECT.getMsg());
private SearchControls getControls() { LdapTemplate ldapTemplate = new LdapTemplate(LdapContext.getLdapContext());
SearchControls controls = new SearchControls(); List<User> result =
controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ldapTemplate.search(
// controls.setCountLimit(ldapConfig.getCountLimit()); "",
controls.setTimeLimit(configuration.getLdapTimeLimit().getValue()); configuration.getLdapFilter().getValue(),
return controls; LdapContext.getControls(),
} new LdapContext.UserAttributesMapperMapper());
private static class UserContextMapper implements ContextMapper<LdapUserIdentification> { // User is empty representative not matched to relevant attribute, filtered out
public LdapUserIdentification mapFromContext(Object ctx) { return result.stream().filter(Objects::nonNull).collect(Collectors.toList());
DirContextOperations adapter = (DirContextOperations) ctx;
return new LdapUserIdentification(
adapter.getNameInNamespace(),
adapter.getDn().toString(),
adapter.getAttributes());
}
} }
} }
...@@ -103,12 +103,6 @@ public enum Status { ...@@ -103,12 +103,6 @@ public enum Status {
SWITCHING_TENANT_SUCCESS(10018, "Select Tenant Success", "选择租户成功"), SWITCHING_TENANT_SUCCESS(10018, "Select Tenant Success", "选择租户成功"),
// user.superadmin.cannot.disable // user.superadmin.cannot.disable
USER_SUPERADMIN_CANNOT_DISABLE(10019, "User SuperAdmin Cannot Disable", "超级管理员用户不能停用"), USER_SUPERADMIN_CANNOT_DISABLE(10019, "User SuperAdmin Cannot Disable", "超级管理员用户不能停用"),
LDAP_USER_DUPLICAT(10020, "The ldap matches to multiple user data", "ldap匹配到多个用户数据"),
LDAP_USER_AUTOLOAD_FORBAID(
10021,
"Auto-mapping LDAP users are not enabled, please contact your administrator to import",
"未开启自动映射LDAP用户,请联系管理员导入"),
LDAP_DEFAULT_TENANT_NOFOUND(10021, "The LDAP default tenant does not exist", "LDAP默认租户不存在"),
// role // role
ROLE_ALREADY_EXISTS(10101, "Role Already Exists", "角色已存在"), ROLE_ALREADY_EXISTS(10101, "Role Already Exists", "角色已存在"),
...@@ -199,6 +193,23 @@ public enum Status { ...@@ -199,6 +193,23 @@ public enum Status {
"海豚调度类型为 [{}] 不支持,非DINKY类型"), "海豚调度类型为 [{}] 不支持,非DINKY类型"),
DS_WORK_FLOW_DEFINITION_NOT_EXIST(17009, "Workflow Definition Not Exist", "工作流定义不存在"), DS_WORK_FLOW_DEFINITION_NOT_EXIST(17009, "Workflow Definition Not Exist", "工作流定义不存在"),
/** LDAP About * */
LDAP_USER_DUPLICAT(18001, "The ldap matches to multiple user data", "ldap匹配到多个用户数据"),
LDAP_USER_AUTOLOAD_FORBAID(
18002,
"Auto-mapping LDAP users are not enabled, please contact your administrator to import",
"未开启自动映射LDAP用户,请联系管理员导入"),
LDAP_DEFAULT_TENANT_NOFOUND(18003, "The LDAP default tenant does not exist", "LDAP默认租户不存在"),
LDAP_USER_INCORRECT(18004, "The LDAP user name (DN) Incorrect", "LDAP用户名(DN)不正确"),
LDAP_NO_USER_FOUND(
18005,
"The LDAP connection was successful, but it did not match to any users",
"LDAP连接成功,但未匹配到任何用户"),
LDAP_FILTER_INCORRECT(
18006,
"If the user filter rule cannot be empty, enter the relevant configuration",
"用户过滤规则不能为空,请填写相关配置"),
/** global exception */ /** global exception */
GLOBAL_PARAMS_CHECK_ERROR(90001, "Field: {0}, {1}", "字段: {0}, {1}"), GLOBAL_PARAMS_CHECK_ERROR(90001, "Field: {0}, {1}", "字段: {0}, {1}"),
GLOBAL_PARAMS_CHECK_ERROR_VALUE(90002, "Field: {0}, Illegal Value: {1}", "字段: {0}, 不合法的值: {1}"), GLOBAL_PARAMS_CHECK_ERROR_VALUE(90002, "Field: {0}, Illegal Value: {1}", "字段: {0}, 不合法的值: {1}"),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment