同步器增加属性映射管理

This commit is contained in:
llh
2024-09-24 18:38:15 +08:00
711 changed files with 17528 additions and 5084 deletions
@@ -22,7 +22,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.GroupPermissions;
import org.dromara.maxkey.entity.Access;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -30,12 +30,12 @@ import org.dromara.mybatis.jpa.IJpaMapper;
*
*/
public interface GroupPermissionsMapper extends IJpaMapper<GroupPermissions> {
public interface AccessMapper extends IJpaMapper<Access> {
public List<GroupPermissions>appsInGroup(GroupPermissions entity);
public List<Access>appsInGroup(Access entity);
public List<GroupPermissions> appsNotInGroup(GroupPermissions entity);
public List<Access> appsNotInGroup(Access entity);
}
@@ -27,7 +27,7 @@ import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dromara.maxkey.entity.Accounts;
import org.dromara.maxkey.entity.AccountsStrategy;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -23,7 +23,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.AccountsStrategy;
import org.dromara.maxkey.entity.Roles;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -16,9 +16,9 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.LdapContext;
import org.dromara.maxkey.entity.cnf.CnfEmailSenders;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface LdapContextMapper extends IJpaMapper<LdapContext> {
public interface CnfEmailSendersMapper extends IJpaMapper<CnfEmailSenders> {
}
@@ -16,9 +16,9 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.EmailSenders;
import org.dromara.maxkey.entity.cnf.CnfLdapContext;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface EmailSendersMapper extends IJpaMapper<EmailSenders> {
public interface CnfLdapContextMapper extends IJpaMapper<CnfLdapContext> {
}
@@ -20,14 +20,14 @@
*/
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.PasswordPolicy;
import org.dromara.maxkey.entity.cnf.CnfPasswordPolicy;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
* @author Crystal.sea
*
*/
public interface PasswordPolicyMapper extends IJpaMapper<PasswordPolicy> {
public interface CnfPasswordPolicyMapper extends IJpaMapper<CnfPasswordPolicy> {
}
@@ -17,9 +17,9 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.SmsProvider;
import org.dromara.maxkey.entity.cnf.CnfSmsProvider;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface SmsProviderMapper extends IJpaMapper<SmsProvider> {
public interface CnfSmsProviderMapper extends IJpaMapper<CnfSmsProvider> {
}
@@ -22,11 +22,11 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.GroupMember;
import org.dromara.maxkey.entity.Groups;
import org.dromara.maxkey.entity.RoleMember;
import org.dromara.maxkey.entity.Roles;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.GroupMember;
import org.dromara.maxkey.entity.idm.Groups;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.entity.permissions.RoleMember;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -22,7 +22,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.Groups;
import org.dromara.maxkey.entity.idm.Groups;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -18,7 +18,7 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.HistoryConnector;
import org.dromara.maxkey.entity.history.HistoryConnector;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -17,7 +17,7 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.HistoryLoginApps;
import org.dromara.maxkey.entity.history.HistoryLoginApps;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -20,7 +20,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.HistoryLogin;
import org.dromara.maxkey.entity.history.HistoryLogin;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -18,7 +18,7 @@
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.HistorySynchronizer;
import org.dromara.maxkey.entity.history.HistorySynchronizer;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -20,7 +20,7 @@
*/
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.HistorySystemLogs;
import org.dromara.maxkey.entity.history.HistorySystemLogs;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -18,8 +18,8 @@
package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.OrganizationsCast;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface OrganizationsCastMapper extends IJpaMapper<OrganizationsCast> {
@@ -19,7 +19,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Update;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface OrganizationsMapper extends IJpaMapper<Organizations> {
@@ -22,7 +22,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.GroupPrivileges;
import org.dromara.maxkey.entity.permissions.Permission;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -30,12 +30,12 @@ import org.dromara.mybatis.jpa.IJpaMapper;
*
*/
public interface GroupPrivilegesMapper extends IJpaMapper<GroupPrivileges> {
public interface PermissionMapper extends IJpaMapper<Permission> {
public int insertGroupPrivileges(List<GroupPrivileges> groupPrivilegesList);
public int insertGroupPrivileges(List<Permission> groupPrivilegesList);
public int deleteGroupPrivileges(List<GroupPrivileges> groupPrivilegesList);
public int deleteGroupPrivileges(List<Permission> groupPrivilegesList);
public List<GroupPrivileges> queryGroupPrivileges(GroupPrivileges groupPrivileges);
public List<Permission> queryGroupPrivileges(Permission groupPrivileges);
}
@@ -0,0 +1,39 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.permissions.PermissionRole;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
* @author Crystal.sea
*
*/
public interface PermissionRoleMapper extends IJpaMapper<PermissionRole> {
public int insertPermissionRoles(List<PermissionRole> permissionRolesList);
public int deletePermissionRoles(List<PermissionRole> permissionRolesList);
public List<PermissionRole> queryPermissionRoles(PermissionRole permissionRole);
}
@@ -23,7 +23,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.Register;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -20,7 +20,7 @@
*/
package org.dromara.maxkey.persistence.mapper;
import org.dromara.maxkey.entity.Resources;
import org.dromara.maxkey.entity.permissions.Resources;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
@@ -0,0 +1,52 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.entity.permissions.RoleMember;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
* @author Crystal.sea
*
*/
public interface RoleMemberMapper extends IJpaMapper<RoleMember> {
public List<RoleMember> memberInRole(RoleMember entity);
public List<RoleMember> memberNotInRole(RoleMember entity);
public List<RoleMember> memberPostNotInRole(RoleMember entity);
public List<Roles> rolesNoMember(RoleMember entity);
public int addDynamicRoleMember(Roles dynamicRole);
public int deleteDynamicRoleMember(Roles dynamicRole);
public int deleteByRoleId(String roleId);
public List<UserInfo> queryMemberByRoleId(String roleId);
}
@@ -0,0 +1,35 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.mybatis.jpa.IJpaMapper;
/**
* @author Crystal.sea
*
*/
public interface RolesMapper extends IJpaMapper<Roles> {
public List<Roles> queryDynamicRoles(Roles groups);
public List<Roles> queryRolesByUserId(String userId);
}
@@ -19,7 +19,7 @@ package org.dromara.maxkey.persistence.mapper;
import java.util.List;
import org.dromara.maxkey.entity.SocialsAssociate;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.IJpaMapper;
public interface SocialsAssociateMapper extends IJpaMapper<SocialsAssociate> {
@@ -23,8 +23,8 @@ import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.IJpaMapper;
@@ -0,0 +1,104 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.ObjectUtils;
import org.dromara.maxkey.entity.Institutions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class InstitutionsRepository {
static final Logger _logger = LoggerFactory.getLogger(InstitutionsRepository.class);
private static final String SELECT_STATEMENT =
"select * from mxk_institutions where id = ? or domain = ? or consoledomain = ?" ;
private static final String DEFAULT_INSTID = "1";
protected static final Cache<String, Institutions> institutionsStore =
Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build();
//id domain mapping
protected static final ConcurrentHashMap<String,String> mapper = new ConcurrentHashMap<>();
protected JdbcTemplate jdbcTemplate;
public InstitutionsRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Institutions get(String instIdOrDomain) {
_logger.trace(" instId {}" , instIdOrDomain);
Institutions inst = getByInstIdOrDomain(instIdOrDomain);
if(inst == null) {//use default inst
inst = getByInstIdOrDomain(DEFAULT_INSTID);
institutionsStore.put(instIdOrDomain, inst);
}
return inst;
}
private Institutions getByInstIdOrDomain(String instIdOrDomain) {
_logger.trace(" instId {}" , instIdOrDomain);
Institutions inst = institutionsStore.getIfPresent(mapper.get(instIdOrDomain)==null ? DEFAULT_INSTID : mapper.get(instIdOrDomain) );
if(inst == null) {
List<Institutions> institutions =
jdbcTemplate.query(SELECT_STATEMENT,new InstitutionsRowMapper(),instIdOrDomain,instIdOrDomain,instIdOrDomain);
if (ObjectUtils.isNotEmpty(institutions)) {
inst = institutions.get(0);
}
if(inst != null ) {
institutionsStore.put(inst.getDomain(), inst);
institutionsStore.put(inst.getConsoleDomain(), inst);
mapper.put(inst.getId(), inst.getDomain());
}
}
return inst;
}
public class InstitutionsRowMapper implements RowMapper<Institutions> {
@Override
public Institutions mapRow(ResultSet rs, int rowNum) throws SQLException {
Institutions institution = new Institutions();
institution.setId(rs.getString("id"));
institution.setName(rs.getString("name"));
institution.setFullName(rs.getString("fullname"));
institution.setLogo(rs.getString("logo"));
institution.setDomain(rs.getString("domain"));
institution.setFrontTitle(rs.getString("fronttitle"));
institution.setConsoleDomain(rs.getString("consoledomain"));
institution.setConsoleTitle(rs.getString("consoletitle"));
institution.setDefaultUri(rs.getString("defaultUri"));
return institution;
}
}
}
@@ -0,0 +1,133 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.sql.Types;
import org.dromara.maxkey.entity.history.HistoryLogin;
import org.dromara.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class LoginHistoryRepository {
private static Logger logger = LoggerFactory.getLogger(LoginHistoryRepository.class);
private static final String HISTORY_LOGIN_INSERT_STATEMENT = """
insert into mxk_history_login
( id ,
sessionid ,
userid ,
username ,
displayname ,
logintype ,
message ,
code ,
provider ,
sourceip ,
country ,
province ,
city ,
location ,
browser ,
platform ,
application ,
loginurl ,
sessionstatus ,
instid)
values( ? , ? , ? , ? , ? , ? , ? , ? , ?, ? , ? , ? , ?, ?, ? , ? , ?, ? , ? , ?)
""";
protected JdbcTemplate jdbcTemplate;
public LoginHistoryRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void login(HistoryLogin historyLogin) {
historyLogin.setId(WebContext.genId());
historyLogin.setLoginUrl(WebContext.getRequest().getRequestURI());
//Thread insert
new Thread(new HistoryLoginRunnable(jdbcTemplate,historyLogin)).start();
}
public class HistoryLoginRunnable implements Runnable{
JdbcTemplate jdbcTemplate;
HistoryLogin historyLogin;
public HistoryLoginRunnable(JdbcTemplate jdbcTemplate, HistoryLogin historyLogin) {
super();
this.jdbcTemplate = jdbcTemplate;
this.historyLogin = historyLogin;
}
@Override
public void run() {
logger.debug("History Login {}" , historyLogin);
jdbcTemplate.update(HISTORY_LOGIN_INSERT_STATEMENT,
new Object[] {
historyLogin.getId(),
historyLogin.getSessionId(),
historyLogin.getUserId(),
historyLogin.getUsername(),
historyLogin.getDisplayName(),
historyLogin.getLoginType(),
historyLogin.getMessage(),
historyLogin.getCode(),
historyLogin.getProvider(),
historyLogin.getSourceIp(),
historyLogin.getCountry(),
historyLogin.getProvince(),
historyLogin.getCity(),
historyLogin.getLocation(),
historyLogin.getBrowser(),
historyLogin.getPlatform(),
"Browser",
historyLogin.getLoginUrl(),
historyLogin.getSessionStatus(),
historyLogin.getInstId()
},
new int[] {
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.INTEGER,
Types.VARCHAR
});
}
}
}
@@ -0,0 +1,380 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsRoles;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.entity.idm.Groups;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public class LoginRepository {
private static final Logger _logger = LoggerFactory.getLogger(LoginRepository.class);
private static final String LOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String UNLOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , badpasswordtime = ? where id = ?";
private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , islocked = ? ,unlocktime = ? where id = ?";
private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogintime = ? , lastloginip = ? , logincount = ?, online = "
+ UserInfo.ONLINE.ONLINE + " where id = ?";
private static final String GROUPS_SELECT_STATEMENT = "select distinct g.id,g.groupcode,g.groupname from mxk_userinfo u,mxk_groups g,mxk_group_member gm where u.id = ? and u.id=gm.memberid and gm.groupid=g.id ";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT = "select * from mxk_userinfo where username = ? ";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE = "select * from mxk_userinfo where (username = ? or mobile = ?)";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL = "select * from mxk_userinfo where (username = ? or mobile = ? or email = ?) ";
private static final String DEFAULT_MYAPPS_SELECT_STATEMENT = "select distinct app.id,app.appname from mxk_apps app,mxk_access gp,mxk_groups g where app.id=gp.appid and app.status = 1 and gp.groupid=g.id and g.id in(%s)";
protected JdbcTemplate jdbcTemplate;
/**
* 1 (USERNAME) 2 (USERNAME | MOBILE) 3 (USERNAME | MOBILE | EMAIL)
*/
public static int LOGIN_ATTRIBUTE_TYPE = 2;
public LoginRepository(){
}
public LoginRepository(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
public UserInfo find(String username, String password) {
List<UserInfo> listUserInfo = null ;
if( LOGIN_ATTRIBUTE_TYPE == 1) {
listUserInfo = findByUsername(username,password);
}else if( LOGIN_ATTRIBUTE_TYPE == 2) {
listUserInfo = findByUsernameOrMobile(username,password);
}else if( LOGIN_ATTRIBUTE_TYPE == 3) {
listUserInfo = findByUsernameOrMobileOrEmail(username,password);
}
_logger.debug("load UserInfo : {}" , listUserInfo);
return (ObjectUtils.isNotEmpty(listUserInfo))? listUserInfo.get(0) : null;
}
public List<UserInfo> findByUsername(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT,
new UserInfoRowMapper(),
username
);
}
public List<UserInfo> findByUsernameOrMobile(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE,
new UserInfoRowMapper(),
username,username
);
}
public List<UserInfo> findByUsernameOrMobileOrEmail(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL,
new UserInfoRowMapper(),
username,username,username
);
}
/**
* 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
*
* @param userInfo
*/
public void updateLock(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.LOCK, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.LOCK);
}
} catch (Exception e) {
_logger.error("lockUser Exception",e);
}
}
/**
* 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
*
* @param userInfo
*/
public void updateUnlock(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("unlockUser Exception",e);
}
}
/**
* reset BadPasswordCount And Lockout
*
* @param userInfo
*/
public void updateLockout(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT,
new Object[] { 0, ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("resetBadPasswordCountAndLockout Exception",e);
}
}
/**
* if login password is error ,BadPasswordCount++ and set bad date
*
* @param userInfo
*/
public void updateBadPasswordCount(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
int badPasswordCount = userInfo.getBadPasswordCount() + 1;
userInfo.setBadPasswordCount(badPasswordCount);
jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT,
new Object[] { badPasswordCount, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
}
} catch (Exception e) {
e.printStackTrace();
_logger.error(e.getMessage());
}
}
public List<GrantedAuthority> queryAuthorizedApps(List<GrantedAuthority> grantedAuthoritys) {
String grantedAuthorityString="'ROLE_ALL_USER'";
for(GrantedAuthority grantedAuthority : grantedAuthoritys) {
grantedAuthorityString += ",'"+ grantedAuthority.getAuthority()+"'";
}
ArrayList<GrantedAuthority> listAuthorizedApps = (ArrayList<GrantedAuthority>) jdbcTemplate.query(
String.format(DEFAULT_MYAPPS_SELECT_STATEMENT, grantedAuthorityString),
new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
return new SimpleGrantedAuthority(rs.getString("id"));
}
});
_logger.debug("list Authorized Apps {}" , listAuthorizedApps);
return listAuthorizedApps;
}
public List<Groups> queryGroups(UserInfo userInfo) {
List<Groups> listRoles = jdbcTemplate.query(GROUPS_SELECT_STATEMENT, new RowMapper<Groups>() {
public Groups mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Groups(rs.getString("id"), rs.getString("groupcode"),rs.getString("groupname"), 0);
}
}, userInfo.getId());
_logger.debug("list Roles {}" , listRoles);
return listRoles;
}
/**
* grant Authority by userinfo
*
* @param userInfo
* @return ArrayList<GrantedAuthority>
*/
public List<GrantedAuthority> grantAuthority(UserInfo userInfo) {
// query Groups for user
List<Groups> listGroups = queryGroups(userInfo);
//set default groups
ArrayList<GrantedAuthority> grantedAuthority = new ArrayList<>();
grantedAuthority.add(ConstsRoles.ROLE_USER);
grantedAuthority.add(ConstsRoles.ROLE_ALL_USER);
grantedAuthority.add(ConstsRoles.ROLE_ORDINARY_USER);
for (Groups group : listGroups) {
grantedAuthority.add(new SimpleGrantedAuthority(group.getId()));
if(group.getGroupCode().startsWith("ROLE_")
&& !grantedAuthority.contains(new SimpleGrantedAuthority(group.getGroupCode()))) {
grantedAuthority.add(new SimpleGrantedAuthority(group.getGroupCode()));
}
}
_logger.debug("Authority : {}" , grantedAuthority);
return grantedAuthority;
}
public void updateLastLogin(UserInfo userInfo) {
jdbcTemplate.update(LOGIN_USERINFO_UPDATE_STATEMENT,
new Object[] {
userInfo.getLastLoginTime(),
userInfo.getLastLoginIp(),
userInfo.getLoginCount() + 1,
userInfo.getId()
},
new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.VARCHAR });
}
public class UserInfoRowMapper implements RowMapper<UserInfo> {
@Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getString("id"));
userInfo.setUsername(rs.getString("username"));
userInfo.setPassword(rs.getString("password"));
userInfo.setSharedSecret(rs.getString("sharedsecret"));
userInfo.setSharedCounter(rs.getString("sharedcounter"));
userInfo.setDecipherable(rs.getString("decipherable"));
userInfo.setWindowsAccount(rs.getString("windowsaccount"));
userInfo.setUserType(rs.getString("usertype"));
userInfo.setDisplayName(rs.getString("displayname"));
userInfo.setNickName(rs.getString("nickname"));
userInfo.setNameZhSpell(rs.getString("namezhspell"));// nameZHSpell
userInfo.setNameZhShortSpell(rs.getString("namezhshortspell"));// nameZHSpell
userInfo.setGivenName(rs.getString("givenname"));
userInfo.setMiddleName(rs.getString("middlename"));
userInfo.setFamilyName(rs.getString("familyname"));
userInfo.setHonorificPrefix(rs.getString("honorificprefix"));
userInfo.setHonorificSuffix(rs.getString("honorificsuffix"));
userInfo.setFormattedName(rs.getString("formattedname"));
userInfo.setGender(rs.getInt("gender"));
userInfo.setBirthDate(rs.getString("birthdate"));
userInfo.setPicture(rs.getBytes("picture"));
userInfo.setMarried(rs.getInt("married"));
userInfo.setIdType(rs.getInt("idtype"));
userInfo.setIdCardNo(rs.getString("idcardno"));
userInfo.setWebSite(rs.getString("website"));
userInfo.setAuthnType(rs.getInt("authntype"));
userInfo.setMobile(rs.getString("mobile"));
userInfo.setMobileVerified(rs.getInt("mobileverified"));
userInfo.setEmail(rs.getString("email"));
userInfo.setEmailVerified(rs.getInt("emailverified"));
userInfo.setPasswordQuestion(rs.getString("passwordquestion"));
userInfo.setPasswordAnswer(rs.getString("passwordanswer"));
userInfo.setAppLoginAuthnType(rs.getInt("apploginauthntype"));
userInfo.setAppLoginPassword(rs.getString("apploginpassword"));
userInfo.setProtectedApps(rs.getString("protectedapps"));
userInfo.setPasswordLastSetTime(rs.getTimestamp("passwordlastsettime"));
userInfo.setPasswordSetType(rs.getInt("passwordsettype"));
userInfo.setBadPasswordCount(rs.getInt("badpasswordcount"));
userInfo.setBadPasswordTime(rs.getTimestamp("badpasswordtime"));
userInfo.setUnLockTime(rs.getTimestamp("unlocktime"));
userInfo.setIsLocked(rs.getInt("islocked"));
userInfo.setLastLoginTime(rs.getTimestamp("lastlogintime"));
userInfo.setLastLoginIp(rs.getString("lastloginip"));
userInfo.setLastLogoffTime(rs.getTimestamp("lastlogofftime"));
userInfo.setLoginCount(rs.getInt("logincount"));
userInfo.setRegionHistory(rs.getString("regionhistory"));
userInfo.setPasswordHistory(rs.getString("passwordhistory"));
userInfo.setTimeZone(rs.getString("timezone"));
userInfo.setLocale(rs.getString("locale"));
userInfo.setPreferredLanguage(rs.getString("preferredlanguage"));
userInfo.setWorkEmail(rs.getString("workemail"));
userInfo.setWorkPhoneNumber(rs.getString("workphonenumber"));
userInfo.setWorkCountry(rs.getString("workcountry"));
userInfo.setWorkRegion(rs.getString("workregion"));
userInfo.setWorkLocality(rs.getString("worklocality"));
userInfo.setWorkStreetAddress(rs.getString("workstreetaddress"));
userInfo.setWorkAddressFormatted(rs.getString("workaddressformatted"));
userInfo.setWorkPostalCode(rs.getString("workpostalcode"));
userInfo.setWorkFax(rs.getString("workfax"));
userInfo.setHomeEmail(rs.getString("homeemail"));
userInfo.setHomePhoneNumber(rs.getString("homephonenumber"));
userInfo.setHomeCountry(rs.getString("homecountry"));
userInfo.setHomeRegion(rs.getString("homeregion"));
userInfo.setHomeLocality(rs.getString("homelocality"));
userInfo.setHomeStreetAddress(rs.getString("homestreetaddress"));
userInfo.setHomeAddressFormatted(rs.getString("homeaddressformatted"));
userInfo.setHomePostalCode(rs.getString("homepostalcode"));
userInfo.setHomeFax(rs.getString("homefax"));
userInfo.setEmployeeNumber(rs.getString("employeenumber"));
userInfo.setDivision(rs.getString("division"));
userInfo.setCostCenter(rs.getString("costcenter"));
userInfo.setOrganization(rs.getString("organization"));
userInfo.setDepartmentId(rs.getString("departmentid"));
userInfo.setDepartment(rs.getString("department"));
userInfo.setJobTitle(rs.getString("jobtitle"));
userInfo.setJobLevel(rs.getString("joblevel"));
userInfo.setManagerId(rs.getString("managerid"));
userInfo.setManager(rs.getString("manager"));
userInfo.setAssistantId(rs.getString("assistantid"));
userInfo.setAssistant(rs.getString("assistant"));
userInfo.setEntryDate(rs.getString("entrydate"));//
userInfo.setQuitDate(rs.getString("quitdate"));
userInfo.setStartWorkDate(rs.getString("startworkdate"));// STARTWORKDATE
userInfo.setExtraAttribute(rs.getString("extraattribute"));
userInfo.setCreatedBy(rs.getString("createdby"));
userInfo.setCreatedDate(rs.getTimestamp("createddate"));
userInfo.setModifiedBy(rs.getString("modifiedby"));
userInfo.setModifiedDate(rs.getTimestamp("modifieddate"));
userInfo.setStatus(rs.getInt("status"));
userInfo.setGridList(rs.getInt("gridlist"));
userInfo.setDescription(rs.getString("description"));
userInfo.setTheme(rs.getString("theme"));
userInfo.setInstId(rs.getString("instid"));
if (userInfo.getTheme() == null || userInfo.getTheme().equalsIgnoreCase("")) {
userInfo.setTheme("default");
}
return userInfo;
}
}
}
@@ -0,0 +1,72 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.util.Locale;
import org.passay.MessageResolver;
import org.passay.PropertiesMessageResolver;
import org.passay.RuleResultDetail;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;
public class PasswordPolicyMessageResolver implements MessageResolver{
/** A accessor for Spring's {@link MessageSource} */
private final MessageSourceAccessor messageSourceAccessor;
/** The {@link MessageResolver} for fallback */
private final MessageResolver fallbackMessageResolver = new PropertiesMessageResolver();
/**
* Create a new instance with the locale associated with the current thread.
* @param messageSource a message source managed by spring
*/
public PasswordPolicyMessageResolver(final MessageSource messageSource)
{
this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
}
/**
* Create a new instance with the specified locale.
* @param messageSource a message source managed by spring
* @param locale the locale to use for message access
*/
public PasswordPolicyMessageResolver(final MessageSource messageSource, final Locale locale)
{
this.messageSourceAccessor = new MessageSourceAccessor(messageSource, locale);
}
/**
* Resolves the message for the supplied rule result detail using Spring's {@link MessageSource}.
* (If the message can't retrieve from a {@link MessageSource}, return default message provided by passay)
* @param detail rule result detail
* @return message for the detail error code
*/
@Override
public String resolve(final RuleResultDetail detail)
{
try {
return this.messageSourceAccessor.getMessage("PasswordPolicy."+detail.getErrorCode(), detail.getValues());
} catch (NoSuchMessageException e) {
return this.fallbackMessageResolver.resolve(detail);
}
}
}
@@ -0,0 +1,186 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.dromara.maxkey.constants.ConstsProperties;
import org.dromara.maxkey.entity.cnf.CnfPasswordPolicy;
import org.passay.CharacterOccurrencesRule;
import org.passay.CharacterRule;
import org.passay.DictionaryRule;
import org.passay.EnglishCharacterData;
import org.passay.EnglishSequenceData;
import org.passay.IllegalSequenceRule;
import org.passay.LengthRule;
import org.passay.Rule;
import org.passay.UsernameRule;
import org.passay.WhitespaceRule;
import org.passay.dictionary.Dictionary;
import org.passay.dictionary.DictionaryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class PasswordPolicyRepository {
static final Logger _logger = LoggerFactory.getLogger(PasswordPolicyRepository.class);
//Dictionary topWeakPassword Source
public static final String TOPWEAKPASSWORD_PROPERTYSOURCE = "classpath:/top_weak_password.txt";
//Cache PasswordPolicy in memory ONE_HOUR
protected static final Cache<String, CnfPasswordPolicy> passwordPolicyStore =
Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build();
protected CnfPasswordPolicy passwordPolicy;
protected JdbcTemplate jdbcTemplate;
ArrayList <Rule> passwordPolicyRuleList;
private static final String PASSWORD_POLICY_KEY = "PASSWORD_POLICY_KEY";
private static final String PASSWORD_POLICY_SELECT_STATEMENT = "select * from mxk_cnf_password_policy ";
public PasswordPolicyRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* init PasswordPolicy and load Rules
* @return
*/
public CnfPasswordPolicy getPasswordPolicy() {
passwordPolicy = passwordPolicyStore.getIfPresent(PASSWORD_POLICY_KEY);
if (passwordPolicy == null) {
passwordPolicy = jdbcTemplate.queryForObject(PASSWORD_POLICY_SELECT_STATEMENT,
new PasswordPolicyRowMapper());
_logger.debug("query PasswordPolicy : {}" , passwordPolicy);
passwordPolicyStore.put(PASSWORD_POLICY_KEY,passwordPolicy);
//RandomPasswordLength =(MaxLength +MinLength)/2
passwordPolicy.setRandomPasswordLength(
Math.round(
(
passwordPolicy.getMaxLength() +
passwordPolicy.getMinLength()
)/2
)
);
passwordPolicyRuleList = new ArrayList<>();
passwordPolicyRuleList.add(new WhitespaceRule());
passwordPolicyRuleList.add(new LengthRule(passwordPolicy.getMinLength(), passwordPolicy.getMaxLength()));
if(passwordPolicy.getUpperCase()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.UpperCase, passwordPolicy.getUpperCase()));
}
if(passwordPolicy.getLowerCase()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.LowerCase, passwordPolicy.getLowerCase()));
}
if(passwordPolicy.getDigits()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.Digit, passwordPolicy.getDigits()));
}
if(passwordPolicy.getSpecialChar()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.Special, passwordPolicy.getSpecialChar()));
}
if(passwordPolicy.getUsername()>0) {
passwordPolicyRuleList.add(new UsernameRule());
}
if(passwordPolicy.getOccurances()>0) {
passwordPolicyRuleList.add(new CharacterOccurrencesRule(passwordPolicy.getOccurances()));
}
if(passwordPolicy.getAlphabetical()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 4, false));
}
if(passwordPolicy.getNumerical()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.Numerical, 4, false));
}
if(passwordPolicy.getQwerty()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.USQwerty, 4, false));
}
if(passwordPolicy.getDictionary()>0 ) {
try {
ClassPathResource dictFile=
new ClassPathResource(
ConstsProperties.classPathResource(TOPWEAKPASSWORD_PROPERTYSOURCE));
Dictionary dictionary =new DictionaryBuilder().addReader(new InputStreamReader(dictFile.getInputStream())).build();
passwordPolicyRuleList.add(new DictionaryRule(dictionary));
}catch(Exception e) {
e.printStackTrace();
}
}
}
return passwordPolicy;
}
public List<Rule> getPasswordPolicyRuleList() {
getPasswordPolicy();
return passwordPolicyRuleList;
}
public class PasswordPolicyRowMapper implements RowMapper<CnfPasswordPolicy> {
@Override
public CnfPasswordPolicy mapRow(ResultSet rs, int rowNum) throws SQLException {
CnfPasswordPolicy newPasswordPolicy = new CnfPasswordPolicy();
newPasswordPolicy.setId(rs.getString("id"));
newPasswordPolicy.setMinLength(rs.getInt("minlength"));
newPasswordPolicy.setMaxLength(rs.getInt("maxlength"));
newPasswordPolicy.setLowerCase(rs.getInt("lowercase"));
newPasswordPolicy.setUpperCase(rs.getInt("uppercase"));
newPasswordPolicy.setDigits(rs.getInt("digits"));
newPasswordPolicy.setSpecialChar(rs.getInt("specialchar"));
newPasswordPolicy.setAttempts(rs.getInt("attempts"));
newPasswordPolicy.setDuration(rs.getInt("duration"));
newPasswordPolicy.setExpiration(rs.getInt("expiration"));
newPasswordPolicy.setUsername(rs.getInt("username"));
newPasswordPolicy.setHistory(rs.getInt("history"));
newPasswordPolicy.setDictionary(rs.getInt("dictionary"));
newPasswordPolicy.setAlphabetical(rs.getInt("alphabetical"));
newPasswordPolicy.setNumerical(rs.getInt("numerical"));
newPasswordPolicy.setQwerty(rs.getInt("qwerty"));
newPasswordPolicy.setOccurances(rs.getInt("occurances"));
return newPasswordPolicy;
}
}
}
@@ -0,0 +1,325 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.repository;
import java.sql.Types;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsPasswordSetType;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.crypto.password.PasswordGen;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.cnf.CnfPasswordPolicy;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.web.WebConstants;
import org.dromara.maxkey.web.WebContext;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
public class PasswordPolicyValidator {
static final Logger _logger = LoggerFactory.getLogger(PasswordPolicyValidator.class);
PasswordPolicyRepository passwordPolicyRepository;
protected JdbcTemplate jdbcTemplate;
MessageSource messageSource;
public static final String PASSWORD_POLICY_VALIDATE_RESULT = "PASSWORD_POLICY_SESSION_VALIDATE_RESULT_KEY";
private static final String LOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String UNLOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , badpasswordtime = ? where id = ?";
private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , islocked = ? ,unlocktime = ? where id = ?";
public PasswordPolicyValidator() {
}
public PasswordPolicyValidator(JdbcTemplate jdbcTemplate,MessageSource messageSource) {
this.messageSource=messageSource;
this.jdbcTemplate = jdbcTemplate;
this.passwordPolicyRepository = new PasswordPolicyRepository(jdbcTemplate);
}
/**
* static validator .
* @param userInfo
* @return boolean
*/
public boolean validator(ChangePassword changePassword) {
String password = changePassword.getPassword();
String username = changePassword.getUsername();
if(StringUtils.isBlank(username)){
_logger.debug("username is Empty ");
return false;
}
if(StringUtils.isBlank(password)){
_logger.debug("password is Empty ");
return false;
}
PasswordValidator validator = new PasswordValidator(
new PasswordPolicyMessageResolver(messageSource),passwordPolicyRepository.getPasswordPolicyRuleList());
RuleResult result = validator.validate(new PasswordData(username,password));
if (result.isValid()) {
_logger.debug("Password is valid");
return true;
} else {
_logger.debug("Invalid password:");
String passwordPolicyMessage = "";
for (String msg : validator.getMessages(result)) {
passwordPolicyMessage = passwordPolicyMessage + msg + "<br>";
_logger.debug("Rule Message {}" , msg);
}
WebContext.setAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT, passwordPolicyMessage);
return false;
}
}
/**
* dynamic passwordPolicy Valid for user login.
* @param userInfo
* @return boolean
*/
public boolean passwordPolicyValid(UserInfo userInfo) {
CnfPasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
DateTime currentdateTime = new DateTime();
/*
* check login attempts fail times
*/
if (userInfo.getBadPasswordCount() >= passwordPolicy.getAttempts() && userInfo.getBadPasswordTime() != null) {
_logger.debug("login Attempts is {} , bad Password Time {}" , userInfo.getBadPasswordCount(),userInfo.getBadPasswordTime());
Duration duration = new Duration(new DateTime(userInfo.getBadPasswordTime()), currentdateTime);
int intDuration = Integer.parseInt(duration.getStandardMinutes() + "");
_logger.debug("bad Password duration {} , " +
"password policy Duration {} , "+
"validate result {}" ,
intDuration,
passwordPolicy.getDuration(),
(intDuration > passwordPolicy.getDuration())
);
//auto unlock attempts when intDuration >= set Duration
if(intDuration >= passwordPolicy.getDuration()) {
_logger.debug("resetAttempts ...");
resetAttempts(userInfo);
}else {
lockUser(userInfo);
throw new BadCredentialsException(
WebContext.getI18nValue("login.error.attempts",
new Object[]{userInfo.getBadPasswordCount(),passwordPolicy.getDuration()})
);
}
}
//locked
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
throw new BadCredentialsException(
userInfo.getUsername()+ " "+
WebContext.getI18nValue("login.error.locked")
);
}
// inactive
if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
throw new BadCredentialsException(
userInfo.getUsername()+
WebContext.getI18nValue("login.error.inactive")
);
}
return true;
}
public void applyPasswordPolicy(UserInfo userInfo) {
CnfPasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
DateTime currentdateTime = new DateTime();
//initial password need change
if(userInfo.getLoginCount()<=0) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.INITIAL_PASSWORD);
}
if (userInfo.getPasswordSetType() != ConstsPasswordSetType.PASSWORD_NORMAL) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
userInfo.getPasswordSetType());
return;
} else {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.PASSWORD_NORMAL);
}
/*
* check password is Expired,Expiration is Expired date ,if Expiration equals 0,not need check
*
*/
if (passwordPolicy.getExpiration() > 0 && userInfo.getPasswordLastSetTime() != null) {
_logger.info("last password set date {}" , userInfo.getPasswordLastSetTime());
Duration duration = new Duration(new DateTime(userInfo.getPasswordLastSetTime()), currentdateTime);
int intDuration = Integer.parseInt(duration.getStandardDays() + "");
_logger.debug("password Last Set duration day {} , " +
"password policy Expiration {} , " +
"validate result {}",
intDuration,
passwordPolicy.getExpiration(),
intDuration <= passwordPolicy.getExpiration()
);
if (intDuration > passwordPolicy.getExpiration()) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.PASSWORD_EXPIRED);
}
}
resetBadPasswordCount(userInfo);
}
/**
* lockUser
*
* @param userInfo
*/
public void lockUser(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
if(userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.LOCK, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.LOCK);
}
}
} catch (Exception e) {
_logger.error("lockUser Exception",e);
}
}
/**
* unlockUser
*
* @param userInfo
*/
public void unlockUser(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("unlockUser Exception",e);
}
}
/**
* reset BadPasswordCount And Lockout
*
* @param userInfo
*/
public void resetAttempts(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT,
new Object[] { 0, ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
userInfo.setBadPasswordCount(0);
}
} catch (Exception e) {
_logger.error("resetAttempts Exception",e);
}
}
/**
* if login password is error ,BadPasswordCount++ and set bad date
*
* @param userInfo
*/
private void setBadPasswordCount(String userId,int badPasswordCount) {
try {
jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT,
new Object[] { badPasswordCount, new Date(), userId },
new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
} catch (Exception e) {
_logger.error("setBadPasswordCount Exception",e);
}
}
public void plusBadPasswordCount(UserInfo userInfo) {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
userInfo.setBadPasswordCount(userInfo.getBadPasswordCount() + 1);
setBadPasswordCount(userInfo.getId(),userInfo.getBadPasswordCount());
CnfPasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
if(userInfo.getBadPasswordCount() >= passwordPolicy.getAttempts()) {
_logger.debug("Bad Password Count {} , Max Attempts {}",
userInfo.getBadPasswordCount() + 1,passwordPolicy.getAttempts());
this.lockUser(userInfo);
}
}
}
public void resetBadPasswordCount(UserInfo userInfo) {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
if(userInfo.getBadPasswordCount()>0) {
setBadPasswordCount(userInfo.getId(),0);
}
}
}
public String generateRandomPassword() {
CnfPasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
PasswordGen passwordGen = new PasswordGen(
passwordPolicy.getRandomPasswordLength()
);
return passwordGen.gen(
passwordPolicy.getLowerCase(),
passwordPolicy.getUpperCase(),
passwordPolicy.getDigits(),
passwordPolicy.getSpecialChar());
}
public PasswordPolicyRepository getPasswordPolicyRepository() {
return passwordPolicyRepository;
}
}
@@ -17,24 +17,26 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.PasswordPolicy;
import org.dromara.maxkey.persistence.mapper.PasswordPolicyMapper;
import org.dromara.maxkey.entity.Access;
import org.dromara.maxkey.persistence.mapper.AccessMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@Repository
public class PasswordPolicyService extends JpaService<PasswordPolicy>{
public PasswordPolicyService() {
super(PasswordPolicyMapper.class);
public class AccessService extends JpaService<Access>{
public AccessService() {
super(AccessMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public PasswordPolicyMapper getMapper() {
return (PasswordPolicyMapper)super.getMapper();
public AccessMapper getMapper() {
return (AccessMapper)super.getMapper();
}
}
@@ -19,17 +19,17 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.crypto.password.PasswordReciprocal;
import org.dromara.maxkey.entity.Accounts;
import org.dromara.maxkey.entity.AccountsStrategy;
import org.dromara.maxkey.entity.OrganizationsCast;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.mapper.AccountsMapper;
import org.dromara.maxkey.provision.ProvisionAction;
import org.dromara.maxkey.provision.ProvisionAct;
import org.dromara.maxkey.provision.ProvisionService;
import org.dromara.maxkey.provision.ProvisionTopic;
import org.dromara.maxkey.util.StringUtils;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@@ -81,7 +81,7 @@ public class AccountsService extends JpaService<Accounts>{
provisionService.send(
ProvisionTopic.ACCOUNT_TOPIC,
account,
ProvisionAction.CREATE_ACTION);
ProvisionAct.CREATE);
}
return true;
@@ -102,7 +102,7 @@ public class AccountsService extends JpaService<Accounts>{
provisionService.send(
ProvisionTopic.ACCOUNT_TOPIC,
account,
ProvisionAction.UPDATE_ACTION);
ProvisionAct.UPDATE);
}
return true;
@@ -114,10 +114,9 @@ public class AccountsService extends JpaService<Accounts>{
return this.getMapper().updateStatus(accounts) > 0;
}
@Override
public boolean remove(String id) {
Accounts account = this.get(id);
if (super.remove(id)) {
if (super.delete(id)) {
UserInfo loadUserInfo = null;
if(provisionService.getApplicationConfig().isProvisionSupport()) {
loadUserInfo = userInfoService.findUserRelated(account.getUserId());
@@ -125,7 +124,7 @@ public class AccountsService extends JpaService<Accounts>{
provisionService.send(
ProvisionTopic.ACCOUNT_TOPIC,
account,
ProvisionAction.DELETE_ACTION);
ProvisionAct.DELETE);
}
return true;
@@ -189,17 +188,17 @@ public class AccountsService extends JpaService<Accounts>{
String shortAccount = generateAccount(userInfo,accountsStrategy,true);
String account = generateAccount(userInfo,accountsStrategy,false);
String accountResult = shortAccount;
List<Accounts> AccountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),shortAccount +accountsStrategy.getSuffixes());
if(!AccountsList.isEmpty()) {
List<Accounts> accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),shortAccount +accountsStrategy.getSuffixes());
if(!accountsList.isEmpty()) {
if(accountsStrategy.getMapping().equalsIgnoreCase("email")) {
accountResult = account;
AccountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),account + accountsStrategy.getSuffixes());
accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),account + accountsStrategy.getSuffixes());
}
if(!AccountsList.isEmpty()) {
if(!accountsList.isEmpty()) {
for(int i =1 ;i < 100 ;i++) {
accountResult = account + i;
AccountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),accountResult + accountsStrategy.getSuffixes());
if(AccountsList.isEmpty()) {
accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),accountResult + accountsStrategy.getSuffixes());
if(accountsList.isEmpty()) {
break;
}
}
@@ -21,7 +21,7 @@ import java.io.Serializable;
import java.util.List;
import org.dromara.maxkey.entity.AccountsStrategy;
import org.dromara.maxkey.entity.Roles;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.maxkey.persistence.mapper.AccountsStrategyMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
@@ -35,9 +35,8 @@ public class AccountsStrategyService extends JpaService<AccountsStrategy> imple
*/
private static final long serialVersionUID = -921086134545225302L;
final static Logger _logger = LoggerFactory.getLogger(AccountsStrategyService.class);
static final Logger _logger = LoggerFactory.getLogger(AccountsStrategyService.class);
/*
@JsonIgnore
@Autowired
@Qualifier("groupMemberService")
GroupMemberService accountsStrategyService;
@@ -60,7 +59,7 @@ public class AccountsStrategyService extends JpaService<AccountsStrategy> imple
}
public boolean deleteById(String groupId) {
this.remove(groupId);
this.delete(groupId);
//groupMemberService.deleteByGroupId(groupId);
return true;
}
@@ -30,7 +30,7 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsCasDetailsService extends JpaService<AppsCasDetails>{
protected final static Cache<String, AppsCasDetails> detailsCache =
protected static final Cache<String, AppsCasDetails> detailsCache =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
@@ -30,7 +30,7 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsFormBasedDetailsService extends JpaService<AppsFormBasedDetails>{
protected final static Cache<String, AppsFormBasedDetails> detailsCache =
protected static final Cache<String, AppsFormBasedDetails> detailsCache =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
@@ -30,7 +30,7 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsJwtDetailsService extends JpaService<AppsJwtDetails>{
protected final static Cache<String, AppsJwtDetails> detailsCache =
protected static final Cache<String, AppsJwtDetails> detailsCache =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
@@ -30,7 +30,7 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsSaml20DetailsService extends JpaService<AppsSAML20Details>{
protected final static Cache<String, AppsSAML20Details> detailsCache =
protected static final Cache<String, AppsSAML20Details> detailsCache =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
@@ -32,11 +32,11 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsService extends JpaService<Apps>{
//maxkey-mgt
public final static String MGT_APP_ID = "622076759805923328";
public static final String MGT_APP_ID = "622076759805923328";
public final static String DETAIL_SUFFIX = "_detail";
public static final String DETAIL_SUFFIX = "_detail";
protected final static Cache<String, Apps> detailsCacheStore =
protected static final Cache<String, Apps> detailsCacheStore =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.build();
@@ -30,7 +30,7 @@ import com.github.benmanes.caffeine.cache.Caffeine;
@Repository
public class AppsTokenBasedDetailsService extends JpaService<AppsTokenBasedDetails>{
protected final static Cache<String, AppsTokenBasedDetails> detailsCache =
protected static final Cache<String, AppsTokenBasedDetails> detailsCache =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
@@ -17,25 +17,26 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.LdapContext;
import org.dromara.maxkey.persistence.mapper.LdapContextMapper;
import org.dromara.maxkey.entity.cnf.CnfEmailSenders;
import org.dromara.maxkey.persistence.mapper.CnfEmailSendersMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@Repository
public class LdapContextService extends JpaService<LdapContext>{
public class CnfEmailSendersService extends JpaService<CnfEmailSenders>{
public LdapContextService() {
super(LdapContextMapper.class);
public CnfEmailSendersService() {
super(CnfEmailSendersMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public LdapContextMapper getMapper() {
return (LdapContextMapper)super.getMapper();
public CnfEmailSendersMapper getMapper() {
return (CnfEmailSendersMapper)super.getMapper();
}
@@ -17,25 +17,25 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.SmsProvider;
import org.dromara.maxkey.persistence.mapper.SmsProviderMapper;
import org.dromara.maxkey.entity.cnf.CnfLdapContext;
import org.dromara.maxkey.persistence.mapper.CnfLdapContextMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@Repository
public class SmsProviderService extends JpaService<SmsProvider>{
public class CnfLdapContextService extends JpaService<CnfLdapContext>{
public SmsProviderService() {
super(SmsProviderMapper.class);
public CnfLdapContextService() {
super(CnfLdapContextMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public SmsProviderMapper getMapper() {
return (SmsProviderMapper)super.getMapper();
public CnfLdapContextMapper getMapper() {
return (CnfLdapContextMapper)super.getMapper();
}
@@ -17,26 +17,24 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.GroupPermissions;
import org.dromara.maxkey.persistence.mapper.GroupPermissionsMapper;
import org.dromara.maxkey.entity.cnf.CnfPasswordPolicy;
import org.dromara.maxkey.persistence.mapper.CnfPasswordPolicyMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@Repository
public class GroupPermissionssService extends JpaService<GroupPermissions>{
public GroupPermissionssService() {
super(GroupPermissionsMapper.class);
public class CnfPasswordPolicyService extends JpaService<CnfPasswordPolicy>{
public CnfPasswordPolicyService() {
super(CnfPasswordPolicyMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public GroupPermissionsMapper getMapper() {
return (GroupPermissionsMapper)super.getMapper();
public CnfPasswordPolicyMapper getMapper() {
return (CnfPasswordPolicyMapper)super.getMapper();
}
}
@@ -17,26 +17,25 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.EmailSenders;
import org.dromara.maxkey.persistence.mapper.EmailSendersMapper;
import org.dromara.maxkey.entity.cnf.CnfSmsProvider;
import org.dromara.maxkey.persistence.mapper.CnfSmsProviderMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@Repository
public class EmailSendersService extends JpaService<EmailSenders>{
public class CnfSmsProviderService extends JpaService<CnfSmsProvider>{
public EmailSendersService() {
super(EmailSendersMapper.class);
public CnfSmsProviderService() {
super(CnfSmsProviderMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public EmailSendersMapper getMapper() {
return (EmailSendersMapper)super.getMapper();
public CnfSmsProviderMapper getMapper() {
return (CnfSmsProviderMapper)super.getMapper();
}
@@ -26,7 +26,7 @@ import org.springframework.stereotype.Repository;
@Repository
public class ConnectorsService extends JpaService<Connectors>{
final static Logger _logger = LoggerFactory.getLogger(ConnectorsService.class);
static final Logger _logger = LoggerFactory.getLogger(ConnectorsService.class);
public ConnectorsService() {
super(ConnectorsMapper.class);
@@ -19,9 +19,9 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.GroupMember;
import org.dromara.maxkey.entity.Groups;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.GroupMember;
import org.dromara.maxkey.entity.idm.Groups;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.mapper.GroupMemberMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
@@ -31,7 +31,7 @@ import org.springframework.stereotype.Repository;
@Repository
public class GroupMemberService extends JpaService<GroupMember>{
final static Logger _logger = LoggerFactory.getLogger(GroupMemberService.class);
static final Logger _logger = LoggerFactory.getLogger(GroupMemberService.class);
public GroupMemberService() {
super(GroupMemberMapper.class);
@@ -63,7 +63,7 @@ public class GroupMemberService extends JpaService<GroupMember>{
public JpaPageResults<Groups> noMember(GroupMember entity) {
entity.setPageResultSelectUUID(entity.generateId());
entity.setPageSelectId(entity.generateId());
entity.setStartRow(calculateStartRow(entity.getPageNumber() ,entity.getPageSize()));
entity.setPageable(true);
@@ -17,35 +17,26 @@
package org.dromara.maxkey.persistence.service;
import java.io.Serializable;
import java.sql.Types;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.entity.Groups;
import org.dromara.maxkey.entity.Institutions;
import org.dromara.maxkey.entity.Roles;
import org.dromara.maxkey.entity.idm.Groups;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.maxkey.persistence.mapper.GroupsMapper;
import org.dromara.maxkey.util.StringUtils;
import org.dromara.maxkey.util.StrUtils;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Repository
public class GroupsService extends JpaService<Groups> implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4156671926199393550L;
final static Logger _logger = LoggerFactory.getLogger(GroupsService.class);
@JsonIgnore
public class GroupsService extends JpaService<Groups>{
static final Logger _logger = LoggerFactory.getLogger(GroupsService.class);
@Autowired
GroupMemberService groupMemberService;
@@ -70,7 +61,7 @@ public class GroupsService extends JpaService<Groups> implements Serializable {
}
public boolean deleteById(String groupId) {
this.remove(groupId);
this.delete(groupId);
groupMemberService.deleteByGroupId(groupId);
return true;
}
@@ -81,26 +72,6 @@ public class GroupsService extends JpaService<Groups> implements Serializable {
public void refreshDynamicGroups(Groups dynamicGroup){
if(dynamicGroup.getCategory().equals(Roles.Category.DYNAMIC)) {
boolean isDynamicTimeSupport = false;
boolean isBetweenEffectiveTime = false;
if(StringUtils.isNotBlank(dynamicGroup.getResumeTime())
&&StringUtils.isNotBlank(dynamicGroup.getSuspendTime())
&&!dynamicGroup.getSuspendTime().equals("00:00")) {
LocalTime currentTime = LocalDateTime.now().toLocalTime();
LocalTime resumeTime = LocalTime.parse(dynamicGroup.getResumeTime());
LocalTime suspendTime = LocalTime.parse(dynamicGroup.getSuspendTime());
_logger.info("currentTime: {} , resumeTime : {} , suspendTime: {}"
, currentTime
, resumeTime
, suspendTime);
isDynamicTimeSupport = true;
if(resumeTime.isBefore(currentTime) && currentTime.isBefore(suspendTime)) {
isBetweenEffectiveTime = true;
}
}
if(StringUtils.isNotBlank(dynamicGroup.getOrgIdsList())) {
String []orgIds = dynamicGroup.getOrgIdsList().split(",");
@@ -120,27 +91,19 @@ public class GroupsService extends JpaService<Groups> implements Serializable {
String filters = dynamicGroup.getFilters();
if(StringUtils.isNotBlank(filters)) {
if(StringUtils.filtersSQLInjection(filters.toLowerCase())) {
if(StrUtils.filtersSQLInjection(filters.toLowerCase())) {
_logger.info("filters include SQL Injection Attack Risk.");
return;
}
filters = filters.replace("&", " AND ");
filters = filters.replace("|", " OR ");
//replace & with AND, | with OR
filters = filters.replace("&", " AND ").replace("|", " OR ");
dynamicGroup.setFilters(filters);
}
if(isDynamicTimeSupport) {
if(isBetweenEffectiveTime) {
groupMemberService.deleteDynamicMember(dynamicGroup);
groupMemberService.addDynamicMember(dynamicGroup);
}else {
groupMemberService.deleteDynamicMember(dynamicGroup);
}
}else{
groupMemberService.deleteDynamicMember(dynamicGroup);
groupMemberService.addDynamicMember(dynamicGroup);
}
groupMemberService.deleteDynamicMember(dynamicGroup);
groupMemberService.addDynamicMember(dynamicGroup);
}
}
@@ -17,7 +17,7 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.HistoryConnector;
import org.dromara.maxkey.entity.history.HistoryConnector;
import org.dromara.maxkey.persistence.mapper.HistoryConnectorMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -17,7 +17,7 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.HistoryLoginApps;
import org.dromara.maxkey.entity.history.HistoryLoginApps;
import org.dromara.maxkey.persistence.mapper.HistoryLoginAppsMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -17,7 +17,7 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.HistoryLogin;
import org.dromara.maxkey.entity.history.HistoryLogin;
import org.dromara.maxkey.persistence.mapper.HistoryLoginMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
@@ -17,7 +17,7 @@
package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.HistorySynchronizer;
import org.dromara.maxkey.entity.history.HistorySynchronizer;
import org.dromara.maxkey.persistence.mapper.HistorySynchronizerMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -19,16 +19,19 @@ package org.dromara.maxkey.persistence.service;
import org.dromara.maxkey.entity.Accounts;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.HistorySystemLogs;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.Resources;
import org.dromara.maxkey.entity.RoleMember;
import org.dromara.maxkey.entity.GroupPermissions;
import org.dromara.maxkey.entity.GroupPrivileges;
import org.dromara.maxkey.entity.Roles;
import java.util.Date;
import org.dromara.maxkey.entity.Access;
import org.dromara.maxkey.entity.SocialsProvider;
import org.dromara.maxkey.entity.Synchronizers;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.history.HistorySystemLogs;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.entity.permissions.Permission;
import org.dromara.maxkey.entity.permissions.Resources;
import org.dromara.maxkey.entity.permissions.RoleMember;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.maxkey.persistence.mapper.HistorySystemLogsMapper;
import org.dromara.maxkey.util.JsonUtils;
import org.dromara.mybatis.jpa.JpaService;
@@ -38,16 +41,13 @@ import org.springframework.stereotype.Repository;
@Repository
public class HistorySystemLogsService extends JpaService<HistorySystemLogs>{
final static Logger _logger = LoggerFactory.getLogger(HistorySystemLogsService.class);
static final Logger _logger = LoggerFactory.getLogger(HistorySystemLogsService.class);
public HistorySystemLogsService() {
super(HistorySystemLogsMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public HistorySystemLogsMapper getMapper() {
return (HistorySystemLogsMapper)super.getMapper();
@@ -56,28 +56,28 @@ public class HistorySystemLogsService extends JpaService<HistorySystemLogs>{
public void insert(String topic,Object entity,String action,String result,UserInfo operator) {
String message = "";
if(entity != null) {
if(entity instanceof UserInfo) {
message = buildMsg((UserInfo)entity);
}else if(entity instanceof Organizations) {
message = buildMsg((Organizations)entity);
}else if(entity instanceof ChangePassword) {
message = buildMsg((ChangePassword)entity);
}else if(entity instanceof Accounts) {
message = buildMsg((Accounts)entity);
}else if(entity instanceof Roles) {
message = buildMsg((Roles)entity);
}else if(entity instanceof RoleMember) {
message = buildMsg((RoleMember)entity);
}else if(entity instanceof GroupPermissions) {
message = buildMsg((GroupPermissions)entity);
}else if(entity instanceof Resources) {
message = buildMsg((Resources)entity);
}else if(entity instanceof Synchronizers) {
message = buildMsg((Synchronizers)entity);
}else if(entity instanceof SocialsProvider) {
message = buildMsg((SocialsProvider)entity);
}else if(entity instanceof GroupPrivileges) {
message = buildMsg((GroupPrivileges)entity);
if(entity instanceof UserInfo userInfo) {
message = buildMsg(userInfo);
}else if(entity instanceof Organizations organization) {
message = buildMsg(organization);
}else if(entity instanceof ChangePassword changePassword) {
message = buildMsg(changePassword);
}else if(entity instanceof Accounts account) {
message = buildMsg(account);
}else if(entity instanceof Roles role) {
message = buildMsg(role);
}else if(entity instanceof RoleMember roleMember) {
message = buildMsg(roleMember);
}else if(entity instanceof Access access) {
message = buildMsg(access);
}else if(entity instanceof Resources resource) {
message = buildMsg(resource);
}else if(entity instanceof Synchronizers synchronizer) {
message = buildMsg(synchronizer);
}else if(entity instanceof SocialsProvider socialsProvider) {
message = buildMsg(socialsProvider);
}else if(entity instanceof Permission permission) {
message = buildMsg(permission);
}else if(entity instanceof String) {
message = entity.toString();
}
@@ -99,6 +99,7 @@ public class HistorySystemLogsService extends JpaService<HistorySystemLogs>{
systemLog.setDisplayName(operator.getDisplayName());
systemLog.setInstId(operator.getInstId());
systemLog.setJsonCotent(JsonUtils.gsonToString(entity));
systemLog.setExecuteTime(new Date());
_logger.trace("System Log {}" ,systemLog);
getMapper().insert(systemLog);
}
@@ -157,7 +158,7 @@ public class HistorySystemLogsService extends JpaService<HistorySystemLogs>{
.toString();
}
public String buildMsg(GroupPermissions permission) {
public String buildMsg(Access permission) {
return new StringBuilder()
.append(permission.getGroupName())
.append("[")
@@ -166,7 +167,7 @@ public class HistorySystemLogsService extends JpaService<HistorySystemLogs>{
.toString();
}
public String buildMsg(GroupPrivileges privilege) {
public String buildMsg(Permission privilege) {
return new StringBuilder()
.append(privilege.getGroupId())
.append("[")
@@ -28,7 +28,7 @@ import org.springframework.stereotype.Repository;
@Repository
public class OrganizationsCastService extends JpaService<OrganizationsCast>{
final static Logger _logger = LoggerFactory.getLogger(OrganizationsCastService.class);
static final Logger _logger = LoggerFactory.getLogger(OrganizationsCastService.class);
public OrganizationsCastService() {
@@ -25,9 +25,9 @@ import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.maxkey.persistence.mapper.OrganizationsMapper;
import org.dromara.maxkey.provision.ProvisionAction;
import org.dromara.maxkey.provision.ProvisionAct;
import org.dromara.maxkey.provision.ProvisionService;
import org.dromara.maxkey.provision.ProvisionTopic;
import org.dromara.mybatis.jpa.JpaService;
@@ -61,7 +61,7 @@ public class OrganizationsService extends JpaService<Organizations>{
public boolean insert(Organizations organization) {
if(super.insert(organization)){
provisionService.send(
ProvisionTopic.ORG_TOPIC, organization, ProvisionAction.CREATE_ACTION);
ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.CREATE);
return true;
}
return false;
@@ -71,7 +71,7 @@ public class OrganizationsService extends JpaService<Organizations>{
public boolean update(Organizations organization) {
if(super.update(organization)){
provisionService.send(
ProvisionTopic.ORG_TOPIC, organization, ProvisionAction.UPDATE_ACTION);
ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.UPDATE);
return true;
}
return false;
@@ -92,11 +92,10 @@ public class OrganizationsService extends JpaService<Organizations>{
return getMapper().queryOrgs(organization);
}
@Override
public boolean delete(Organizations organization) {
if(super.delete(organization)){
if(super.delete(organization.getId())){
provisionService.send(
ProvisionTopic.ORG_TOPIC, organization, ProvisionAction.DELETE_ACTION);
ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.DELETE);
return true;
}
return false;
@@ -0,0 +1,56 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.permissions.PermissionRole;
import org.dromara.maxkey.persistence.mapper.PermissionRoleMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
@Repository
public class PermissionRoleService extends JpaService<PermissionRole>{
static final Logger _logger = LoggerFactory.getLogger(PermissionRoleService.class);
public PermissionRoleService() {
super(PermissionRoleMapper.class);
}
@Override
public PermissionRoleMapper getMapper() {
return (PermissionRoleMapper)super.getMapper();
}
public boolean insertPermissionRoles(List<PermissionRole> permissionRolesList) {
return getMapper().insertPermissionRoles(permissionRolesList)>0;
}
public boolean deletePermissionRoles(List<PermissionRole> permissionRolesList) {
return getMapper().deletePermissionRoles(permissionRolesList)>=0;
}
public List<PermissionRole> queryPermissionRoles(PermissionRole permissionRole){
return getMapper().queryPermissionRoles(permissionRole);
}
}
@@ -19,39 +19,39 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.GroupPrivileges;
import org.dromara.maxkey.persistence.mapper.GroupPrivilegesMapper;
import org.dromara.maxkey.entity.permissions.Permission;
import org.dromara.maxkey.persistence.mapper.PermissionMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
@Repository
public class GroupPrivilegesService extends JpaService<GroupPrivileges>{
final static Logger _logger = LoggerFactory.getLogger(GroupPrivilegesService.class);
public class PermissionService extends JpaService<Permission>{
static final Logger _logger = LoggerFactory.getLogger(PermissionService.class);
public GroupPrivilegesService() {
super(GroupPrivilegesMapper.class);
public PermissionService() {
super(PermissionMapper.class);
}
/* (non-Javadoc)
* @see com.connsec.db.service.BaseService#getMapper()
*/
@Override
public GroupPrivilegesMapper getMapper() {
return (GroupPrivilegesMapper)super.getMapper();
public PermissionMapper getMapper() {
return (PermissionMapper)super.getMapper();
}
public boolean insertGroupPrivileges(List<GroupPrivileges> rolePermissionsList) {
public boolean insertGroupPrivileges(List<Permission> rolePermissionsList) {
return getMapper().insertGroupPrivileges(rolePermissionsList)>0;
};
public boolean deleteGroupPrivileges(List<GroupPrivileges> rolePermissionsList) {
public boolean deleteGroupPrivileges(List<Permission> rolePermissionsList) {
return getMapper().deleteGroupPrivileges(rolePermissionsList)>=0;
}
public List<GroupPrivileges> queryGroupPrivileges(GroupPrivileges rolePermissions){
public List<Permission> queryGroupPrivileges(Permission rolePermissions){
return getMapper().queryGroupPrivileges(rolePermissions);
}
@@ -20,7 +20,7 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.Register;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.mapper.RegisterMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -19,7 +19,7 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.Resources;
import org.dromara.maxkey.entity.permissions.Resources;
import org.dromara.maxkey.persistence.mapper.ResourcesMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -0,0 +1,87 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.entity.permissions.RoleMember;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.maxkey.persistence.mapper.RoleMemberMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
@Repository
public class RoleMemberService extends JpaService<RoleMember>{
static final Logger _logger = LoggerFactory.getLogger(RoleMemberService.class);
public RoleMemberService() {
super(RoleMemberMapper.class);
}
@Override
public RoleMemberMapper getMapper() {
return (RoleMemberMapper)super.getMapper();
}
public int addDynamicRoleMember(Roles dynamicGroup) {
return getMapper().addDynamicRoleMember(dynamicGroup);
}
public int deleteDynamicRoleMember(Roles dynamicGroup) {
return getMapper().deleteDynamicRoleMember(dynamicGroup);
}
public int deleteByRoleId(String groupId) {
return getMapper().deleteByRoleId(groupId);
}
public List<UserInfo> queryMemberByRoleId(String groupId){
return getMapper().queryMemberByRoleId(groupId);
}
public JpaPageResults<Roles> rolesNoMember(RoleMember entity) {
entity.setPageSelectId(entity.generateId());
entity.setStartRow(calculateStartRow(entity.getPageNumber() ,entity.getPageSize()));
entity.setPageable(true);
List<Roles> resultslist = null;
try {
resultslist = getMapper().rolesNoMember(entity);
} catch (Exception e) {
_logger.error("fetchPageResults Exception " , e);
}
entity.setPageable(false);
Integer totalPage = resultslist.size();
Integer totalCount = 0;
if(entity.getPageNumber() == 1 && totalPage < entity.getPageSize()) {
totalCount = totalPage;
}else {
totalCount = parseCount(getMapper().fetchCount(entity));
}
return new JpaPageResults<Roles>(entity.getPageNumber(),entity.getPageSize(),totalPage,totalCount,resultslist);
}
}
@@ -0,0 +1,124 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.dromara.maxkey.persistence.service;
import java.sql.Types;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.entity.Institutions;
import org.dromara.maxkey.entity.permissions.Roles;
import org.dromara.maxkey.persistence.mapper.RolesMapper;
import org.dromara.maxkey.util.StrUtils;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class RolesService extends JpaService<Roles> {
static final Logger _logger = LoggerFactory.getLogger(RolesService.class);
@Autowired
RoleMemberService roleMemberService;
@Autowired
InstitutionsService institutionsService;
public RolesService() {
super(RolesMapper.class);
}
@Override
public RolesMapper getMapper() {
return (RolesMapper)super.getMapper();
}
public List<Roles> queryDynamicRoles(Roles groups){
return this.getMapper().queryDynamicRoles(groups);
}
public boolean deleteById(String groupId) {
this.delete(groupId);
roleMemberService.deleteByRoleId(groupId);
return true;
}
public List<Roles> queryRolesByUserId(String userId){
return this.getMapper().queryRolesByUserId(userId);
}
public void refreshDynamicRoles(Roles dynamicRole){
if(dynamicRole.getCategory().equals(Roles.Category.DYNAMIC)) {
if(StringUtils.isNotBlank(dynamicRole.getOrgIdsList())) {
String []orgIds = dynamicRole.getOrgIdsList().split(",");
StringBuffer orgIdFilters = new StringBuffer();
for(String orgId : orgIds) {
if(StringUtils.isNotBlank(orgId)) {
if(orgIdFilters.length() > 0) {
orgIdFilters.append(",");
}
orgIdFilters.append("'").append(orgId).append("'");
}
}
if(orgIdFilters.length() > 0) {
dynamicRole.setOrgIdsList(orgIdFilters.toString());
}
}
String filters = dynamicRole.getFilters();
_logger.debug("filters {}" , filters);
if(StringUtils.isNotBlank(filters)) {
if(StrUtils.filtersSQLInjection(filters.toLowerCase())) {
_logger.info("filters include SQL Injection Attack Risk.");
return;
}
//replace & with AND, | with OR
filters = filters.replace("&", " AND ").replace("\\|", " OR ");
_logger.debug("set filters {}" , filters);
dynamicRole.setFilters(filters);
}
roleMemberService.deleteDynamicRoleMember(dynamicRole);
roleMemberService.addDynamicRoleMember(dynamicRole);
}
}
public void refreshAllDynamicRoles(){
List<Institutions> instList =
institutionsService.find("where status = ? ", new Object[]{ConstsStatus.ACTIVE}, new int[]{Types.INTEGER});
for(Institutions inst : instList) {
Roles role = new Roles();
role.setInstId(inst.getId());
List<Roles> rolesList = queryDynamicRoles(role);
for(Roles r : rolesList) {
_logger.debug("role {}" , r);
refreshDynamicRoles(r);
}
}
}
}
@@ -20,7 +20,7 @@ package org.dromara.maxkey.persistence.service;
import java.util.List;
import org.dromara.maxkey.entity.SocialsAssociate;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.mapper.SocialsAssociateMapper;
import org.dromara.mybatis.jpa.JpaService;
import org.springframework.stereotype.Repository;
@@ -26,7 +26,7 @@ import org.springframework.stereotype.Repository;
@Repository
public class SocialsProviderService extends JpaService<SocialsProvider>{
final static Logger _logger = LoggerFactory.getLogger(SocialsProviderService.class);
static final Logger _logger = LoggerFactory.getLogger(SocialsProviderService.class);
public SocialsProviderService() {
@@ -21,9 +21,9 @@ import java.sql.Types;
import java.util.Date;
import java.util.List;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.SynchroRelated;
import org.dromara.maxkey.entity.Synchronizers;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.maxkey.persistence.mapper.SynchroRelatedMapper;
import org.dromara.maxkey.util.DateUtils;
import org.dromara.mybatis.jpa.JpaService;
@@ -26,7 +26,7 @@ import org.springframework.stereotype.Repository;
@Repository
public class SynchronizersService extends JpaService<Synchronizers>{
final static Logger _logger = LoggerFactory.getLogger(SynchronizersService.class);
static final Logger _logger = LoggerFactory.getLogger(SynchronizersService.class);
public SynchronizersService() {
super(SynchronizersMapper.class);
@@ -21,18 +21,17 @@ package org.dromara.maxkey.persistence.service;
import java.sql.Types;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.crypto.password.PasswordReciprocal;
import org.dromara.maxkey.entity.Accounts;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.mapper.UserInfoMapper;
import org.dromara.maxkey.persistence.repository.PasswordPolicyValidator;
import org.dromara.maxkey.provision.ProvisionAction;
import org.dromara.maxkey.provision.ProvisionAct;
import org.dromara.maxkey.provision.ProvisionService;
import org.dromara.maxkey.provision.ProvisionTopic;
import org.dromara.maxkey.util.DateUtils;
import org.dromara.maxkey.util.StringUtils;
import org.dromara.maxkey.web.WebContext;
import org.dromara.mybatis.jpa.JpaService;
import org.slf4j.Logger;
@@ -48,7 +47,7 @@ import org.springframework.stereotype.Repository;
*/
@Repository
public class UserInfoService extends JpaService<UserInfo> {
final static Logger _logger = LoggerFactory.getLogger(UserInfoService.class);
static final Logger _logger = LoggerFactory.getLogger(UserInfoService.class);
@Autowired
private PasswordEncoder passwordEncoder;
@@ -82,7 +81,7 @@ public class UserInfoService extends JpaService<UserInfo> {
provisionService.send(
ProvisionTopic.USERINFO_TOPIC,
loadUserInfo,
ProvisionAction.CREATE_ACTION);
ProvisionAct.CREATE);
}
return true;
@@ -101,7 +100,7 @@ public class UserInfoService extends JpaService<UserInfo> {
provisionService.send(
ProvisionTopic.USERINFO_TOPIC,
loadUserInfo,
ProvisionAction.CREATE_ACTION);
ProvisionAct.CREATE);
}
return true;
@@ -120,7 +119,7 @@ public class UserInfoService extends JpaService<UserInfo> {
provisionService.send(
ProvisionTopic.USERINFO_TOPIC,
loadUserInfo,
ProvisionAction.UPDATE_ACTION);
ProvisionAct.UPDATE);
}
if(userInfo.getPassword() != null) {
changePasswordProvisioning(changePassword);
@@ -130,18 +129,17 @@ public class UserInfoService extends JpaService<UserInfo> {
return false;
}
@Override
public boolean delete(UserInfo userInfo) {
UserInfo loadUserInfo = null;
if(provisionService.getApplicationConfig().isProvisionSupport()) {
loadUserInfo = findUserRelated(userInfo.getId());
}
if( super.delete(userInfo)){
if( super.delete(userInfo.getId())){
provisionService.send(
ProvisionTopic.USERINFO_TOPIC,
loadUserInfo,
ProvisionAction.DELETE_ACTION);
ProvisionAct.DELETE);
accountUpdate(loadUserInfo);
return true;
}
@@ -338,7 +336,7 @@ public class UserInfoService extends JpaService<UserInfo> {
provisionService.send(
ProvisionTopic.PASSWORD_TOPIC,
changePassword,
ProvisionAction.PASSWORD_ACTION);
ProvisionAct.PASSWORD);
}
}
@@ -17,14 +17,14 @@
package org.dromara.maxkey.provision;
public class ProvisionAction {
public class ProvisionAct {
public static final String CREATE_ACTION = "CREATE_ACTION";
public static final String CREATE = "CREATE";
public static final String DELETE_ACTION = "DELETE_ACTION";
public static final String DELETE = "DELETE";
public static final String UPDATE_ACTION = "UPDATE_ACTION";
public static final String UPDATE = "UPDATE";
public static final String PASSWORD_ACTION = "PASSWORD_ACTION";
public static final String PASSWORD = "PASSWORD";
}
@@ -27,11 +27,17 @@ public class ProvisionTopic {
public static final String ACCOUNT_TOPIC = "MXK_IDENTITY_ACCOUNT_TOPIC";
public static final String GROUP_TOPIC = "MXK_GROUP_TOPIC";
public static final String GROUP_MEMBER_TOPIC = "MXK_GROUP_MEMBER_TOPIC";
public static final String GROUP_PERMISSIONS_TOPIC = "MXK_GROUP_PERMISSIONS_TOPIC";
public static final String ROLE_TOPIC = "MXK_ROLE_TOPIC";
public static final String ROLE_MEMBER_TOPIC = "MXK_ROLE_MEMBER_TOPIC";
public static final String ROLE_PRIVILEGES_TOPIC = "MXK_ROLE_PRIVILEGES_TOPIC";
public static final String ROLE_PERMISSIONS_TOPIC = "MXK_ROLE_PERMISSIONS_TOPIC";
public static final String RESOURCE_TOPIC = "MXK_RESOURCE_TOPIC";
@@ -25,10 +25,10 @@ import org.dromara.maxkey.crypto.password.PasswordReciprocal;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.Connectors;
import org.dromara.maxkey.entity.Message;
import org.dromara.maxkey.entity.Organizations;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.entity.idm.Organizations;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.maxkey.persistence.service.ConnectorsService;
import org.dromara.maxkey.provision.ProvisionAction;
import org.dromara.maxkey.provision.ProvisionAct;
import org.dromara.maxkey.provision.ProvisionMessage;
import org.dromara.maxkey.provision.ProvisionTopic;
import org.dromara.maxkey.util.DateUtils;
@@ -160,11 +160,11 @@ public class ProvisioningRunner {
}
public String getActionType(String actionType) {
if(actionType.equalsIgnoreCase(ProvisionAction.CREATE_ACTION)) {
if(actionType.equalsIgnoreCase(ProvisionAct.CREATE)) {
return "create";
}else if(actionType.equalsIgnoreCase(ProvisionAction.UPDATE_ACTION)) {
}else if(actionType.equalsIgnoreCase(ProvisionAct.UPDATE)) {
return "update";
}else if(actionType.equalsIgnoreCase(ProvisionAction.DELETE_ACTION)) {
}else if(actionType.equalsIgnoreCase(ProvisionAct.DELETE)) {
return "delete";
}
return "";
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.GroupPermissionsMapper" >
<mapper namespace="org.dromara.maxkey.persistence.mapper.AccessMapper" >
<sql id="where_statement">
<if test="id != null and id != ''">
@@ -18,7 +18,7 @@
</sql>
<!-- AppGroup -->
<select id="appsInGroup" parameterType="GroupPermissions" resultType="GroupPermissions">
<select id="appsInGroup" parameterType="Access" resultType="Access">
select
p.id,
p.groupid,
@@ -34,7 +34,7 @@
apps.vendorurl
from
mxk_apps apps,
mxk_group_permissions p,
mxk_access p,
mxk_groups r
where
apps.instid = #{instId}
@@ -49,7 +49,7 @@
<include refid="where_statement"/>
</select>
<select id="appsNotInGroup" parameterType="GroupPermissions" resultType="GroupPermissions">
<select id="appsNotInGroup" parameterType="Access" resultType="Access">
select
*
from
@@ -60,7 +60,7 @@
select
appid
from
mxk_group_permissions
mxk_access
where
groupid = #{groupId}
)
@@ -180,7 +180,7 @@
select distinct
app.*
from
mxk_apps app,mxk_group_permissions p,mxk_groups g
mxk_apps app,mxk_access p,mxk_groups g
where
app.id = p.appid
and p.groupid = g.id
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.PasswordPolicyMapper" >
<mapper namespace="org.dromara.maxkey.persistence.mapper.CnfPasswordPolicyMapper" >
</mapper>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.GroupPrivilegesMapper">
<mapper namespace="org.dromara.maxkey.persistence.mapper.PermissionMapper">
<sql id="where_statement">
<if test="id != null and id != ''">
@@ -11,11 +11,11 @@
</if>
</sql>
<select id="queryGroupPrivileges" parameterType="GroupPrivileges" resultType="GroupPrivileges">
<select id="queryGroupPrivileges" parameterType="Permission" resultType="Permission">
select
*
from
mxk_group_privileges
mxk_permission
where instid = #{instId}
and status = 1
<if test="id != null and id != ''">
@@ -31,7 +31,7 @@
</select>
<update id="deleteGroupPrivileges" parameterType="java.util.List">
update mxk_group_privileges
update mxk_permission
set status = 9
where 1 = 1 and
<foreach item="item" collection="list" open="(" separator="or" close=")">
@@ -40,7 +40,7 @@
</update>
<insert id="insertGroupPrivileges" parameterType="java.util.List">
insert into mxk_group_privileges ( id,appid,groupid,resourceid,status,instid)
insert into mxk_permission ( id,appid,groupid,resourceid,status,instid)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},#{item.appId},#{item.groupId},#{item.resourceId},#{item.status},#{item.instId})
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.PermissionRoleMapper">
<sql id="where_statement">
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name like '%${name}%'
</if>
</sql>
<select id="queryPermissionRoles" parameterType="PermissionRole" resultType="PermissionRole">
select
*
from
mxk_permission_role
where instid = #{instId}
and status = 1
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="roleId != null and roleId != ''">
and roleid = #{roleId}
</if>
<if test="appId != null and appId != ''">
and appid = #{appId}
</if>
</select>
<update id="deletePermissionRoles" parameterType="java.util.List">
update mxk_permission_role
set status = 9
where 1 = 1 and
<foreach item="item" collection="list" open="(" separator="or" close=")">
( id = #{item.id} and instid = #{item.instId} )
</foreach>
</update>
<insert id="insertPermissionRoles" parameterType="java.util.List">
insert into mxk_permission_role ( id,appid,roleid,resourceid,createdby,status,instid)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},
#{item.appId},
#{item.roleId},
#{item.resourceId},
#{item.createdBy},
#{item.status},
#{item.instId})
</foreach>
</insert>
</mapper>
@@ -0,0 +1,234 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.RoleMemberMapper">
<sql id="where_statement">
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="roleName != null and roleName != ''">
and rolename = #{roleName}
</if>
</sql>
<select id="memberInRole" parameterType="RoleMember" resultType="RoleMember">
select distinct
rm.id as id,
rm.type as type,
r.id as roleid,
r.rolename,
concat(u.displayname,'(',u.username,')') membername,
u.jobtitle,
u.gender,
u.departmentid,
u.department,
rm.createddate
from
mxk_userinfo u,
mxk_roles r,
mxk_role_member rm
where u.instid = #{instId}
and r.instid = #{instId}
and rm.instid = #{instId}
and rm.type in( 'USER','USER-DYNAMIC')
and rm.roleid = r.id
and rm.memberid = u.id
<if test="roleId != null and roleId != ''">
and rm.roleid = #{roleId}
and r.id = #{roleId}
</if>
<if test="roleName != null and roleName != ''">
and r.rolename = #{roleName}
</if>
<if test="memberName != null and memberName != ''">
and (
u.username like '%${memberName}%'
or u.displayname like '%${memberName}%'
)
</if>
</select>
<select id="memberNotInRole" parameterType="RoleMember" resultType="RoleMember">
select distinct
u.id,
u.username,
u.displayname ,
u.gender,
u.organization,
u.departmentid,
u.department,
u.jobtitle,
u.createdby
from
mxk_userinfo u
where
u.id not in(
select rm.memberid
from mxk_roles r,mxk_role_member rm
where 1 = 1
<if test="roleId != null and roleId != ''">
and rm.roleid = #{roleId}
and r.id = #{roleId}
</if>
<if test="roleName != null and roleName != ''">
and r.rolename = #{roleName}
</if>
and rm.type in( 'USER','USER-DYNAMIC')
and rm.roleid = r.id
)
<if test="username != null and username != ''">
and u.username = #{username}
</if>
<if test="displayName != null and displayName != ''">
and u.displayname like '%${displayName}%'
</if>
</select>
<select id="rolesNoMember" parameterType="RoleMember" resultType="Roles">
select distinct
r.*
from
mxk_roles r
where
r.id not in(
select
rm.roleid
from mxk_role_member rm,mxk_userinfo u
where rm.memberid = u.id
<if test="username != null and username != ''">
and u.username = #{username}
</if>
<if test="memberId != null and memberId != ''">
and rm.memberid = #{memberid}
</if>
)
<if test="roleName != null and roleName != ''">
and r.rolename = #{roleName}
</if>
</select>
<!-- ROLE_MEMBER ROLE Member-->
<select id="roleMemberInRole" parameterType="RoleMember" resultType="Roles">
select distinct
ig.*
from
mxk_roles ir,
mxk_roles r,
mxk_role_member rm
where
1 = 1
and rm.roleid = g.id
and rm.memberid = ig.id
and rm.type = 'ROLE'
<if test="roleId != null and roleId != ''">
and rm.roleid = #{roleId}
and r.id = #{roleId}
</if>
<if test="roleName != null and roleName != ''">
and r.rolename = #{roleName}
</if>
</select>
<update id="addDynamicRoleMember" parameterType="Roles" >
insert into mxk_role_member(
id,
roleid,
memberid,
type,
instid
)
select
concat('${id}_',u.id) id,
'${id}' roleid,
u.id memberid,
'USER-DYNAMIC' type,
'${instId}' instid
from mxk_userinfo u
where not exists(
select 1 from mxk_role_member rm
where rm.roleid=#{id}
and rm.memberid=u.id
and rm.type='USER-DYNAMIC'
)
<if test="filters != null and filters != ''">
and (${filters})
</if>
<if test="orgIdsList != null and orgIdsList != ''">
and u.departmentid in( ${orgIdsList})
</if>
</update>
<delete id="deleteDynamicRoleMember" parameterType="Roles" >
delete from mxk_role_member rm
where type = 'user-dynamic'
and rm.roleid=#{id}
and not exists(
select 1
from mxk_userinfo u
where 1 = 1
and u.id=rm.memberid
<if test="filters != null and filters != ''">
and (${filters})
</if>
<if test="orgIdsList != null and orgIdsList != ''">
and u.departmentid in ( ${orgIdsList})
</if>
)
</delete>
<select id="queryMemberByRoleId" parameterType="string" resultType="UserInfo">
select distinct
r.roleId,
r.roleName,
u.id,
u.username,
u.usertype,
u.windowsaccount,
u.displayname ,
u.nickname ,
u.namezhspell,
u.namezhshortspell,
u.givenname ,
u.middlename ,
u.familyname ,
u.gender,
u.authntype,
u.mobile,
u.email,
u.workemail,
u.workphonenumber,
u.employeenumber,
u.division,
u.costcenter,
u.organization,
u.departmentid,
u.department,
u.jobtitle,
u.joblevel,
rm.createddate,
u.status
from
mxk_userinfo u,
mxk_roles r,
mxk_role_member rm
where 1 = 1
and rm.roleid = #{value}
and g.id = #{value}
and rm.type in( 'USER','USER-DYNAMIC')
and rm.roleid = r.id
and rm.memberid = u.id
</select>
<delete id="deleteByRoleId" parameterType="string" >
delete from mxk_role_member rm
where rm.roleid = #{value} and rolecode != 'ROLE_ALL_USER'
</delete>
</mapper>
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.RolesMapper">
<sql id="where_statement">
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="roleName != null and roleName != ''">
and rolename like '%${roleName}%'
</if>
<if test="appId != null and appId != ''">
and appid = #{appId}
</if>
</sql>
<select id="fetchPageResults" parameterType="Roles" resultType="Roles">
select
*
from
mxk_roles
where instid = #{instId}
<include refid="where_statement"/>
</select>
<select id="queryDynamicRoles" parameterType="Roles" resultType="Roles">
select
*
from
mxk_roles
where instid = #{instId}
and category = 'dynamic'
<include refid="where_statement"/>
</select>
<update id="logisticDelete" parameterType="Roles" >
update mxk_roles set
status = '2'
where instid = #{instId}
<if test="id != null">
and id = #{id}
</if>
<if test="roleName != roleName">
and rolename = #{roleName}
</if>
</update>
<update id="logisticBatchDelete" parameterType="java.util.List">
update mxk_roles
set status='2'
where instid = #{instId}
and id in
<foreach item="item" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</update>
<select id="queryRolesByUserId" parameterType="string" resultType="Roles">
select distinct
r.*
from
mxk_userinfo u,
mxk_roles r,
mxk_role_member rm
where u.instid = #{instId}
and r.instid = #{instId}
and rm.instid = #{instId}
and rm.memberid = #{value}
and u.id = #{value}
and rm.type in( 'USER','USER-DYNAMIC')
and rm.groupid = r.id
and rm.memberid = u.id
</select>
</mapper>
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.maxkey.persistence.mapper.PermissionRoleMapper">
<sql id="where_statement">
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name like '%${name}%'
</if>
</sql>
<select id="queryPermissionRoles" parameterType="PermissionRole" resultType="PermissionRole">
select
*
from
mxk_permission_role
where instid = #{instId}
and status = 1
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="roleId != null and roleId != ''">
and roleid = #{roleId}
</if>
<if test="appId != null and appId != ''">
and appid = #{appId}
</if>
</select>
<update id="deletePermissionRoles" parameterType="java.util.List">
update mxk_permission_role
set status = 9
where 1 = 1 and
<foreach item="item" collection="list" open="(" separator="or" close=")">
( id = #{item.id} and instid = #{item.instId} )
</foreach>
</update>
<insert id="insertPermissionRoles" parameterType="java.util.List">
insert into mxk_permission_role ( id,appid,roleid,resourceid,createdby,status,instid)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},
#{item.appId},
#{item.roleId},
#{item.resourceId},
#{item.createdBy},
#{item.status},
#{item.instId})
</foreach>
</insert>
</mapper>
@@ -54,7 +54,7 @@ public class FormBasedDetailsServiceTest {
service.insert(formBasedDetails);
Thread.sleep(1000);
service.remove(formBasedDetails.getId());
service.delete(formBasedDetails.getId());
}
@@ -74,7 +74,7 @@ public class FormBasedDetailsServiceTest {
_logger.info("remove...");
AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails();
formBasedDetails.setId("921d3377-937a-4578-b1e2-92fb23b5e512");
service.remove(formBasedDetails.getId());
service.delete(formBasedDetails.getId());
}