Search in sources :

Example 16 with UserAccount

use of com.cloud.legacymodel.user.UserAccount 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 17 with UserAccount

use of com.cloud.legacymodel.user.UserAccount in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method getUserAccount.

private UserAccount getUserAccount(final String username, final String password, final Long domainId, final Map<String, Object[]> requestParameters) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Attempting to log in user: " + username + " in domain " + domainId);
    }
    UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId);
    boolean authenticated = false;
    final HashSet<ActionOnFailedAuthentication> actionsOnFailedAuthenticaion = new HashSet<>();
    final User.Source userSource = userAccount != null ? userAccount.getSource() : User.Source.UNKNOWN;
    for (final UserAuthenticator authenticator : _userAuthenticators) {
        if (userSource != User.Source.UNKNOWN) {
            if (!authenticator.getName().equalsIgnoreCase(userSource.name())) {
                continue;
            }
        }
        final Pair<Boolean, ActionOnFailedAuthentication> result = authenticator.authenticate(username, password, domainId, requestParameters);
        if (result.first()) {
            authenticated = true;
            break;
        } else if (result.second() != null) {
            actionsOnFailedAuthenticaion.add(result.second());
        }
    }
    final boolean updateIncorrectLoginCount = actionsOnFailedAuthenticaion.contains(ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT);
    if (authenticated) {
        final Domain domain = _domainMgr.getDomain(domainId);
        String domainName = null;
        if (domain != null) {
            domainName = domain.getName();
        }
        userAccount = _userAccountDao.getUserAccount(username, domainId);
        if (!userAccount.getState().equalsIgnoreCase(Account.State.enabled.toString()) || !userAccount.getAccountState().equalsIgnoreCase(Account.State.enabled.toString())) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)");
            }
            throw new CloudAuthenticationException("User " + username + " (or their account) in domain " + domainName + " is disabled/locked. Please contact the " + "administrator.");
        }
        // Whenever the user is able to log in successfully, reset the login attempts to zero
        if (!isInternalAccount(userAccount.getId())) {
            updateLoginAttempts(userAccount.getId(), 0, false);
        }
        return userAccount;
    } else {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to authenticate user with username " + username + " in domain " + domainId);
        }
        if (userAccount == null) {
            s_logger.warn("Unable to find an user with username " + username + " in domain " + domainId);
            return null;
        }
        if (userAccount.getState().equalsIgnoreCase(Account.State.enabled.toString())) {
            if (!isInternalAccount(userAccount.getId())) {
                // Internal accounts are not disabled
                final int attemptsMade = userAccount.getLoginAttempts() + 1;
                if (updateIncorrectLoginCount) {
                    if (attemptsMade < _allowedLoginAttempts) {
                        updateLoginAttempts(userAccount.getId(), attemptsMade, false);
                        s_logger.warn("Login attempt failed. You have " + (_allowedLoginAttempts - attemptsMade) + " attempt(s) remaining");
                    } else {
                        updateLoginAttempts(userAccount.getId(), _allowedLoginAttempts, true);
                        s_logger.warn("User " + userAccount.getUsername() + " has been disabled due to multiple failed login attempts." + " Please contact admin.");
                    }
                }
            }
        } else {
            s_logger.info("User " + userAccount.getUsername() + " is disabled/locked");
        }
        return null;
    }
}
Also used : User(com.cloud.legacymodel.user.User) CloudAuthenticationException(com.cloud.legacymodel.exceptions.CloudAuthenticationException) UserAuthenticator(com.cloud.server.auth.UserAuthenticator) ActionOnFailedAuthentication(com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication) Domain(com.cloud.legacymodel.domain.Domain) UserAccount(com.cloud.legacymodel.user.UserAccount) HashSet(java.util.HashSet)

Example 18 with UserAccount

