Search in sources :

Example 31 with ZLdapContext

use of com.zimbra.cs.ldap.ZLdapContext in project zm-mailbox by Zimbra.

the class LdapProvisioning method createAccount.

private Account createAccount(String emailAddress, String password, Map<String, Object> acctAttrs, SpecialAttrs specialAttrs, String[] additionalObjectClasses, boolean restoring, Map<String, Object> origAttrs) throws ServiceException {
    String uuid = specialAttrs.getZimbraId();
    String baseDn = specialAttrs.getLdapBaseDn();
    emailAddress = emailAddress.toLowerCase().trim();
    String[] parts = emailAddress.split("@");
    if (parts.length != 2) {
        throw ServiceException.INVALID_REQUEST("must be valid email address: " + emailAddress, null);
    }
    String localPart = parts[0];
    String domain = parts[1];
    domain = IDNUtil.toAsciiDomainName(domain);
    emailAddress = localPart + "@" + domain;
    validEmailAddress(emailAddress);
    if (restoring) {
        validate(ProvisioningValidator.CREATE_ACCOUNT, emailAddress, additionalObjectClasses, origAttrs);
        validate(ProvisioningValidator.CREATE_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE, emailAddress, origAttrs);
    } else {
        validate(ProvisioningValidator.CREATE_ACCOUNT, emailAddress, additionalObjectClasses, acctAttrs);
        validate(ProvisioningValidator.CREATE_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE, emailAddress, acctAttrs);
    }
    if (acctAttrs == null) {
        acctAttrs = new HashMap<String, Object>();
    }
    CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
    callbackContext.setCreatingEntryName(emailAddress);
    AttributeManager.getInstance().preModify(acctAttrs, null, callbackContext, true);
    Account acct = null;
    String dn = null;
    ZLdapContext zlc = null;
    try {
        zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_ACCOUNT);
        Domain d = getDomainByAsciiName(domain, zlc);
        if (d == null) {
            throw AccountServiceException.NO_SUCH_DOMAIN(domain);
        }
        if (!d.isLocal()) {
            throw ServiceException.INVALID_REQUEST("domain type must be local", null);
        }
        ZMutableEntry entry = LdapClient.createMutableEntry();
        entry.mapToAttrs(acctAttrs);
        for (int i = 0; i < sInvalidAccountCreateModifyAttrs.length; i++) {
            String a = sInvalidAccountCreateModifyAttrs[i];
            if (entry.hasAttribute(a))
                throw ServiceException.INVALID_REQUEST("invalid attribute for CreateAccount: " + a, null);
        }
        Set<String> ocs;
        if (additionalObjectClasses == null) {
            // We are creating a pure account object, get all object classes for account.
            //
            // If restoring, only add zimbra default object classes, do not add extra
            // ones configured.  After createAccount, the restore code will issue a
            // modifyAttrs call and all object classes in the backed up account will be
            // in the attr map passed to modifyAttrs.
            //
            ocs = LdapObjectClass.getAccountObjectClasses(this, restoring);
        } else {
            // We are creating a "subclass" of account (e.g. calendar resource), get just the
            // zimbra default object classes for account, then add extra object classes needed
            // by the subclass.  All object classes needed by the subclass (calendar resource)
            // were figured out in the createCalendarResource method: including the zimbra
            // default (zimbracalendarResource) and any extra ones configured via
            // globalconfig.zimbraCalendarResourceExtraObjectClass.
            //
            // It doesn't matter if the additionalObjectClasses already contains object classes
            // added by the getAccountObjectClasses(this, true).  When additional object classes
            // are added to the set, duplicated once will only appear once.
            //
            //
            // The "restoring" flag is ignored in this path.
            // When restoring a calendar a resource, the restoring code:
            //     - always calls createAccount, not createCalendarResource
            //     - always pass null for additionalObjectClasses
            //     - like restoring an account, it will call modifyAttrs after the
            //       entry is created, any object classes in the backed up data
            //       will be in the attr map passed to modifyAttrs.
            ocs = LdapObjectClass.getAccountObjectClasses(this, true);
            for (int i = 0; i < additionalObjectClasses.length; i++) ocs.add(additionalObjectClasses[i]);
        }
        boolean skipCountingLicenseQuota = false;
        /* bug 48226
             *
             * Check if any of the OCs in the backup is a structural OC that subclasses
             * our default OC (defined in ZIMBRA_DEFAULT_PERSON_OC).
             * If so, add that OC now while creating the account, because it cannot be modified later.
             */
        if (restoring && origAttrs != null) {
            Object ocsInBackupObj = origAttrs.get(A_objectClass);
            String[] ocsInBackup = StringUtil.toStringArray(ocsInBackupObj);
            String mostSpecificOC = LdapObjectClassHierarchy.getMostSpecificOC(this, ocsInBackup, LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC);
            if (!LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC.equalsIgnoreCase(mostSpecificOC)) {
                ocs.add(mostSpecificOC);
            }
            //calendar resource doesn't count against license quota
            if (origAttrs.get(A_zimbraCalResType) != null) {
                skipCountingLicenseQuota = true;
            }
            if (origAttrs.get(A_zimbraIsSystemResource) != null) {
                entry.setAttr(A_zimbraIsSystemResource, "TRUE");
                skipCountingLicenseQuota = true;
            }
            if (origAttrs.get(A_zimbraIsExternalVirtualAccount) != null) {
                entry.setAttr(A_zimbraIsExternalVirtualAccount, "TRUE");
                skipCountingLicenseQuota = true;
            }
        }
        entry.addAttr(A_objectClass, ocs);
        String zimbraIdStr;
        if (uuid == null) {
            zimbraIdStr = LdapUtil.generateUUID();
        } else {
            zimbraIdStr = uuid;
        }
        entry.setAttr(A_zimbraId, zimbraIdStr);
        entry.setAttr(A_zimbraCreateTimestamp, LdapDateUtil.toGeneralizedTime(new Date()));
        // default account status is active
        if (!entry.hasAttribute(Provisioning.A_zimbraAccountStatus)) {
            entry.setAttr(A_zimbraAccountStatus, Provisioning.ACCOUNT_STATUS_ACTIVE);
        }
        Cos cos = null;
        String cosId = entry.getAttrString(Provisioning.A_zimbraCOSId);
        if (cosId != null) {
            cos = lookupCos(cosId, zlc);
            if (!cos.getId().equals(cosId)) {
                cosId = cos.getId();
            }
            entry.setAttr(Provisioning.A_zimbraCOSId, cosId);
        } else {
            String domainCosId = domain != null ? isExternalVirtualAccount(entry) ? d.getDomainDefaultExternalUserCOSId() : d.getDomainDefaultCOSId() : null;
            if (domainCosId != null) {
                cos = get(Key.CosBy.id, domainCosId);
            }
            if (cos == null) {
                cos = getCosByName(isExternalVirtualAccount(entry) ? Provisioning.DEFAULT_EXTERNAL_COS_NAME : Provisioning.DEFAULT_COS_NAME, zlc);
            }
        }
        boolean hasMailTransport = entry.hasAttribute(Provisioning.A_zimbraMailTransport);
        // zimbraMailHost(and zimbraMailTransport) if it is not specified
        if (!hasMailTransport) {
            addMailHost(entry, cos, true);
        }
        // set all the mail-related attrs if zimbraMailHost or zimbraMailTransport was specified
        if (entry.hasAttribute(Provisioning.A_zimbraMailHost) || entry.hasAttribute(Provisioning.A_zimbraMailTransport)) {
            // default mail status is enabled
            if (!entry.hasAttribute(Provisioning.A_zimbraMailStatus)) {
                entry.setAttr(A_zimbraMailStatus, MAIL_STATUS_ENABLED);
            }
            // default account mail delivery address is email address
            if (!entry.hasAttribute(Provisioning.A_zimbraMailDeliveryAddress)) {
                entry.setAttr(A_zimbraMailDeliveryAddress, emailAddress);
            }
        } else {
            throw ServiceException.INVALID_REQUEST("missing " + Provisioning.A_zimbraMailHost + " or " + Provisioning.A_zimbraMailTransport + " for CreateAccount: " + emailAddress, null);
        }
        // amivisAccount requires the mail attr, so we always add it
        entry.setAttr(A_mail, emailAddress);
        // required for ZIMBRA_DEFAULT_PERSON_OC class
        if (!entry.hasAttribute(Provisioning.A_cn)) {
            String displayName = entry.getAttrString(Provisioning.A_displayName);
            if (displayName != null) {
                entry.setAttr(A_cn, displayName);
            } else {
                entry.setAttr(A_cn, localPart);
            }
        }
        // required for ZIMBRA_DEFAULT_PERSON_OC class
        if (!entry.hasAttribute(Provisioning.A_sn)) {
            entry.setAttr(A_sn, localPart);
        }
        entry.setAttr(A_uid, localPart);
        String entryPassword = entry.getAttrString(Provisioning.A_userPassword);
        if (entryPassword != null) {
            //password is a hash i.e. from autoprov; do not set with modify password
            password = null;
        } else if (password != null) {
            //user entered
            checkPasswordStrength(password, null, cos, entry);
        }
        entry.setAttr(Provisioning.A_zimbraPasswordModifiedTime, LdapDateUtil.toGeneralizedTime(new Date()));
        String ucPassword = entry.getAttrString(Provisioning.A_zimbraUCPassword);
        if (ucPassword != null) {
            String encryptedPassword = Account.encrypytUCPassword(entry.getAttrString(Provisioning.A_zimbraId), ucPassword);
            entry.setAttr(Provisioning.A_zimbraUCPassword, encryptedPassword);
        }
        dn = mDIT.accountDNCreate(baseDn, entry.getAttributes(), localPart, domain);
        entry.setDN(dn);
        zlc.createEntry(entry);
        acct = getAccountById(zimbraIdStr, zlc, true);
        if (acct == null) {
            throw ServiceException.FAILURE("unable to get account after creating LDAP account entry: " + emailAddress + ", check ldap log for possible error", null);
        }
        AttributeManager.getInstance().postModify(acctAttrs, acct, callbackContext);
        removeExternalAddrsFromAllDynamicGroups(acct.getAllAddrsSet(), zlc);
        validate(ProvisioningValidator.CREATE_ACCOUNT_SUCCEEDED, emailAddress, acct, skipCountingLicenseQuota);
        if (password != null) {
            setLdapPassword(acct, zlc, password);
        }
        return acct;
    } catch (LdapEntryAlreadyExistException e) {
        throw AccountServiceException.ACCOUNT_EXISTS(emailAddress, dn, e);
    } catch (LdapException e) {
        throw e;
    } catch (AccountServiceException e) {
        throw e;
    } catch (ServiceException e) {
        throw ServiceException.FAILURE("unable to create account: " + emailAddress, e);
    } finally {
        LdapClient.closeContext(zlc);
        if (!restoring && acct != null) {
            for (PostCreateAccountListener listener : ProvisioningExt.getPostCreateAccountListeners()) {
                if (listener.enabled()) {
                    listener.handle(acct);
                }
            }
        }
    }
}
Also used : Account(com.zimbra.cs.account.Account) GuestAccount(com.zimbra.cs.account.GuestAccount) LdapAccount(com.zimbra.cs.account.ldap.entry.LdapAccount) ZMutableEntry(com.zimbra.cs.ldap.ZMutableEntry) LdapEntryAlreadyExistException(com.zimbra.cs.ldap.LdapException.LdapEntryAlreadyExistException) ZLdapContext(com.zimbra.cs.ldap.ZLdapContext) LdapCos(com.zimbra.cs.account.ldap.entry.LdapCos) Cos(com.zimbra.cs.account.Cos) Date(java.util.Date) AccountServiceException(com.zimbra.cs.account.AccountServiceException) AccountServiceException(com.zimbra.cs.account.AccountServiceException) AuthFailedServiceException(com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException) ServiceException(com.zimbra.common.service.ServiceException) CallbackContext(com.zimbra.cs.account.callback.CallbackContext) PostCreateAccountListener(com.zimbra.cs.account.ProvisioningExt.PostCreateAccountListener) LdapDomain(com.zimbra.cs.account.ldap.entry.LdapDomain) Domain(com.zimbra.cs.account.Domain) LdapException(com.zimbra.cs.ldap.LdapException)

