From b2cefb856e3a80b29ee3cdbc09cd2df156dd6ee5 Mon Sep 17 00:00:00 2001 From: Fabian 'xx4h' Sylvester Date: Sat, 12 Oct 2024 12:25:17 +0200 Subject: [PATCH] cleanup: extract to function * isURL * isJwtToken --- pkg/init/init.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/pkg/init/init.go b/pkg/init/init.go index 1ba7b61..0eb761d 100644 --- a/pkg/init/init.go +++ b/pkg/init/init.go @@ -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): ") @@ -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: ") @@ -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() }