use of com.cloud.legacymodel.user.UserAccount in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method enableUser.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User")
public UserAccount enableUser(final long userId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Check if user exists in the system
    final User user = _userDao.findById(userId);
    if (user == null || user.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    final Account account = _accountDao.findById(user.getAccountId());
    if (account == null) {
        throw new InvalidParameterValueException("unable to find user account " + user.getAccountId());
    }
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    // If the user is a System user, return an error
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new InvalidParameterValueException("User id : " + userId + " is a system user, enabling is not allowed");
    }
    checkAccess(caller, AccessType.OperateEntry, true, account);
    final boolean success = Transaction.execute(new TransactionCallback<Boolean>() {

        @Override
        public Boolean doInTransaction(final TransactionStatus status) {
            boolean success = doSetUserStatus(userId, State.enabled);
            // make sure the account is enabled too
            success = success && enableAccount(user.getAccountId());
            return success;
        }
    });
    if (success) {
        // whenever the user is successfully enabled, reset the login attempts to zero
        updateLoginAttempts(userId, 0, false);
        CallContext.current().putContextParameter(User.class, user.getUuid());
        return _userAccountDao.findById(userId);
    } else {
        throw new CloudRuntimeException("Unable to enable user " + userId);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 19 with UserAccount

use of com.cloud.legacymodel.user.UserAccount in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method lockUser.

@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_LOCK, eventDescription = "locking User")
public UserAccount lockUser(final long userId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Check if user with id exists in the system
    final User user = _userDao.findById(userId);
    if (user == null || user.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find user by id");
    }
    final Account account = _accountDao.findById(user.getAccountId());
    if (account == null) {
        throw new InvalidParameterValueException("unable to find user account " + user.getAccountId());
    }
    // don't allow to lock user of the account of type Project
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Unable to find user by id");
    }
    // If the user is a System user, return an error. We do not allow this
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new PermissionDeniedException("user id : " + userId + " is a system user, locking is not allowed");
    }
    checkAccess(caller, AccessType.OperateEntry, true, account);
    // make sure the account is enabled too
    // if the user is either locked already or disabled already, don't change state...only lock currently enabled
    // users
    boolean success;
    if (user.getState().equals(State.locked)) {
        // already locked...no-op
        return _userAccountDao.findById(userId);
    } else if (user.getState().equals(State.enabled)) {
        success = doSetUserStatus(user.getId(), State.locked);
        boolean lockAccount = true;
        final List<UserVO> allUsersByAccount = _userDao.listByAccount(user.getAccountId());
        for (final UserVO oneUser : allUsersByAccount) {
            if (oneUser.getState().equals(State.enabled)) {
                lockAccount = false;
                break;
            }
        }
        if (lockAccount) {
            success = (success && lockAccount(user.getAccountId()));
        }
    } else {
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Attempting to lock a non-enabled user, current state is " + user.getState() + " (userId: " + user.getId() + "), locking failed.");
        }
        success = false;
    }
    if (success) {
        CallContext.current().putContextParameter(User.class, user.getUuid());
        return _userAccountDao.findById(userId);
    } else {
        throw new CloudRuntimeException("Unable to lock user " + userId);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) VpnUserVO(com.cloud.network.VpnUserVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) ActionEvent(com.cloud.event.ActionEvent)

Example 20 with UserAccount

use of com.cloud.legacymodel.user.UserAccount in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method disableUser.

@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_DISABLE, eventDescription = "disabling User", async = true)
public UserAccount disableUser(final long userId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Check if user exists in the system
    final User user = _userDao.findById(userId);
    if (user == null || user.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    final Account account = _accountDao.findById(user.getAccountId());
    if (account == null) {
        throw new InvalidParameterValueException("unable to find user account " + user.getAccountId());
    }
    // don't allow disabling user belonging to project's account
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    // If the user is a System user, return an error
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new InvalidParameterValueException("User id : " + userId + " is a system user, disabling is not allowed");
    }
    checkAccess(caller, AccessType.OperateEntry, true, account);
    final boolean success = doSetUserStatus(userId, State.disabled);
    if (success) {
        CallContext.current().putContextParameter(User.class, user.getUuid());
        // user successfully disabled
        return _userAccountDao.findById(userId);
    } else {
        throw new CloudRuntimeException("Unable to disable user " + userId);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

UserAccount (com.cloud.legacymodel.user.UserAccount)21 Account (com.cloud.legacymodel.user.Account)10 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)8 ServerApiException (com.cloud.api.ServerApiException)7 UserResponse (com.cloud.api.response.UserResponse)5 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)5 User (com.cloud.legacymodel.user.User)5 ActionEvent (com.cloud.event.ActionEvent)4 Domain (com.cloud.legacymodel.domain.Domain)4 Pair (com.cloud.legacymodel.utils.Pair)4 CloudAuthenticationException (com.cloud.legacymodel.exceptions.CloudAuthenticationException)3 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)3 VpnUserVO (com.cloud.network.VpnUserVO)3 AccountResponse (com.cloud.api.response.AccountResponse)2 DomainVO (com.cloud.domain.DomainVO)2 LdapUser (com.cloud.ldap.LdapUser)2 NoLdapUserMatchingQueryException (com.cloud.ldap.NoLdapUserMatchingQueryException)2 UserAuthenticator (com.cloud.server.auth.UserAuthenticator)2 DB (com.cloud.utils.db.DB)2 TransactionStatus (com.cloud.utils.db.TransactionStatus)2