-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (99 loc) · 2.46 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
package main
import (
"encoding/json"
"fmt"
"github.com/fatih/color"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/gume1a/oauthproxy/internal/config"
"github.com/gume1a/oauthproxy/internal/registry"
"github.com/gume1a/oauthproxy/pkg/identity"
"github.com/joho/godotenv"
"io"
"log"
"net/http"
"os"
)
func main() {
// Read the ascii art and print it.
f, _ := os.Open("./assets/terminal/logo_banner.txt")
_, _ = io.Copy(os.Stdout, f)
_ = f.Close()
fmt.Print("\n\n")
// Router configuration.
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Load the .env file.
err := godotenv.Load()
if err != nil {
if !os.IsNotExist(err) {
log.Fatalf("%s failed reading .env: %v",
color.RedString("INIT"),
err,
)
}
} else {
log.Printf("%s .env loaded",
color.BlueString("INIT"),
)
}
// Get the configuration.
cfg := config.Get()
// HTTP server configuration.
addr := fmt.Sprintf("%s:%v", cfg.Host, cfg.Port)
providers, err := config.GetProviders()
if err != nil {
log.Fatalf("%s failed getting providers: %v",
color.RedString("INIT"),
err,
)
}
// Get the registry.
registrar := registry.NewRegistry(providers)
r.Route("/oauth", func(r chi.Router) {
r.Post("/{provider_id}", func(rw http.ResponseWriter, req *http.Request) {
// Get the provider id from the path.
providerId := identity.ProviderId(chi.URLParam(req, "provider_id"))
// Forward the request to the right provider.
registrar.ProxyServeHTTP(providerId, rw, req)
})
})
// Get the supported providers.
r.Get("/supported", func(rw http.ResponseWriter, req *http.Request) {
providers := registrar.Providers()
enc := json.NewEncoder(rw)
if err := enc.Encode(providers); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
}
})
fs := http.FileServer(http.Dir("./assets/static"))
r.Handle("/*", fs)
serverChan := make(chan error)
// Start the non-blocking server.
go func() {
log.Printf("%s %v",
color.BlueString("PROVIDERS"),
registrar.Providers(),
)
log.Printf("%s starting listening on %v",
color.BlueString("SERVER"),
color.CyanString("http://"+addr),
)
serverChan <- http.ListenAndServe(addr, r)
log.Printf("%s %s",
color.RedString("SERVER"),
"exited",
)
}()
// Wait for the server error.
select {
case err := <-serverChan:
log.Printf("%s %v\n",
color.RedString("SERVER"),
err,
)
}
}