Skip to content
Draft
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions internal/cli/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func Builder() *cobra.Command {
WhoAmIBuilder(),
LogoutBuilder(),
RegisterBuilder(),
TokenBuilder(),
)

return cmd
Expand Down
81 changes: 81 additions & 0 deletions internal/cli/auth/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2025 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package auth

import (
"fmt"

"github.com/mongodb/atlas-cli-core/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/spf13/cobra"
)

//go:generate go tool go.uber.org/mock/mockgen -typed -destination=token_mock_test.go -package=auth . TokenConfig

type TokenConfig interface {
AccessToken() string
Name() string
}

type tokenOpts struct {
cli.OutputOpts
config TokenConfig
}

func (opts *tokenOpts) Run() error {
accessToken := opts.config.AccessToken()
if accessToken == "" {
return fmt.Errorf("no access token found for profile %s", opts.config.Name())
}
return opts.Print(accessToken)
}

func TokenBuilder() *cobra.Command {
opts := &tokenOpts{}
cmd := &cobra.Command{
Use: "token",
Hidden: true,
Short: "Return the token for the current profile.",
Example: ` # Return the token for the current profile:
atlas auth token

# Return the token for the current profile and save it to a file:
atlas auth token > token.txt

# Return the token for a specific profile:
atlas auth token --profile <profile_name>
`,
Args: require.NoArgs,
PreRunE: func(cmd *cobra.Command, _ []string) error {
opts.OutWriter = cmd.OutOrStdout()
// If the profile is set in the context, use it instead of the default profile
profile, ok := config.ProfileFromContext(cmd.Context())
if ok {
opts.config = profile
} else {
opts.config = config.Default()
}
return nil
},
RunE: func(_ *cobra.Command, _ []string) error {
return opts.Run()
},
}

opts.AddOutputOptFlags(cmd)

return cmd
}
116 changes: 116 additions & 0 deletions internal/cli/auth/token_mock_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

100 changes: 100 additions & 0 deletions internal/cli/auth/token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2025 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package auth

import (
"bytes"
"testing"

"github.com/mongodb/atlas-cli-core/config"
"github.com/mongodb/atlas-cli-core/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)

func Test_tokenOpts_Run_Success(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockConfig := NewMockTokenConfig(ctrl)
buf := new(bytes.Buffer)

opts := &tokenOpts{
config: mockConfig,
}
opts.OutWriter = buf
opts.Output = "template" // Set output format to template

mockConfig.EXPECT().AccessToken().Return("test-access-token").Times(1)

err := opts.Run()
require.NoError(t, err)
assert.Equal(t, "test-access-token\n", buf.String())
}

func Test_tokenOpts_Run_NoToken(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockConfig := NewMockTokenConfig(ctrl)
buf := new(bytes.Buffer)

opts := &tokenOpts{
config: mockConfig,
}
opts.OutWriter = buf

mockConfig.EXPECT().AccessToken().Return("").Times(1)
mockConfig.EXPECT().Name().Return("test-profile").Times(1)

err := opts.Run()
require.Error(t, err)
assert.Contains(t, err.Error(), "no access token found for profile test-profile")
}

func TestTokenBuilder_PreRunE_DefaultConfig(t *testing.T) {
cmd := TokenBuilder()

// Test that PreRunE uses config.Default() when no profile in context
err := cmd.PreRunE(cmd, []string{})

// Should not error - just sets up the default config
require.NoError(t, err)
}

func TestTokenBuilder_PreRunE_ProfileFromContext(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockStore := mocks.NewMockStore(ctrl)

// Create a test profile
testProfile := config.NewProfile("test-profile", mockStore)

cmd := TokenBuilder()

// Add profile to context and execute the command with that context
ctx := config.WithProfile(t.Context(), testProfile)
cmd.SetContext(ctx)

mockStore.EXPECT().
GetHierarchicalValue("test-profile", gomock.Any()).
Return("").
AnyTimes()

err := cmd.PreRunE(cmd, []string{})
require.NoError(t, err)
}
Loading