Example 32 with ZLdapContext

use of com.zimbra.cs.ldap.ZLdapContext in project zm-mailbox by Zimbra.

the class LdapProvisioning method removeDynamicGroupMembers.

private void removeDynamicGroupMembers(LdapDynamicGroup group, String[] members, boolean externalOnly) throws ServiceException {
    if (group.isMembershipDefinedByCustomURL()) {
        throw ServiceException.INVALID_REQUEST(String.format("cannot remove members from dynamic group '%s' with custom memberURL", group.getName()), null);
    }
    String groupId = group.getId();
    List<Account> accts = new ArrayList<Account>();
    List<String> externalAddrs = new ArrayList<String>();
    HashSet<String> failed = new HashSet<String>();
    // check for errors, and put valid accts to the queue
    for (String member : members) {
        String memberName = member.toLowerCase();
        boolean isBadAddr = false;
        try {
            memberName = IDNUtil.toAsciiEmail(memberName);
        } catch (ServiceException e) {
            // if the addr is not a valid email address, maybe they want to
            // remove a bogus addr that somehow got in, just let it through.
            memberName = member;
            isBadAddr = true;
        }
        // always add all addrs to "externalAddrs".
        externalAddrs.add(memberName);
        if (!externalOnly) {
            Account acct = isBadAddr ? null : get(AccountBy.name, member);
            if (acct != null) {
                Set<String> memberOf = acct.getMultiAttrSet(Provisioning.A_zimbraMemberOf);
                if (memberOf.contains(groupId)) {
                    accts.add(acct);
                } else {
                    // else the addr is not in the group, throw exception
                    failed.add(memberName);
                }
            }
        }
    }
    if (!failed.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iter = failed.iterator();
        while (true) {
            sb.append(iter.next());
            if (!iter.hasNext())
                break;
            sb.append(",");
        }
        throw AccountServiceException.NO_SUCH_MEMBER(group.getName(), sb.toString());
    }
    ZLdapContext zlc = null;
    try {
        zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.REMOVE_GROUP_MEMBER);
        /*
             * remove internal members
             */
        for (Account acct : accts) {
            Map<String, Object> attrs = new HashMap<String, Object>();
            attrs.put("-" + Provisioning.A_zimbraMemberOf, groupId);
            modifyLdapAttrs(acct, zlc, attrs);
            clearUpwardMembershipCache(acct);
        }
        /*
             * remove external members on the static unit
             */
        LdapDynamicGroup.StaticUnit staticUnit = group.getStaticUnit();
        Set<String> existingAddrs = staticUnit.getMembersSet();
        List<String> addrsToRemove = Lists.newArrayList();
        for (String addr : externalAddrs) {
            if (existingAddrs.contains(addr)) {
                addrsToRemove.add(addr);
            }
        }
        if (!addrsToRemove.isEmpty()) {
            Map<String, String[]> attrs = new HashMap<String, String[]>();
            attrs.put("-" + LdapDynamicGroup.StaticUnit.MEMBER_ATTR, addrsToRemove.toArray(new String[addrsToRemove.size()]));
            modifyLdapAttrs(staticUnit, zlc, attrs);
        }
    } finally {
        LdapClient.closeContext(zlc);
    }
    PermissionCache.invalidateCache();
    cleanGroupMembersCache(group);
}
Also used : Account(com.zimbra.cs.account.Account) GuestAccount(com.zimbra.cs.account.GuestAccount) LdapAccount(com.zimbra.cs.account.ldap.entry.LdapAccount) ZLdapContext(com.zimbra.cs.ldap.ZLdapContext) HashMap(java.util.HashMap) LdapDynamicGroup(com.zimbra.cs.account.ldap.entry.LdapDynamicGroup) ArrayList(java.util.ArrayList) AccountServiceException(com.zimbra.cs.account.AccountServiceException) AuthFailedServiceException(com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException) ServiceException(com.zimbra.common.service.ServiceException) HashSet(java.util.HashSet)

