Search in sources :

Example 46 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method populateOwner.

// TODO: we may need to refactor once ControlledEntityResponse and
// ControlledEntity id to uuid conversion are all done.
// currently code is scattered in
private void populateOwner(final ControlledEntityResponse response, final ControlledEntity object) {
    final Account account = ApiDBUtils.findAccountById(object.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        // find the project
        final Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
        if (project != null) {
            response.setProjectId(project.getUuid());
            response.setProjectName(project.getName());
        }
    } else {
        response.setAccountName(account.getAccountName());
    }
    final Domain domain = ApiDBUtils.findDomainById(object.getDomainId());
    response.setDomainId(domain.getUuid());
    response.setDomainName(domain.getName());
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) Project(com.cloud.projects.Project) Domain(com.cloud.legacymodel.domain.Domain)

Example 47 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class ApiServer method loginUser.

@Override
public ResponseObject loginUser(final HttpSession session, final String username, final String password, Long domainId, final String domainPath, final InetAddress loginIpAddress, final Map<String, Object[]> requestParameters) throws CloudAuthenticationException {
    // we will default to ROOT
    if (domainId == null) {
        if (domainPath == null || domainPath.trim().length() == 0) {
            domainId = Domain.ROOT_DOMAIN;
        } else {
            final Domain domainObj = _domainMgr.findDomainByPath(domainPath);
            if (domainObj != null) {
                domainId = domainObj.getId();
            } else {
                // if an unknown path is passed in, fail the login call
                throw new CloudAuthenticationException("Unable to find the domain from the path " + domainPath);
            }
        }
    }
    final UserAccount userAcct = _accountMgr.authenticateUser(username, password, domainId, loginIpAddress, requestParameters);
    if (userAcct != null) {
        final String timezone = userAcct.getTimezone();
        float offsetInHrs = 0f;
        if (timezone != null) {
            final TimeZone t = TimeZone.getTimeZone(timezone);
            s_logger.info("Current user logged in under " + timezone + " timezone");
            final java.util.Date date = new java.util.Date();
            final long longDate = date.getTime();
            final float offsetInMs = (t.getOffset(longDate));
            offsetInHrs = offsetInMs / (1000 * 60 * 60);
            s_logger.info("Timezone offset from UTC is: " + offsetInHrs);
        }
        final Account account = _accountMgr.getAccount(userAcct.getAccountId());
        // set the userId and account object for everyone
        session.setAttribute("userid", userAcct.getId());
        final UserVO user = (UserVO) _accountMgr.getActiveUser(userAcct.getId());
        if (user.getUuid() != null) {
            session.setAttribute("user_UUID", user.getUuid());
        }
        session.setAttribute("username", userAcct.getUsername());
        session.setAttribute("firstname", userAcct.getFirstname());
        session.setAttribute("lastname", userAcct.getLastname());
        session.setAttribute("accountobj", account);
        session.setAttribute("account", account.getAccountName());
        session.setAttribute("domainid", account.getDomainId());
        final DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId());
        if (domain.getUuid() != null) {
            session.setAttribute("domain_UUID", domain.getUuid());
        }
        if (domain.getName() != null) {
            session.setAttribute(ApiConstants.DOMAIN_NAME, domain.getName());
        }
        session.setAttribute("type", Short.valueOf(account.getType()).toString());
        session.setAttribute("registrationtoken", userAcct.getRegistrationToken());
        session.setAttribute("registered", Boolean.toString(userAcct.isRegistered()));
        if (timezone != null) {
            session.setAttribute("timezone", timezone);
            session.setAttribute("timezoneoffset", Float.valueOf(offsetInHrs).toString());
        }
        // (bug 5483) generate a session key that the user must submit on every request to prevent CSRF, add that
        // to the login response so that session-based authenticators know to send the key back
        final SecureRandom sesssionKeyRandom = new SecureRandom();
        final byte[] sessionKeyBytes = new byte[20];
        sesssionKeyRandom.nextBytes(sessionKeyBytes);
        final String sessionKey = Base64.encodeBase64URLSafeString(sessionKeyBytes);
        session.setAttribute(ApiConstants.SESSIONKEY, sessionKey);
        return createLoginResponse(session);
    }
    throw new CloudAuthenticationException("Failed to authenticate user " + username + " in domain " + domainId + "; please provide valid credentials");
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) CloudAuthenticationException(com.cloud.legacymodel.exceptions.CloudAuthenticationException) Date(java.util.Date) SecureRandom(java.security.SecureRandom) Date(java.util.Date) ResponseDate(org.apache.http.protocol.ResponseDate) DomainVO(com.cloud.domain.DomainVO) TimeZone(java.util.TimeZone) UserVO(com.cloud.user.UserVO) Domain(com.cloud.legacymodel.domain.Domain) UserAccount(com.cloud.legacymodel.user.UserAccount)

Example 48 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method listDomainSpecificNetworksByDomainPath.

