Search in sources :

Example 21 with CredentialedUser

use of com.google.cloud.tools.intellij.login.CredentialedUser in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudRepositoryService method list.

@NotNull
public ListReposResponse list(CredentialedUser user, String cloudProject) throws CloudRepositoryServiceException {
    try {
        Credential credential = user.getCredential();
        HttpRequestInitializer initializer = httpRequest -> {
            HttpHeaders headers = new HttpHeaders();
            httpRequest.setConnectTimeout(LIST_TIMEOUT_MS);
            httpRequest.setReadTimeout(LIST_TIMEOUT_MS);
            httpRequest.setHeaders(headers);
            credential.initialize(httpRequest);
        };
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        String userAgent = ServiceManager.getService(PluginInfoService.class).getUserAgent();
        Source source = new Source.Builder(httpTransport, JacksonFactory.getDefaultInstance(), initializer).setRootUrl(CLOUD_SOURCE_API_ROOT_URL).setServicePath("").setApplicationName(userAgent).build();
        return new CustomUrlSourceRequest(source, cloudProject).execute();
    } catch (IOException | GeneralSecurityException ex) {
        throw new CloudRepositoryServiceException();
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ListReposResponse(com.google.api.services.source.model.ListReposResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) Preconditions(com.google.api.client.util.Preconditions) Source(com.google.api.services.source.Source) ServiceManager(com.intellij.openapi.components.ServiceManager) GeneralSecurityException(java.security.GeneralSecurityException) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) Key(com.google.api.client.util.Key) Credential(com.google.api.client.auth.oauth2.Credential) SourceRequest(com.google.api.services.source.SourceRequest) NotNull(org.jetbrains.annotations.NotNull) HttpHeaders(com.google.api.client.http.HttpHeaders) Credential(com.google.api.client.auth.oauth2.Credential) GeneralSecurityException(java.security.GeneralSecurityException) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) IOException(java.io.IOException) Source(com.google.api.services.source.Source) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) NotNull(org.jetbrains.annotations.NotNull)

Example 22 with CredentialedUser

use of com.google.cloud.tools.intellij.login.CredentialedUser in project google-cloud-intellij by GoogleCloudPlatform.

the class GcpHttpAuthDataProvider method getAuthData.

@Nullable
@Override
public AuthData getAuthData(@NotNull String url) {
    final Project currentProject = getCurrentProject();
    if ((currentProject != null || Context.currentContext != null) && isGcpUrl(url)) {
        Context currentContext = // always prefer context over project setting.
        Context.currentContext;
        String userEmail = currentContext != null ? currentContext.userName : null;
        if (Strings.isNullOrEmpty(userEmail) && currentProject != null) {
            userEmail = PropertiesComponent.getInstance(currentProject).getValue(GCP_USER, "");
        }
        CredentialedUser targetUser = getUserFromEmail(userEmail);
        if (targetUser == null) {
            // show a dialog allowing the user to select a login.  (new project recognized)
            ApplicationManager.getApplication().invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    SelectUserDialog dialog = new SelectUserDialog(currentProject, GctBundle.getString("httpauthprovider.chooselogin"));
                    DialogManager.show(dialog);
                    chooseManualLogin = !dialog.isOK();
                    selectedUser = dialog.getSelectedUser();
                }
            }, ModalityState.defaultModalityState());
            if (chooseManualLogin) {
                return null;
            }
            userEmail = selectedUser;
            targetUser = getUserFromEmail(userEmail);
            if (targetUser != null && currentProject != null && Context.currentContext == null) {
                PropertiesComponent.getInstance(currentProject).setValue(GCP_USER, userEmail);
            }
        }
        if (targetUser != null) {
            try {
                return new AuthData(targetUser.getEmail(), targetUser.getGoogleLoginState().fetchAccessToken());
            } catch (IOException ex) {
                LOG.error("IOException creating authdata:" + ex.toString());
            }
        }
    }
    return null;
}
Also used : Project(com.intellij.openapi.project.Project) SelectUserDialog(com.google.cloud.tools.intellij.resources.SelectUserDialog) AuthData(com.intellij.util.AuthData) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) IOException(java.io.IOException) Nullable(org.jetbrains.annotations.Nullable)

Example 23 with CredentialedUser

use of com.google.cloud.tools.intellij.login.CredentialedUser in project google-cloud-intellij by GoogleCloudPlatform.