Example 33 with ZLdapContext

use of com.zimbra.cs.ldap.ZLdapContext in project zm-mailbox by Zimbra.

the class ZLdapHelper method searchForEntry.

@Override
@TODOEXCEPTIONMAPPING
public ZSearchResultEntry searchForEntry(String base, ZLdapFilter filter, ZLdapContext initZlc, boolean useMaster, String[] returnAttrs) throws LdapMultipleEntriesMatchedException, ServiceException {
    ZLdapContext zlc = initZlc;
    try {
        if (zlc == null) {
            zlc = LdapClient.getContext(LdapServerType.get(useMaster), LdapUsage.SEARCH);
        }
        ZSearchControls sc = (returnAttrs == null) ? ZSearchControls.SEARCH_CTLS_SUBTREE() : ZSearchControls.createSearchControls(ZSearchScope.SEARCH_SCOPE_SUBTREE, ZSearchControls.SIZE_UNLIMITED, returnAttrs);
        ZSearchResultEnumeration ne = zlc.searchDir(base, filter, sc);
        if (ne.hasMore()) {
            ZSearchResultEntry sr = ne.next();
            if (ne.hasMore()) {
                String dups = LdapUtil.formatMultipleMatchedEntries(sr, ne);
                throw LdapException.MULTIPLE_ENTRIES_MATCHED(base, filter.toFilterString(), dups);
            }
            ne.close();
            return sr;
        }
    /*  all callsites with the following @TODOEXCEPTIONMAPPING pattern can have ease of mind now and remove the
         * TODOEXCEPTIONMAPPING annotation
         *
        } catch (NameNotFoundException e) {
            return null;
        } catch (InvalidNameException e) {
            return null;
        } catch (NamingException e) {
            throw ServiceException.FAILURE("unable to lookup account via query: "+query+" message: "+e.getMessage(), e);
        */
    } finally {
        if (initZlc == null)
            LdapClient.closeContext(zlc);
    }
    return null;
}
Also used : ZSearchControls(com.zimbra.cs.ldap.ZSearchControls) ZLdapContext(com.zimbra.cs.ldap.ZLdapContext) ZSearchResultEnumeration(com.zimbra.cs.ldap.ZSearchResultEnumeration) ZSearchResultEntry(com.zimbra.cs.ldap.ZSearchResultEntry) TODOEXCEPTIONMAPPING(com.zimbra.cs.ldap.LdapTODO.TODOEXCEPTIONMAPPING)

