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

test: command login #949

Merged
merged 7 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
5 changes: 1 addition & 4 deletions pkg/cmd/deploy/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -569,13 +569,10 @@ func (cmd *DeployCmd) updateInstance(ctx context.Context, client *apiapp.Client,
func checkToken(f *cmdutil.Factory) error {
configureToken := f.Config.GetString("token")

t, err := token.New(&token.Config{
t := token.New(&token.Config{
Client: f.HttpClient,
Out: f.IOStreams.Out,
})
if err != nil {
return fmt.Errorf("%s: %w", utils.ErrorTokenManager, err)
}

if configureToken == "" {
return utils.ErrorTokenNotProvided
Expand Down
5 changes: 1 addition & 4 deletions pkg/cmd/deploy_remote/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -569,13 +569,10 @@ func (cmd *DeployCmd) updateInstance(ctx context.Context, client *apiapp.Client,
func checkToken(f *cmdutil.Factory) error {
configureToken := f.Config.GetString("token")

t, err := token.New(&token.Config{
t := token.New(&token.Config{
Client: f.HttpClient,
Out: f.IOStreams.Out,
})
if err != nil {
return fmt.Errorf("%s: %w", utils.ErrorTokenManager, err)
}

if configureToken == "" {
return utils.ErrorTokenNotProvided
Expand Down
7 changes: 2 additions & 5 deletions pkg/cmd/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ type initCmd struct {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down Expand Up @@ -212,10 +212,7 @@ func (cmd *initCmd) Run(c *cobra.Command, _ []string) error {
return err
}

dirPath, err := cmd.dir()
if err != nil {
return err
}
dirPath := cmd.dir()

// Create a temporary directory
tempDir, err := cmd.mkdirTemp(dirPath.Dir, "tempclonesamples")
Expand Down
158 changes: 2 additions & 156 deletions pkg/cmd/init/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func Test_initCmd_Run(t *testing.T) {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down Expand Up @@ -686,160 +686,6 @@ func Test_initCmd_Run(t *testing.T) {
},
wantErr: true,
},
{
name: "error dir",
fields: fields{
auto: true,
f: &cmdutil.Factory{
Flags: cmdutil.Flags{
GlobalFlagAll: false,
Format: "",
Out: "",
NoColor: false,
},
IOStreams: iostreams.System(),
},
globalFlagAll: false,
name: "",
preset: "vite",
mode: "deliver",
getWorkDir: func() (string, error) {
return "/path/full", nil
},
get: func(url string) (resp *http.Response, err error) {
b, err := os.ReadFile("./.fixtures/project_samples.json")
if err != nil {
return nil, err
}

responseBody := io.NopCloser(bytes.NewReader(b))
resp = &http.Response{
StatusCode: 200,
Body: responseBody,
Header: make(http.Header),
}
return resp, nil
},
readAll: io.ReadAll,
unmarshal: json.Unmarshal,
askOne: func(p survey.Prompt,
response interface{},
opts ...survey.AskOpt,
) error {
return nil
},
dir: func() (config.DirPath, error) {
return config.DirPath{}, errors.New("error dir")
},
mkdirTemp: func(dir, pattern string) (string, error) {
return "", nil
},
removeAll: os.RemoveAll,
rename: func(oldpath, newpath string) error {
return nil
},
mkdir: func(path string, perm os.FileMode) error { return nil },
marshalIndent: json.MarshalIndent,
writeFile: func(filename string, data []byte, perm fs.FileMode) error {
return nil
},
changeDir: func(dir string) error { return nil },
commandRunnerOutput: func(f *cmdutil.Factory, comm string, envVars []string) (string, error) {
return "3.2.1", nil
},
commandRunInteractive: func(f *cmdutil.Factory, comm string) error {
return nil
},
load: func(filenames ...string) (err error) {
os.Setenv("preset", "vite")
os.Setenv("mode", "deliver")
return nil
},
git: github.Github{
Clone: func(url, path string) error {
return nil
},
},
},
wantErr: true,
},
{
name: "error mkdirTemp",
fields: fields{
auto: true,
f: &cmdutil.Factory{
Flags: cmdutil.Flags{
GlobalFlagAll: false,
Format: "",
Out: "",
NoColor: false,
},
IOStreams: iostreams.System(),
},
globalFlagAll: false,
name: "",
preset: "vite",
mode: "deliver",
getWorkDir: func() (string, error) {
return "/path/full", nil
},
get: func(url string) (resp *http.Response, err error) {
b, err := os.ReadFile("./.fixtures/project_samples.json")
if err != nil {
return nil, err
}

responseBody := io.NopCloser(bytes.NewReader(b))
resp = &http.Response{
StatusCode: 200,
Body: responseBody,
Header: make(http.Header),
}
return resp, nil
},
readAll: io.ReadAll,
unmarshal: json.Unmarshal,
askOne: func(p survey.Prompt,
response interface{},
opts ...survey.AskOpt,
) error {
return nil
},
dir: func() (config.DirPath, error) {
return config.DirPath{}, errors.New("error dir")
},
mkdirTemp: func(dir, pattern string) (string, error) {
return "", nil
},
removeAll: os.RemoveAll,
rename: func(oldpath, newpath string) error {
return nil
},
mkdir: func(path string, perm os.FileMode) error { return nil },
marshalIndent: json.MarshalIndent,
writeFile: func(filename string, data []byte, perm fs.FileMode) error {
return nil
},
changeDir: func(dir string) error { return nil },
commandRunnerOutput: func(f *cmdutil.Factory, comm string, envVars []string) (string, error) {
return "3.2.1", nil
},
commandRunInteractive: func(f *cmdutil.Factory, comm string) error {
return nil
},
load: func(filenames ...string) (err error) {
os.Setenv("preset", "vite")
os.Setenv("mode", "deliver")
return nil
},
git: github.Github{
Clone: func(url, path string) error {
return nil
},
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -920,7 +766,7 @@ func Test_initCmd_deps(t *testing.T) {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down
9 changes: 9 additions & 0 deletions pkg/cmd/login/.fixtures/response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"uuid": "5b8934cf-3561-4b48-aceb-7ba52a227b6c",
"name": "One day token",
"key": "tokenazion",
"user_id": 23192,
"created": "2023-08-29T15:23:41.878136Z",
"expires_at": "2024-07-26T00:00:00Z",
"description": "example"
}
59 changes: 41 additions & 18 deletions pkg/cmd/login/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,65 @@ import (
"net/http"

msg "github.com/aziontech/azion-cli/messages/login"
"github.com/aziontech/azion-cli/pkg/cmdutil"
"github.com/aziontech/azion-cli/pkg/logger"
"github.com/skratchdot/open-golang/open"
"go.uber.org/zap"
)

const (
urlSsoNext = "https://sso.azion.com/login?next=cli"
)

func browserLogin(f *cmdutil.Factory) error {
// when it's a single test set true
var enableHandlerRouter = true

ctx, cancel := context.WithCancel(context.Background())
type Server interface {
ListenAndServe() error
Shutdown(ctx context.Context) error
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
paramValue := r.URL.Query().Get("c")
_, _ = io.WriteString(w, msg.BrowserMsg)
if paramValue != "" {
tokenValue = paramValue
}
cancel()
})
var (
globalCtx context.Context
globalCancel context.CancelFunc
)

func initializeContext() {
globalCtx, globalCancel = context.WithCancel(context.Background())
}

func shutdownContext() {
if globalCancel != nil {
globalCancel()
}
}

func (l *login) browserLogin(srv Server) error {
initializeContext()
defer shutdownContext()

srv := &http.Server{Addr: ":8080"}
err := openBrowser(f)
if enableHandlerRouter {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
paramValue := r.URL.Query().Get("c")
_, _ = io.WriteString(w, msg.BrowserMsg)
if paramValue != "" {
tokenValue = paramValue
}
globalCancel()
})
}

err := l.openBrowser()
if err != nil {
return err
}

go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
logger.Error(msg.ErrorServerClosed.Error(), zap.Error(err))
}
}()

<-ctx.Done() // wait for the signal to gracefully shutdown the server
<-globalCtx.Done() // wait for the signal to gracefully shutdown the server

// gracefully shutdown the server:
// waiting indefinitely for connections to return to idle and then shut down.
Expand All @@ -53,9 +76,9 @@ func browserLogin(f *cmdutil.Factory) error {
return nil
}

func openBrowser(f *cmdutil.Factory) error {
logger.FInfo(f.IOStreams.Out, msg.VisitMsg)
err := open.Run(urlSsoNext)
func (l *login) openBrowser() error {
logger.FInfo(l.factory.IOStreams.Out, msg.VisitMsg)
err := l.run(urlSsoNext)
if err != nil {
return err
}
Expand Down
Loading
Loading