Search in sources :

Example 61 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class AuthorizeSAMLSSOCmd method execute.

@Override
public void execute() {
    // Check permissions
    UserAccount userAccount = _accountService.getUserAccountById(getId());
    if (userAccount == null) {
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, "Unable to find a user account with the given ID");
    }
    Domain domain = _domainService.getDomain(userAccount.getDomainId());
    Account account = _accountService.getAccount(userAccount.getAccountId());
    _accountService.checkAccess(CallContext.current().getCallingAccount(), domain);
    _accountService.checkAccess(CallContext.current().getCallingAccount(), SecurityChecker.AccessType.OperateEntry, true, account);
    CallContext.current().setEventDetails("UserId: " + getId());
    SuccessResponse response = new SuccessResponse();
    Boolean status = false;
    if (_samlAuthManager.authorizeUser(getId(), getEntityId(), getEnable())) {
        status = true;
    }
    response.setResponseName(getCommandName());
    response.setSuccess(status);
    setResponseObject(response);
}
Also used : Account(com.cloud.user.Account) UserAccount(com.cloud.user.UserAccount) SuccessResponse(org.apache.cloudstack.api.response.SuccessResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) Domain(com.cloud.domain.Domain) UserAccount(com.cloud.user.UserAccount)

Example 62 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class ListAndSwitchSAMLAccountCmd method authenticate.

@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    if (session == null || session.isNew()) {
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, _apiServer.getSerializedApiError(ApiErrorCode.UNAUTHORIZED.getHttpCode(), "Only authenticated saml users can request this API", params, responseType));
    }
    if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) {
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, _apiServer.getSerializedApiError(ApiErrorCode.UNAUTHORIZED.getHttpCode(), "Unauthorized session, please re-login", params, responseType));
    }
    final long currentUserId = (Long) session.getAttribute("userid");
    final UserAccount currentUserAccount = _accountService.getUserAccountById(currentUserId);
    if (currentUserAccount == null || currentUserAccount.getSource() != User.Source.SAML2) {
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Only authenticated saml users can request this API", params, responseType));
    }
    String userUuid = null;
    String domainUuid = null;
    if (params.containsKey(ApiConstants.USER_ID)) {
        userUuid = ((String[]) params.get(ApiConstants.USER_ID))[0];
    }
    if (params.containsKey(ApiConstants.DOMAIN_ID)) {
        domainUuid = ((String[]) params.get(ApiConstants.DOMAIN_ID))[0];
    }
    if (userUuid != null && domainUuid != null) {
        final User user = _userDao.findByUuid(userUuid);
        final Domain domain = _domainDao.findByUuid(domainUuid);
        final UserAccount nextUserAccount = _accountService.getUserAccountById(user.getId());
        if (nextUserAccount != null && !nextUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
            throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "The requested user account is locked and cannot be switched to, please contact your administrator.", params, responseType));
        }
        if (nextUserAccount == null || !nextUserAccount.getAccountState().equals(Account.State.enabled.toString()) || !nextUserAccount.getUsername().equals(currentUserAccount.getUsername()) || !nextUserAccount.getExternalEntity().equals(currentUserAccount.getExternalEntity()) || (nextUserAccount.getDomainId() != domain.getId()) || (nextUserAccount.getSource() != User.Source.SAML2)) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "User account is not allowed to switch to the requested account", params, responseType));
        }
        try {
            if (_apiServer.verifyUser(nextUserAccount.getId())) {
                final LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, nextUserAccount.getUsername(), nextUserAccount.getUsername() + nextUserAccount.getSource().toString(), nextUserAccount.getDomainId(), null, remoteAddress, params);
                SAMLUtils.setupSamlUserCookies(loginResponse, resp);
                resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
                return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
            }
        } catch (CloudAuthenticationException | IOException exception) {
            s_logger.debug("Failed to switch to request SAML user account due to: " + exception.getMessage());
        }
    } else {
        List<UserAccountVO> switchableAccounts = _userAccountDao.getAllUsersByNameAndEntity(currentUserAccount.getUsername(), currentUserAccount.getExternalEntity());
        if (switchableAccounts != null && switchableAccounts.size() > 0 && currentUserId != User.UID_SYSTEM) {
            List<SamlUserAccountResponse> accountResponses = new ArrayList<SamlUserAccountResponse>();
            for (UserAccountVO userAccount : switchableAccounts) {
                User user = _userDao.getUser(userAccount.getId());
                Domain domain = _domainService.getDomain(userAccount.getDomainId());
                SamlUserAccountResponse accountResponse = new SamlUserAccountResponse();
                accountResponse.setUserId(user.getUuid());
                accountResponse.setUserName(user.getUsername());
                accountResponse.setDomainId(domain.getUuid());
                accountResponse.setDomainName(domain.getName());
                accountResponse.setAccountName(userAccount.getAccountName());
                accountResponse.setIdpId(user.getExternalEntity());
                accountResponses.add(accountResponse);
            }
            ListResponse<SamlUserAccountResponse> response = new ListResponse<SamlUserAccountResponse>();
            response.setResponses(accountResponses);
            response.setResponseName(getCommandName());
            return ApiResponseSerializer.toSerializedString(response, responseType);
        }
    }
    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Unable to switch to requested SAML account. Please make sure your user/account is enabled. Please contact your administrator.", params, responseType));
}
Also used : User(com.cloud.user.User) ListResponse(org.apache.cloudstack.api.response.ListResponse) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) SamlUserAccountResponse(org.apache.cloudstack.api.response.SamlUserAccountResponse) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UserAccountVO(com.cloud.user.UserAccountVO) ServerApiException(org.apache.cloudstack.api.ServerApiException) Domain(com.cloud.domain.Domain) UserAccount(com.cloud.user.UserAccount) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse)