Example 34 with ZLdapContext

use of com.zimbra.cs.ldap.ZLdapContext in project zm-mailbox by Zimbra.

the class ZLdapHelper method searchLdap.

@Override
public void searchLdap(ILdapContext ldapContext, SearchLdapOptions searchOptions) throws ServiceException {
    ZLdapContext zlc = LdapClient.toZLdapContext(getProv(), ldapContext);
    zlc.searchPaged(searchOptions);
}
Also used : ZLdapContext(com.zimbra.cs.ldap.ZLdapContext)

Example 35 with ZLdapContext

use of com.zimbra.cs.ldap.ZLdapContext in project zm-mailbox by Zimbra.

the class LdapDynamicGroup method updateGroupMembershipForCustomDynamicGroups.

public static GroupMembership updateGroupMembershipForCustomDynamicGroups(LdapProvisioning prov, GroupMembership membership, Account acct, Domain domain, boolean adminGroupsOnly) throws ServiceException {
    String acctDN = prov.getDNforAccount(acct, null, false);
    if (acctDN == null) {
        return membership;
    }
    ZLdapFilter filter = ZLdapFilterFactory.getInstance().allDynamicGroups();
    ZLdapContext zlcCompare = null;
    try {
        zlcCompare = LdapClient.getContext(LdapServerType.get(false), LdapUsage.COMPARE);
        BySearchResultEntrySearcher searcher = new BySearchResultEntrySearcher(prov, (ZLdapContext) null, domain, BASIC_ATTRS, new GroupMembershipUpdator(prov, zlcCompare, acctDN, membership, adminGroupsOnly, true, false));
        searcher.doSearch(filter, DYNAMIC_GROUPS_TYPE);
    } finally {
        LdapClient.closeContext(zlcCompare);
    }
    return membership;
}
Also used : ZLdapFilter(com.zimbra.cs.ldap.ZLdapFilter) ZLdapContext(com.zimbra.cs.ldap.ZLdapContext) BySearchResultEntrySearcher(com.zimbra.cs.account.ldap.BySearchResultEntrySearcher)

