Skip to content

Commit

Permalink
cleanup: extract to function
Browse files Browse the repository at this point in the history
* isURL
* isJwtToken
  • Loading branch information
xx4h committed Oct 12, 2024
1 parent e389413 commit b2cefb8
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions pkg/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ func getHubType() string {
return hubType
}

func isURL(url string) bool {
up, err := u.Parse(url)
if err != nil || up.Scheme == "" || up.Host == "" {
return false
}
return true
}

func getURL() string {
var url string
fmt.Print("Enter API URL of your hub (e.g. https://home-assistant.example.com/api): ")
Expand All @@ -88,14 +96,22 @@ func getURL() string {
fmt.Printf("Error: %v\n", err)
return getURL()
}
up, err := u.Parse(url)
if err != nil || up.Scheme == "" || up.Host == "" {
if ok := isURL(url); !ok {
fmt.Printf("Not a valid URL: %s\n", url)
return getURL()
}
return url
}

func isJwtToken(token []byte) bool {
t := string(token)
_, _, err := new(jwt.Parser).ParseUnverified(t, jwt.MapClaims{})
if err != nil {
return false
}
return true
}

func getToken() string {
var token string
fmt.Print("Enter your hub token: ")
Expand All @@ -104,9 +120,7 @@ func getToken() string {
fmt.Printf("Error: %v\n", err)
return getToken()
}
token = string(byteToken)
_, _, err = new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{})
if err != nil {
if ok := isJwtToken(byteToken); !ok {
fmt.Printf("\nNot a valid Token (JWT): %v\n", err)
return getToken()
}
Expand Down

0 comments on commit b2cefb8

Please sign in to comment.