Example 63 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class SAML2AuthManagerImpl method saveToken.

@Override
public void saveToken(String authnId, String domainPath, String entity) {
    Long domainId = null;
    if (domainPath != null) {
        Domain domain = _domainMgr.findDomainByPath(domainPath);
        if (domain != null) {
            domainId = domain.getId();
        }
    }
    SAMLTokenVO token = new SAMLTokenVO(authnId, domainId, entity);
    if (_samlTokenDao.findByUuid(authnId) == null) {
        _samlTokenDao.persist(token);
    } else {
        s_logger.warn("Duplicate SAML token for entity=" + entity + " token id=" + authnId + " domain=" + domainPath);
    }
}
Also used : Domain(com.cloud.domain.Domain)

Example 64 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class ContrailManagerImpl method getProjectId.

@Override
public String getProjectId(long domainId, long accountId) throws IOException {
    ProjectVO project = getProject(accountId);
    if (project != null) {
        return project.getUuid();
    }
    DomainVO domain = _domainDao.findById(domainId);
    if (domain.getId() != Domain.ROOT_DOMAIN) {
        net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain) _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid());
        return _api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, VNC_DEFAULT_PROJECT);
    }
    return null;
}
Also used : DomainVO(com.cloud.domain.DomainVO) Domain(com.cloud.domain.Domain) ProjectVO(com.cloud.projects.ProjectVO)

Example 65 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

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 always use domainId first. If that does not exist, we will use domain name. If THAT doesn't exist
    // we will default to ROOT
    final Domain userDomain = domainMgr.findDomainByIdOrPath(domainId, domainPath);
    if (userDomain == null || userDomain.getId() < 1L) {
        throw new CloudAuthenticationException("Unable to find the domain from the path " + domainPath);
    } else {
        domainId = userDomain.getId();
    }
    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());
        }
        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.user.UserAccount) Account(com.cloud.user.Account) CloudAuthenticationException(com.cloud.exception.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.domain.Domain) UserAccount(com.cloud.user.UserAccount)

Aggregations

Domain (com.cloud.domain.Domain)81 Account (com.cloud.user.Account)42 ArrayList (java.util.ArrayList)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)20 Test (org.junit.Test)20 DeployDestination (com.cloud.deploy.DeployDestination)17 Network (com.cloud.network.Network)17 ReservationContext (com.cloud.vm.ReservationContext)17 DataCenter (com.cloud.dc.DataCenter)16 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)16 NetworkOffering (com.cloud.offering.NetworkOffering)16 HostVO (com.cloud.host.HostVO)15 NetworkVO (com.cloud.network.dao.NetworkVO)15 UserAccount (com.cloud.user.UserAccount)15 URI (java.net.URI)12 DomainVO (com.cloud.domain.DomainVO)11 ProjectAccount (com.cloud.projects.ProjectAccount)11 Project (com.cloud.projects.Project)10 NiciraNvpDeviceVO (com.cloud.network.NiciraNvpDeviceVO)8 DB (com.cloud.utils.db.DB)8