Skip to content

Commit afd19ba

Browse files
gfelbingjoaopalet
andauthored
auth: login: use next free port (#113)
* auth: login: use next free port * Update internal/pkg/auth/user_login.go Co-authored-by: João Palet <[email protected]> * Update internal/pkg/auth/user_login.go Co-authored-by: João Palet <[email protected]> --------- Co-authored-by: João Palet <[email protected]>
1 parent 0d343da commit afd19ba

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

internal/pkg/auth/user_login.go

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"io"
1010
"net"
1111
"net/http"
12-
"net/url"
1312
"os"
1413
"os/exec"
1514
"path/filepath"
@@ -23,7 +22,6 @@ import (
2322
const (
2423
authDomain = "auth.01.idp.eu01.stackit.cloud/oauth"
2524
clientId = "stackit-cli-client-id"
26-
redirectURL = "http://localhost:8000"
2725
loginSuccessPath = "/login-successful"
2826
stackitLandingPage = "https://www.stackit.de"
2927
htmlTemplatesPath = "templates"
@@ -39,6 +37,16 @@ type User struct {
3937

4038
// AuthorizeUser implements the PKCE OAuth2 flow.
4139
func AuthorizeUser() error {
40+
listener, err := net.Listen("tcp", ":0")
41+
if err != nil {
42+
return fmt.Errorf("bind port for login redirect: %w", err)
43+
}
44+
address, ok := listener.Addr().(*net.TCPAddr)
45+
if !ok {
46+
return fmt.Errorf("assert listener address type to TCP address")
47+
}
48+
redirectURL := fmt.Sprintf("http://localhost:%d", address.Port)
49+
4250
conf := &oauth2.Config{
4351
ClientID: clientId,
4452
Endpoint: oauth2.Endpoint{
@@ -146,19 +154,6 @@ func AuthorizeUser() error {
146154
}
147155
})
148156

149-
// Parse the redirect URL for the port number
150-
u, err := url.Parse(redirectURL)
151-
if err != nil {
152-
return fmt.Errorf("parse redirect URL: %w", err)
153-
}
154-
155-
// Set up a listener on the redirect port
156-
port := fmt.Sprintf(":%s", u.Port())
157-
l, err := net.Listen("tcp", port)
158-
if err != nil {
159-
return fmt.Errorf("listen to port %s: %w", port, err)
160-
}
161-
162157
// Open a browser window to the authorizationURL
163158
err = openBrowser(authorizationURL)
164159
if err != nil {
@@ -167,7 +162,7 @@ func AuthorizeUser() error {
167162

168163
// Start the blocking web server loop
169164
// It will exit when the handlers get fired and call server.Close()
170-
err = server.Serve(l)
165+
err = server.Serve(listener)
171166
if !errors.Is(err, http.ErrServerClosed) {
172167
return fmt.Errorf("server for PKCE flow closed unexpectedly: %w", err)
173168
}

0 commit comments

Comments
 (0)