private List<NetworkVO> listDomainSpecificNetworksByDomainPath(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final String path, final boolean isRecursive) {
    Set<Long> allowedDomains = new HashSet<>();
    if (path != null) {
        if (isRecursive) {
            allowedDomains = _domainMgr.getDomainChildrenIds(path);
        } else {
            final Domain domain = _domainDao.findDomainByPath(path);
            allowedDomains.add(domain.getId());
        }
    }
    final List<Long> networkIds = new ArrayList<>();
    final List<NetworkDomainVO> maps = _networkDomainDao.listDomainNetworkMapByDomain(allowedDomains.toArray());
    for (final NetworkDomainVO map : maps) {
        networkIds.add(map.getNetworkId());
    }
    if (!networkIds.isEmpty()) {
        final SearchCriteria<NetworkVO> domainSC = _networksDao.createSearchCriteria();
        domainSC.addAnd("id", SearchCriteria.Op.IN, networkIds.toArray());
        domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
        sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
        return _networksDao.search(sc, searchFilter);
    } else {
        return new ArrayList<>();
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) Domain(com.cloud.legacymodel.domain.Domain) HashSet(java.util.HashSet)

Example 49 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method createUserAccount.

@Override
@DB
@ActionEvents({ @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"), @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") })
public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, final short accountType, Long domainId, final String networkDomain, final Map<String, String> details, final String accountUUID, final String userUUID, final User.Source source) {
    if (accountName == null) {
        accountName = userName;
    }
    if (domainId == null) {
        domainId = Domain.ROOT_DOMAIN;
    }
    if (StringUtils.isEmpty(userName)) {
        throw new InvalidParameterValueException("Username is empty");
    }
    if (StringUtils.isEmpty(firstName)) {
        throw new InvalidParameterValueException("Firstname is empty");
    }
    if (StringUtils.isEmpty(lastName)) {
        throw new InvalidParameterValueException("Lastname is empty");
    }
    // Validate domain
    final Domain domain = _domainMgr.getDomain(domainId);
    if (domain == null) {
        throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account");
    }
    // Check permissions
    checkAccess(CallContext.current().getCallingAccount(), domain);
    if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) {
        throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId);
    }
    if (networkDomain != null && networkDomain.length() > 0) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
    }
    final String accountNameFinal = accountName;
    final Long domainIdFinal = domainId;
    final String accountUUIDFinal = accountUUID;
    final Pair<Long, Account> pair = Transaction.execute(new TransactionCallback<Pair<Long, Account>>() {

        @Override
        public Pair<Long, Account> doInTransaction(final TransactionStatus status) {
            // create account
            String accountUUID = accountUUIDFinal;
            if (accountUUID == null) {
                accountUUID = UUID.randomUUID().toString();
            }
            final AccountVO account = createAccount(accountNameFinal, accountType, domainIdFinal, networkDomain, details, accountUUID);
            final long accountId = account.getId();
            // create the first user for the account
            final UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID, source);
            if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
                // set registration token
                final byte[] bytes = (domainIdFinal + accountNameFinal + userName + System.currentTimeMillis()).getBytes();
                final String registrationToken = UUID.nameUUIDFromBytes(bytes).toString();
                user.setRegistrationToken(registrationToken);
            }
            return new Pair<>(user.getId(), account);
        }
    });
    final long userId = pair.first();
    final Account account = pair.second();
    // create correct account and group association based on accountType
    if (accountType != Account.ACCOUNT_TYPE_PROJECT) {
        final Map<Long, Long> accountGroupMap = new HashMap<>();
        accountGroupMap.put(account.getId(), new Long(accountType + 1));
        _messageBus.publish(_name, MESSAGE_ADD_ACCOUNT_EVENT, PublishScope.LOCAL, accountGroupMap);
    }
    CallContext.current().putContextParameter(Account.class, account.getUuid());
    // check success
    return _userAccountDao.findById(userId);
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) HashMap(java.util.HashMap) TransactionStatus(com.cloud.utils.db.TransactionStatus) VpnUserVO(com.cloud.network.VpnUserVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Domain(com.cloud.legacymodel.domain.Domain) Pair(com.cloud.legacymodel.utils.Pair) DB(com.cloud.utils.db.DB) ActionEvents(com.cloud.event.ActionEvents)

Example 50 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method createUser.

@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User")
public UserVO createUser(final String userName, final String password, final String firstName, final String lastName, final String email, final String timeZone, final String accountName, Long domainId, final String userUUID, final User.Source source) {
    // default domain to ROOT if not specified
    if (domainId == null) {
        domainId = Domain.ROOT_DOMAIN;
    }
    final Domain domain = _domainMgr.getDomain(domainId);
    if (domain == null) {
        throw new CloudRuntimeException("The domain " + domainId + " does not exist; unable to create user");
    } else if (domain.getState().equals(Domain.State.Inactive)) {
        throw new CloudRuntimeException("The user cannot be created as domain " + domain.getName() + " is being deleted");
    }
    checkAccess(CallContext.current().getCallingAccount(), domain);
    final Account account = _accountDao.findEnabledAccount(accountName, domainId);
    if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user");
    }
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new PermissionDeniedException("Account id : " + account.getId() + " is a system account, can't add a user to it");
    }
    if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) {
        throw new CloudRuntimeException("The user " + userName + " already exists in domain " + domainId);
    }
    final UserVO user;
    user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone, userUUID, source);
    return user;
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) VpnUserVO(com.cloud.network.VpnUserVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) Domain(com.cloud.legacymodel.domain.Domain) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

Domain (com.cloud.legacymodel.domain.Domain)55 Account (com.cloud.legacymodel.user.Account)37 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)20 UserAccount (com.cloud.legacymodel.user.UserAccount)19 ArrayList (java.util.ArrayList)16 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)11 Project (com.cloud.projects.Project)11 DomainVO (com.cloud.domain.DomainVO)10 Network (com.cloud.legacymodel.network.Network)10 DomainResponse (com.cloud.api.response.DomainResponse)8 Pair (com.cloud.legacymodel.utils.Pair)7 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)7 HostVO (com.cloud.host.HostVO)6 List (java.util.List)6 Filter (com.cloud.utils.db.Filter)5 HashSet (java.util.HashSet)5 Test (org.junit.Test)5 AffinityGroupResponse (com.cloud.affinity.AffinityGroupResponse)4 CloudAuthenticationException (com.cloud.legacymodel.exceptions.CloudAuthenticationException)4 NetworkVO (com.cloud.network.dao.NetworkVO)4