Newer
Older
)
var (
httpPort = flag.Int("http_port", 80, "HTTP port to serve on (defaults to 80)")
)
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
RefreshTokenIssuedAt string `json:"refresh_token_issued_at"`
IssueAt string `json:"issued_at"`
func main() {
// Parse the flags
flag.Parse()
mux := http.NewServeMux()
mux.HandleFunc("/auth_old", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- New auth request")
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Query received - ", query)
clientId := query.Get("client_id")
state := query.Get("state")
redirectUri := "https://oauth-proxy.wf.alpha.grandlyon.com/"
responseType := "code"
authReq := "https://gw.hml.api.enedis.fr/group/espace-particuliers/consentement-linky/oauth2/authorize?client_id="+ clientId +"&duration=P6M&redirect_uri="+ redirectUri +"&response_type="+ responseType +"&state="+ state
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Send request to auth endpoint", authReq)
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Endpoint response with status", response.Status)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
// Define the replyUri
referer := r.Header.Get("Referer")
replyUri := strings.Replace(referer, "home.", "", 1)
replyUri = replyUri + "accounts/enedis-konnector/redirect"
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Reply to - ", replyUri)
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Get the response body as a string
pageContent := string(contents)
// Find a substr
codeStartIndex := strings.Index(pageContent, "?code=")
if codeStartIndex == -1 {
fmt.Println("No code found")
}
codeStartIndex += 6
// Find the index of the closing tag
codeEndIndex := strings.Index(pageContent, "&state=")
if codeEndIndex == -1 {
fmt.Println("No closing tag for code found.")
}
stateStartIndex := strings.Index(pageContent, "&state=")
if stateStartIndex == -1 {
fmt.Println("No state found")
}
stateStartIndex += 7
stateEndIndex := strings.Index(pageContent, "&usage_point_id=")
if stateEndIndex == -1 {
fmt.Println("No closing tag for state found.")
}
usageStartIndex := strings.Index(pageContent, "&usage_point_id=")
if usageStartIndex == -1 {
fmt.Println("No usage found")
}
usageStartIndex += 16
usageEndIndex := strings.Index(pageContent, "&usage_point_id=")
if usageEndIndex == -1 {
fmt.Println("No closing tag for usage found.")
}
usageEndIndex += 30
pageCode := string([]byte(pageContent[codeStartIndex:codeEndIndex]))
pageState := string([]byte(pageContent[stateStartIndex:stateEndIndex]))
pageUsage := string([]byte(pageContent[usageStartIndex:usageEndIndex]))
// Print out the result
fmt.Printf("Page code: %s\n", pageCode)
fmt.Printf("Page state: %s\n", pageState)
fmt.Printf("Page usage: %s\n", pageUsage)
redir := replyUri + "?code=" + pageCode + "&state="+ pageState +"&usage_point_id=" + pageUsage
fmt.Println(redir)
http.Redirect(w, r, redir, 302)
}
})
mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- New auth request")
query := r.URL.Query()
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Query received - ", query)
clientId := query.Get("client_id")
state := query.Get("state")
redirectUri := "https://oauth-proxy.wf.alpha.grandlyon.com/"
responseType := "code"
authReq := "https://gw.hml.api.enedis.fr/group/espace-particuliers/consentement-linky/oauth2/authorize?client_id="+ clientId +"&duration=P6M&redirect_uri="+ redirectUri +"&response_type="+ responseType +"&state="+ state
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Send request to auth endpoint", authReq)
response, err := http.Get(authReq)
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Endpoint response with status", response.Status)
if err != nil {
fmt.Println(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
// Define the replyUri
replyUri := "https://oauth-proxy.wf.alpha.grandlyon.com/redirect"
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Reply to - ", replyUri)
// Get the response body as a string
pageContentString := string(contents)
// Replace redirectUri by the host in the body
pageContentString = strings.ReplaceAll(pageContentString, redirectUri, replyUri)
fmt.Println(pageContentString)
// Convert string to byte for response writting
newPageContentByte := []byte(pageContentString)
// fmt.Println(r.Host)
if response.StatusCode >= 200 && response.StatusCode <= 299 {
w.Write(newPageContentByte)
} else {
http.Error(w, http.StatusText(response.StatusCode), response.StatusCode)
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- New redirect request")
query := r.URL.Query()
fmt.Println(query)
code := query.Get("code")
state := query.Get("state")
usagePointId := query.Get("usage_point_id")
// Get the redirect uri from the referer
referer := r.Header.Get("Referer")
redirectUri := ""
redirectStartIndex := strings.Index(referer, "&redirect_uri=")
if redirectStartIndex == -1 {
fmt.Println("No redirect found")
}
redirectStartIndex += len("&redirect_uri=")
splitRefer := string([]byte(referer[redirectStartIndex:len(referer)]))
fmt.Println(splitRefer)
redirectEndIndex := strings.Index(splitRefer, "&")
if redirectEndIndex == -1 {
redirectUri = splitRefer
}
redirectUri = string([]byte(splitRefer[0:redirectEndIndex]))
fmt.Println(redirectUri)
redir := "https://" + redirectUri + "/accounts/enedis-konnector/redirect?code=" + code + "&state="+ state +"&usage_point_id=" + usagePointId
fmt.Println(redir)
http.Redirect(w, r, redir, 302)
})
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- New token request")
query := r.URL.Query()
fmt.Println(query)
clientId := query.Get("client_id")
clientSecret := query.Get("client_secret")
code := query.Get("code")
grantType := query.Get("grant_type")
refreshToken := query.Get("refresh_token")
tokenUrl := "https://gw.hml.api.enedis.fr/v1/oauth2/token"
data := url.Values{}
data.Set("client_id", clientId)
data.Set("client_secret", clientSecret)
data.Set("code", code)
data.Set("grant_type", grantType)
if refreshToken != "" {
data.Set("refresh_token", refreshToken)
data.Set("grant_type", "refresh_token")
}
req, _ := http.NewRequest("POST", tokenUrl, strings.NewReader(data.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Send request to token endpoint", tokenUrl)
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Endpoint response with status", response.Status)
if err != nil {
fmt.Println(err)
} else {
defer response.Body.Close()
if response.StatusCode >= 200 && response.StatusCode <= 299 {
// Set Content-Type in response header
w.Header().Add("Content-Type", "application/json")
// Decode response Body using the defined type "TokenResponse"
data := TokenResponse{}
decodeError := json.NewDecoder(response.Body).Decode(&data)
if decodeError != nil {
http.Error(w, decodeError.Error(), 500)
return
}
// Response with json data
jsonError := json.NewEncoder(w).Encode(data)
if jsonError != nil {
http.Error(w, jsonError.Error(), 500)
return
}
} else {
http.Error(w, http.StatusText(response.StatusCode), response.StatusCode)
http.ListenAndServe(":"+strconv.Itoa(*httpPort), mux)
}