2024-10-27 06:10:27 +01:00
|
|
|
package pkg
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
Copyright 2024 Jonas Kaninda.
|
|
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
|
You may get a copy of the License at
|
|
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*/
|
|
|
|
|
import (
|
2024-11-08 12:03:52 +01:00
|
|
|
"context"
|
|
|
|
|
"encoding/json"
|
2024-10-27 06:10:27 +01:00
|
|
|
"fmt"
|
2024-10-27 07:57:52 +01:00
|
|
|
"github.com/jedib0t/go-pretty/v6/table"
|
2024-11-08 12:03:52 +01:00
|
|
|
"golang.org/x/oauth2"
|
2024-11-17 03:56:47 +01:00
|
|
|
"io"
|
2024-10-28 02:26:02 +01:00
|
|
|
"net/http"
|
2024-10-27 06:10:27 +01:00
|
|
|
)
|
|
|
|
|
|
2024-11-05 10:34:47 +01:00
|
|
|
// printRoute prints routes
|
2024-10-27 07:57:52 +01:00
|
|
|
func printRoute(routes []Route) {
|
|
|
|
|
t := table.NewWriter()
|
2024-11-19 18:18:58 +01:00
|
|
|
t.AppendHeader(table.Row{"Name", "Path", "Rewrite", "Destination"})
|
2024-10-27 07:57:52 +01:00
|
|
|
for _, route := range routes {
|
2024-11-19 18:18:58 +01:00
|
|
|
if len(route.Backends) != 0 {
|
2024-11-11 08:50:34 +01:00
|
|
|
t.AppendRow(table.Row{route.Name, route.Path, route.Rewrite, fmt.Sprintf("backends: [%d]", len(route.Backends))})
|
|
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
t.AppendRow(table.Row{route.Name, route.Path, route.Rewrite, route.Destination})
|
|
|
|
|
}
|
2024-10-27 07:57:52 +01:00
|
|
|
}
|
|
|
|
|
fmt.Println(t.Render())
|
|
|
|
|
}
|
2024-11-05 10:34:47 +01:00
|
|
|
|
|
|
|
|
// getRealIP gets user real IP
|
2024-10-28 02:26:02 +01:00
|
|
|
func getRealIP(r *http.Request) string {
|
|
|
|
|
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
|
|
|
|
return ip
|
|
|
|
|
}
|
|
|
|
|
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
|
|
|
|
|
return ip
|
|
|
|
|
}
|
|
|
|
|
return r.RemoteAddr
|
|
|
|
|
}
|
2024-11-05 10:34:47 +01:00
|
|
|
|
2024-11-08 12:03:52 +01:00
|
|
|
func (oauth *OauthRulerMiddleware) getUserInfo(token *oauth2.Token) (UserInfo, error) {
|
|
|
|
|
oauthConfig := oauth2Config(oauth)
|
|
|
|
|
// Call the user info endpoint with the token
|
|
|
|
|
client := oauthConfig.Client(context.Background(), token)
|
|
|
|
|
resp, err := client.Get(oauth.Endpoint.UserInfoURL)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return UserInfo{}, err
|
|
|
|
|
}
|
2024-11-17 03:56:47 +01:00
|
|
|
defer func(Body io.ReadCloser) {
|
|
|
|
|
err := Body.Close()
|
|
|
|
|
if err != nil {
|
2024-11-17 05:28:27 +01:00
|
|
|
return
|
2024-11-17 03:56:47 +01:00
|
|
|
}
|
|
|
|
|
}(resp.Body)
|
2024-11-08 12:03:52 +01:00
|
|
|
|
|
|
|
|
// Parse the user info
|
|
|
|
|
var userInfo UserInfo
|
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
|
|
|
|
return UserInfo{}, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return userInfo, nil
|
|
|
|
|
}
|