the class ProjectRepositoriesModelItem method loadRepositories.

@SuppressWarnings("FutureReturnValueIgnored")
public void loadRepositories(@NotNull String cloudProject, @NotNull CredentialedUser user, @Nullable Runnable onComplete) {
    setUserObject(cloudProject);
    cloudRepositoryService.listAsync(user, cloudProject).thenAccept(response -> {
        removeAllChildren();
        List<Repo> repositories = response.getRepos();
        if (!response.isEmpty() && repositories != null) {
            repositories.forEach(repo -> {
                Object name = repo.get("name");
                if (name != null) {
                    add(new RepositoryModelItem(name.toString()));
                }
            });
        } else {
            add(new ResourceEmptyModelItem(GctBundle.message("cloud.repository.list.empty")));
        }
        if (onComplete != null) {
            onComplete.run();
        }
    }).exceptionally(response -> {
        removeAllChildren();
        add(new ResourceErrorModelItem(GctBundle.message("cloud.repository.list.error")));
        if (onComplete != null) {
            onComplete.run();
        }
        return null;
    });
}
Also used : Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) ResourceErrorModelItem(com.google.cloud.tools.intellij.resources.ResourceErrorModelItem) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) Repo(com.google.api.services.source.model.Repo) GctBundle(com.google.cloud.tools.intellij.util.GctBundle) ResourceEmptyModelItem(com.google.cloud.tools.intellij.resources.ResourceEmptyModelItem) NotNull(org.jetbrains.annotations.NotNull) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) List(java.util.List) ResourceEmptyModelItem(com.google.cloud.tools.intellij.resources.ResourceEmptyModelItem) ResourceErrorModelItem(com.google.cloud.tools.intellij.resources.ResourceErrorModelItem)

Example 24 with CredentialedUser

use of com.google.cloud.tools.intellij.login.CredentialedUser in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudDebuggerClient method getClient.

/**
 * Returns a cloud debugger connection given a user email to indicate the credentials to use. The
 * function may return null if the user is not logged in.
 */
@Nullable
private static Debugger getClient(@Nullable final String userEmail, final int timeout) {
    if (Strings.isNullOrEmpty(userEmail)) {
        LOG.warn("unexpected null email in controller initialize.");
        return null;
    }
    final String hashkey = userEmail + timeout;
    Debugger cloudDebuggerClient = debuggerClientsFromUserEmail.get(hashkey);
    if (cloudDebuggerClient == null) {
        try {
            final CredentialedUser user = Services.getLoginService().getAllUsers().get(userEmail);
            final Credential credential = (user != null ? user.getCredential() : null);
            if (credential != null) {
                user.getGoogleLoginState().addLoginListener(new LoginListener() {

                    @Override
                    public void statusChanged(boolean login) {
                        if (!login) {
                            // aggressively remove the cached item on any status change.
                            debuggerClientsFromUserEmail.remove(hashkey);
                        } else {
                        // NOPMD
                        // user logged in, should we do something?
                        }
                    }
                });
                HttpRequestInitializer initializer = new HttpRequestInitializer() {

                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {
                        HttpHeaders headers = new HttpHeaders();
                        httpRequest.setConnectTimeout(timeout);
                        httpRequest.setReadTimeout(timeout);
                        httpRequest.setHeaders(headers);
                        credential.initialize(httpRequest);
                    }
                };
                HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
                String userAgent = ServiceManager.getService(PluginInfoService.class).getUserAgent();
                cloudDebuggerClient = new Builder(httpTransport, JSON_FACTORY, initializer).setRootUrl(ROOT_URL).setApplicationName(userAgent).build().debugger();
            }
        } catch (IOException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        } catch (GeneralSecurityException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        }
        if (cloudDebuggerClient != null) {
            debuggerClientsFromUserEmail.put(hashkey, cloudDebuggerClient);
        }
    }
    return cloudDebuggerClient;
}
Also used : Debugger(com.google.api.services.clouddebugger.v2.Clouddebugger.Debugger) HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Credential(com.google.api.client.auth.oauth2.Credential) Builder(com.google.api.services.clouddebugger.v2.Clouddebugger.Builder) GeneralSecurityException(java.security.GeneralSecurityException) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) IOException(java.io.IOException) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) LoginListener(com.google.gdt.eclipse.login.common.LoginListener) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) Nullable(org.jetbrains.annotations.Nullable)

