| 209 | } |
| 210 | |
| 211 | func setTeamOnLogin(ctx context.Context, cmd *cobra.Command, token string) error { |
| 212 | cl, err := team.NewClient(token) |
| 213 | if err != nil { |
| 214 | return fmt.Errorf("failed to create API client: %w", err) |
| 215 | } |
| 216 | |
| 217 | // list all available teams |
| 218 | teams, err := cl.ListAllTeams(ctx) |
| 219 | if err != nil { |
| 220 | return fmt.Errorf("failed to list teams: %w", err) |
| 221 | } |
| 222 | |
| 223 | if cmd.Flags().Changed("team") { |
| 224 | // don't care about the current cached config value as the user explicitly passes the `team` flag |
| 225 | currentTeam := cmd.Flag("team").Value.String() |
| 226 | foundTeam, err := cl.FindTeam(teams, currentTeam) |
| 227 | if err != nil { |
| 228 | return fmt.Errorf("failed to validate team: %w", err) |
| 229 | } |
| 230 | err = config.SetValue("team", currentTeam) |
| 231 | if err != nil { |
| 232 | return fmt.Errorf("failed to set team: %w", err) |
| 233 | } |
| 234 | err = config.SetValue("team_internal", strconv.FormatBool(foundTeam.Internal)) |
| 235 | if err != nil { |
| 236 | return fmt.Errorf("failed to set team metadata: %w", err) |
| 237 | } |
| 238 | return nil |
| 239 | } |
| 240 | |
| 241 | currentTeam, err := config.GetValue("team") |
| 242 | if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 243 | return fmt.Errorf("failed to get current team: %w", err) |
| 244 | } |
| 245 | foundTeam, err := cl.FindTeam(teams, currentTeam) |
| 246 | if len(currentTeam) > 0 && err == nil { |
| 247 | // The selected team is available to the user, so we're just using it |
| 248 | cmd.Printf("Your current team is set to %s.\n", foundTeam.Name) |
| 249 | |
| 250 | // Make sure we update the internal flag in case it changed |
| 251 | err = config.SetValue("team_internal", strconv.FormatBool(foundTeam.Internal)) |
| 252 | if err != nil { |
| 253 | return fmt.Errorf("failed to set team metadata: %w", err) |
| 254 | } |
| 255 | return nil |
| 256 | } |
| 257 | |
| 258 | // either the team is not set, or the currently selected team is unavailable |
| 259 | switch len(teams) { |
| 260 | case 0: |
| 261 | // no available teams, urge the user to create one |
| 262 | cmd.Printf("Your current team is not set.\n\n") |
| 263 | cmd.Printf("There are no teams available to you.\n\n") |
| 264 | cmd.Printf("Please create a team or accept an invite.") |
| 265 | cmd.Printf("You should run `cloudquery switch <team>` to set your team afterwards.\n\n") |
| 266 | if len(currentTeam) > 0 { |
| 267 | // remove current team setting |
| 268 | err = config.UnsetValue("team") |