-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (81 loc) · 2.63 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
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/mittwald/mstudio-ext-proxy/pkg/bootstrap"
"github.com/mittwald/mstudio-ext-proxy/pkg/controller"
"github.com/mittwald/mstudio-ext-proxy/pkg/persistence"
"github.com/mittwald/mstudio-ext-proxy/pkg/proxy"
"log/slog"
"net/http"
"os"
"strconv"
"strings"
)
func main() {
config := bootstrap.ConfigFromEnv()
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
mongoClient := bootstrap.ConnectToMongodb(config.MongoDBURI)
mongoDatabase := mongoClient.Database("mstudio_ext")
mittwaldClient := bootstrap.BuildMittwaldAPIClientFromConfig(config, logger)
authOptions := bootstrap.BuildAuthenticationOptions(config)
instanceRepository := persistence.NewMongoExtensionInstanceRepository(mongoDatabase.Collection("instances"))
sessionRepository := persistence.MustNewMongoSessionRepository(mongoDatabase.Collection("sessions"))
webhookCtrl := controller.WebhookController{
ExtensionInstanceRepository: instanceRepository,
WebhookVerifier: bootstrap.BuildWebhookVerifier(mittwaldClient),
Logger: logger,
}
authCtrl := controller.UserAuthenticationController{
Client: mittwaldClient,
SessionRepository: sessionRepository,
InstanceRepository: instanceRepository,
Development: config.Context == "dev",
AuthenticationOptions: authOptions,
}
r := gin.New()
r.LoadHTMLGlob("templates/*")
rm := r.Group("/mstudio")
rm.POST("/webhooks", webhookCtrl.HandleWebhookRequest)
rm.GET("/auth/oneclick", authCtrl.HandleAuthenticationRequest)
rm.GET("/auth/fake", authCtrl.HandleFakeAuthentication)
if authOptions.StaticPassword != "" {
rm.Any("/auth/password", authCtrl.HandlePasswordAuthentication)
}
mux := http.NewServeMux()
mux.Handle("/mstudio/", r)
for prefix, proxyConfig := range config.Upstreams {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
proxyHandler := proxy.Handler{
HTTPClient: http.DefaultClient,
SessionRepository: sessionRepository,
Configuration: proxyConfig,
Logger: logger,
AuthenticationOptions: authOptions,
}
mux.Handle(prefix, &proxyHandler)
}
s := http.Server{
Handler: mux,
Addr: getListenAddr(),
}
logger.Info("listening", "server.addr", s.Addr)
if err := s.ListenAndServe(); err != nil {
panic(err)
}
}
func getListenPort() int64 {
if p := os.Getenv("PORT"); p != "" {
pi, err := strconv.ParseInt(p, 10, 32)
if err != nil {
panic(err)
}
return pi
}
return 8000
}
func getListenAddr() string {
return fmt.Sprintf(":%d", getListenPort())
}