Aggregations

ZLdapContext (com.zimbra.cs.ldap.ZLdapContext)112 ServiceException (com.zimbra.common.service.ServiceException)51 AccountServiceException (com.zimbra.cs.account.AccountServiceException)48 AuthFailedServiceException (com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException)46 LdapEntryAlreadyExistException (com.zimbra.cs.ldap.LdapException.LdapEntryAlreadyExistException)21 LdapException (com.zimbra.cs.ldap.LdapException)20 ZMutableEntry (com.zimbra.cs.ldap.ZMutableEntry)18 Domain (com.zimbra.cs.account.Domain)17 CallbackContext (com.zimbra.cs.account.callback.CallbackContext)14 Date (java.util.Date)14 LdapDomain (com.zimbra.cs.account.ldap.entry.LdapDomain)12 HashMap (java.util.HashMap)12 LdapEntry (com.zimbra.cs.account.ldap.entry.LdapEntry)11 SearchLdapOptions (com.zimbra.cs.ldap.SearchLdapOptions)11 Account (com.zimbra.cs.account.Account)9 LdapDynamicGroup (com.zimbra.cs.account.ldap.entry.LdapDynamicGroup)8 ZLdapFilter (com.zimbra.cs.ldap.ZLdapFilter)8 GuestAccount (com.zimbra.cs.account.GuestAccount)7 LdapAccount (com.zimbra.cs.account.ldap.entry.LdapAccount)7 ZSearchResultEntry (com.zimbra.cs.ldap.ZSearchResultEntry)7