Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use both project and user API token and populate default org id and projectid #325

Merged
merged 5 commits into from
Jan 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 55 additions & 30 deletions internal/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"syscall"

Expand Down Expand Up @@ -87,41 +88,29 @@ func (c *Client) NewCommand() *cobra.Command {
token := string(b)
c.Servicer.SetToken(token)
metalGoClient := c.Servicer.MetalAPI(cmd)
c.UserService = *metalGoClient.UsersApi
c.ProjectService = *metalGoClient.ProjectsApi
c.UserService = *metalGoClient.UsersApi

include := []string{} // []string | Nested attributes to include. Included objects will return their full attributes. Attribute names can be dotted (up to 3 levels) to included deeply nested objects. (optional)
exclude := []string{"devices", "members", "memberships", "invitations", "ssh_keys", "volumes", "backend_transfer_enabled", "updated_at", "customdata", "event_alert_configuration",
"timezone", "features", "avatar_url", "avatar_thumb_url", "two_factor_auth", "mailing_address", "max_projects", "verification_stage", "emails", "phone_number", "restricted",
"full_name", "email", "social_accounts", "opt_in_updated_at", "opt_in", "first_name", "last_name", "last_login_at"}
user, _, err := c.UserService.FindCurrentUser(context.Background()).Include(include).Exclude(exclude).Execute()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO we should stick with loading the current user first so that, if we were given a user token, we avoid loading more projects than necessary or making multiple paginated calls to the projects endpoint. What is the response and/or error that comes back if we try to run c.UserService.FindCurrentUser(context.Background()).Include(include).Exclude(exclude).Execute() with a project token? Is there something in the response/error that we can use to decide that the token might be a project token?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description of #265 had an approach in mind

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is already largely following the steps in the issue description. I still prefer adding project API support in a way that does not add latency to user token initialization, but adding the 2-project limit described in that issue to this PR would at least reduce the added latency.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chris pointed out that a user might only have 1 project, in which case metal init would treat their token as a project token instead of a user token; the token type doesn't have any impact outside of the init command, though, so which endpoint we try to load first is largely a philosophical issue. I leave the decision up to the contributor as to whether we should remove auto-pagination from getProjectsOK or load the current user endpoint first and then try projects if current user 403s.

// Parse the entered key to figure out if it's a user or project
// level API Key
defaultOrgId, defaultProjectId, err := parseServiceToken(c.ProjectService, c.UserService)
if err != nil {
return err
}
organization := user.GetDefaultOrganizationId()
project := user.GetDefaultProjectId()
fmt.Printf("Organization ID [%s]: ", organization)

fmt.Printf("Organization ID [%s]: ", defaultOrgId)
userOrg := ""
fmt.Scanln(&userOrg)
if userOrg == "" {
userOrg = organization
}

// Choose the first project in the preferred org
if project == "" {
project, err = getFirstProjectID(c.ProjectService, userOrg)
if err != nil {
return err
}
userOrg = defaultOrgId
}

fmt.Printf("Project ID [%s]: ", project)
fmt.Printf("Project ID [%s]: ", defaultProjectId)

userProj := ""
fmt.Scanln(&userProj)
if userProj == "" {
userProj = project
userProj = defaultProjectId
}

b, err = formatConfig(userProj, userOrg, token)
Expand All @@ -135,22 +124,58 @@ func (c *Client) NewCommand() *cobra.Command {
return initCmd
}

func getFirstProjectID(s metal.ProjectsApiService, userOrg string) (string, error) {
include := []string{"organization"} // []string | Nested attributes to include. Included objects will return their full attributes. Attribute names can be dotted (up to 3 levels) to included deeply nested objects. (optional)
exclude := []string{"devices", "members", "memberships", "invitations", "ssh_keys", "volumes", "backend_transfer_enabled", "updated_at", "customdata", "event_alert_configuration"}
resp, err := s.FindProjects(context.Background()).Include(include).Exclude(exclude).ExecuteWithPagination()
func parseServiceToken(p metal.ProjectsApiService, u metal.UsersApiService) (string, string, error) {
var defaultOrgId, defaultProjectId string
// Get first page of projects associated with provided token
projects, err := getFirstPageOfProjects(p)
if err != nil {
return "", err
return "", "", err
}

projects := resp.Projects
for _, p := range projects {
if p.Organization.GetId() == userOrg {
return p.GetId(), nil
switch numProj := len(projects); {
case numProj == 0:
// If no projects come back, warn the user but assume it's a valid user
// token
fmt.Println("WARN: No available projects found with the provided API Token")
defaultOrgId, defaultProjectId, err = getDefaultIds(u)
if err != nil {
return "", "", err
}
case numProj == 1:
// If only one project comes back, assume it's a project token
// and grab the ProjectID and Org Id from that single project
defaultProjectId = projects[0].GetId()
defaultOrgId = path.Base(projects[0].Organization.AdditionalProperties["href"].(string))
case numProj > 1:
// If more than one project comes back it must be a user token.
defaultOrgId, defaultProjectId, err = getDefaultIds(u)
if err != nil {
return "", "", err
}
}

return defaultOrgId, defaultProjectId, nil
}

func getDefaultIds(u metal.UsersApiService) (string, string, error) {
// Set up exclude list for user query
exclude := []string{"devices", "members", "memberships", "invitations", "ssh_keys", "volumes", "backend_transfer_enabled", "updated_at", "customdata", "event_alert_configuration",
"timezone", "features", "avatar_url", "avatar_thumb_url", "two_factor_auth", "mailing_address", "max_projects", "verification_stage", "emails", "phone_number", "restricted",
"full_name", "email", "social_accounts", "opt_in_updated_at", "opt_in", "first_name", "last_name", "last_login_at"}
user, _, err := u.FindCurrentUser(context.Background()).Exclude(exclude).Execute()
if err != nil {
return "", "", err
}
return user.GetDefaultOrganizationId(), user.GetDefaultProjectId(), err
}

return "", nil // it's ok to have no projects and no default project
func getFirstPageOfProjects(p metal.ProjectsApiService) ([]metal.Project, error) {
exclude := []string{"address", "backend_transfer_enabled", "created_at", "customdata", "description", "devices", "event_alert_configuration", "members", "memberships", "invitations", "ssh_keys", "tags", "transfers", "volumes", "updated_at"}
projectList, _, err := p.FindProjects(context.Background()).Exclude(exclude).Page(1).Execute()
if err != nil {
return nil, err
}
return projectList.Projects, err
}

func formatConfig(userProj, userOrg, token string) ([]byte, error) {
Expand Down
Loading