Example 25 with CredentialedUser

use of com.google.cloud.tools.intellij.login.CredentialedUser in project google-cloud-intellij by GoogleCloudPlatform.

the class UsersListCellRenderer method getListCellRendererComponent.

@Nullable
@Override
public Component getListCellRendererComponent(JList<? extends UsersListItem> list, UsersListItem usersListItem, int index, boolean isSelected, boolean cellHasFocus) {
    if (usersListItem instanceof NoUsersListItem) {
        return createNoUserDisplay();
    }
    final CredentialedUser activeUser = Services.getLoginService().getActiveUser();
    final boolean isActiveUserSelected = activeUser != null && usersListItem.getUserEmail().equals(activeUser.getEmail());
    JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, HGAP, VGAP));
    mainPanel.setMinimumSize(isActiveUserSelected ? activeMainPanelDimension : mainPanelDimension);
    mainPanel.setAlignmentX(LEFT_ALIGNMENT);
    // Update colors
    final Color bg = isActiveUserSelected ? activeColor : inactiveColor;
    final Color fg = isActiveUserSelected ? UIUtil.getListSelectionForeground() : UIUtil.getListForeground();
    mainPanel.setBackground(bg);
    mainPanel.setForeground(fg);
    Image image = usersListItem.getUserPicture();
    if (image == null) {
        // Use default profile image.
        image = Toolkit.getDefaultToolkit().getImage(UsersListCellRenderer.class.getResource(DEFAULT_AVATAR));
    }
    final int imageWidth;
    final int imageHeight;
    final Map<String, Image> userImageCache;
    if (isActiveUserSelected) {
        imageWidth = ACTIVE_USER_IMAGE_WIDTH;
        imageHeight = ACTIVE_USER_IMAGE_HEIGHT;
        userImageCache = userLargeImageCache;
    } else {
        imageWidth = PLAIN_USER_IMAGE_WIDTH;
        imageHeight = PLAIN_USER_IMAGE_HEIGHT;
        userImageCache = userSmallImageCache;
    }
    final Image scaledImage;
    if (!userImageCache.containsKey(usersListItem.getUserEmail())) {
        scaledImage = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH);
        userImageCache.put(usersListItem.getUserEmail(), scaledImage);
    } else {
        scaledImage = userImageCache.get(usersListItem.getUserEmail());
    }
    final JComponent textPanel;
    if (isActiveUserSelected) {
        textPanel = createActiveTextDisplay(usersListItem);
    } else {
        textPanel = createTextDisplay(false, usersListItem);
    }
    mainPanel.add(new JLabel(new ImageIcon(scaledImage)));
    mainPanel.add(textPanel);
    mainPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, JBColor.border()));
    return mainPanel;
}
Also used : JPanel(javax.swing.JPanel) ImageIcon(javax.swing.ImageIcon) FlowLayout(java.awt.FlowLayout) Color(java.awt.Color) JBColor(com.intellij.ui.JBColor) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) Image(java.awt.Image) Point(java.awt.Point) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

CredentialedUser (com.google.cloud.tools.intellij.login.CredentialedUser)31 IOException (java.io.IOException)9 GoogleLoginState (com.google.gdt.eclipse.login.common.GoogleLoginState)6 Nullable (org.jetbrains.annotations.Nullable)6 IntegratedGoogleLoginService (com.google.cloud.tools.intellij.login.IntegratedGoogleLoginService)5 CloudProject (com.google.cloud.tools.intellij.project.CloudProject)5 LinkedHashMap (java.util.LinkedHashMap)5 Credential (com.google.api.client.auth.oauth2.Credential)4 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)4 ArrayList (java.util.ArrayList)3 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)2 HttpHeaders (com.google.api.client.http.HttpHeaders)2 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)2 HttpTransport (com.google.api.client.http.HttpTransport)2 CloudResourceManager (com.google.api.services.cloudresourcemanager.CloudResourceManager)2 Iam (com.google.api.services.iam.v1.Iam)2 ServiceAccount (com.google.api.services.iam.v1.model.ServiceAccount)2 ServiceAccountKey (com.google.api.services.iam.v1.model.ServiceAccountKey)2 GoogleApiClientFactory (com.google.cloud.tools.intellij.resources.GoogleApiClientFactory)2 PluginInfoService (com.google.cloud.tools.intellij.service.PluginInfoService)2