github.com/greenpau/go-authcrunch@v1.1.4/pkg/redirects/redirect_parser.go (about) 1 // Copyright 2024 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package redirects 16 17 import ( 18 "fmt" 19 "net/url" 20 "strings" 21 ) 22 23 // ParseRedirectURI parses redirect_uri from URL string. 24 func ParseRedirectURI(s string) (*url.URL, error) { 25 parsedURL, err := url.Parse(s) 26 if err != nil { 27 return nil, fmt.Errorf("failed to parse base uri") 28 } 29 if parsedURL.Scheme == "" || parsedURL.Host == "" || parsedURL.Path == "" { 30 return nil, fmt.Errorf("non compliant base uri") 31 } 32 if !HasRedirectURI(parsedURL) { 33 return nil, fmt.Errorf("redirect uri is not url") 34 } 35 queryParams := parsedURL.Query() 36 rawRedirectURI := queryParams.Get("redirect_uri") 37 if strings.HasPrefix(rawRedirectURI, "/") { 38 return nil, fmt.Errorf("redirect uri has no scheme and host") 39 } 40 parsedRedirectURI, err := url.Parse(rawRedirectURI) 41 if err != nil { 42 return nil, fmt.Errorf("failed to parse redirect uri") 43 } 44 if parsedRedirectURI.Scheme == "" || parsedRedirectURI.Host == "" || parsedRedirectURI.Path == "" { 45 return nil, fmt.Errorf("non compliant redirect uri") 46 } 47 return parsedRedirectURI, nil 48 } 49 50 // GetRedirectURI returns redirect_uri value from query parameters. 51 func GetRedirectURI(u *url.URL) *url.URL { 52 queryParams := u.Query() 53 if queryParams == nil { 54 return nil 55 } 56 rawRedirectURI := queryParams.Get("redirect_uri") 57 parsedRedirectURI, err := url.Parse(rawRedirectURI) 58 if err != nil { 59 return nil 60 } 61 if parsedRedirectURI.Scheme == "" || parsedRedirectURI.Host == "" || parsedRedirectURI.Path == "" { 62 return nil 63 } 64 return parsedRedirectURI 65 } 66 67 // GetRawRedirectURI returns raw redirect_uri value from query parameters. 68 func GetRawRedirectURI(u *url.URL) string { 69 queryParams := u.Query() 70 if queryParams == nil { 71 return "" 72 } 73 return queryParams.Get("redirect_uri") 74 } 75 76 // HasRedirectURI check whether URL has redirect_uri in query parameters. 77 func HasRedirectURI(u *url.URL) bool { 78 queryParams := u.Query() 79 if queryParams == nil { 80 return false 81 } 82 rawRedirectURI := queryParams.Get("redirect_uri") 83 if rawRedirectURI == "" { 84 return false 85 } 86 return true 87 }