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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
|
package cmd
import (
"context"
"fmt"
"html/template"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
"github.com/Wacky404/rpserver/internal/auth/users"
"github.com/Wacky404/rpserver/internal/middleware"
"github.com/golang-jwt/jwt/v5"
)
var (
proxyCache = make(map[string]*httputil.ReverseProxy)
cacheMutex sync.RWMutex
)
func ExecuteServer(port string, cert string, key string) error {
mux := http.NewServeMux()
mux.Handle("/", middleware.Recover(http.HandlerFunc(serveLoginPage)))
mux.Handle("/login", middleware.Recover(http.HandlerFunc(serveLoginPage)))
mux.Handle("/auth/login", middleware.Recover(http.HandlerFunc(handleLogin)))
mux.Handle("/dashboard", middleware.Recover(middleware.Cookies(http.HandlerFunc(serveDashboard))))
// mux.Handle("/settings/generate", middleware.Recover(middleware.Cookies(http.HandlerFunc())))
mux.Handle("v1/proxy", middleware.Recover(middleware.JWT(http.HandlerFunc(handleProxy))))
mux.Handle("v1/status", middleware.Recover(http.HandlerFunc(handleStatus)))
err := http.ListenAndServeTLS(port, cert, key, mux)
return err
}
func serveDashboard(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/dash/dashboard.html"))
tmpl.Execute(w, nil)
}
func serveLoginPage(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/index.html"))
tmpl.Execute(w, nil)
}
/* This function doesn't have proper auth for login creds */
func handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
username := r.FormValue("username")
password := r.FormValue("password")
// pull this out into auth function
if username == "admin" && password == "password4321" {
newSID := users.SessionPrefix + users.GenID(16)
cookie := &http.Cookie{
Name: middleware.AdmitCookies[0],
Value: newSID,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
Expires: time.Now().Add(time.Minute * 5),
}
http.SetCookie(w, cookie)
w.Header().Set("HX-Redirect", "/dashboard")
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `Invalid username or password`)
}
func handleStatus(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "200 OK")
}
func handleProxy(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value("claims").(jwt.MapClaims)
if !ok {
http.Error(w, "Failed to get JWT claims", http.StatusInternalServerError)
return
}
userID := claims["sub"]
role := claims["role"]
fmt.Printf("%v, %v", userID, role)
backendURL, err := getBackendURL(r)
if err != nil {
http.Error(w, "Backend URL not provided", http.StatusBadRequest)
return
}
proxy := getOrCreateProxy(backendURL)
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
r = r.WithContext(ctx)
proxy.Director = func(req *http.Request) {
req.URL.Scheme = backendURL.Scheme
req.URL.Host = backendURL.Host
req.URL.Path = backendURL.Path
req.Host = backendURL.Host
}
done := make(chan struct{})
go func() {
proxy.ServeHTTP(w, r)
close(done)
}()
select {
case <-ctx.Done():
http.Error(w, "Request timed out", http.StatusGatewayTimeout)
log.Println("Request to", r.URL.Path, "timed out...balls")
case <-done:
}
}
func getBackendURL(r *http.Request) (*url.URL, error) {
backend := r.Header.Get("X-Backend-URL")
if backend == "" {
return nil, http.ErrNoLocation
}
return url.Parse(backend)
}
func getOrCreateProxy(target *url.URL) *httputil.ReverseProxy {
cacheMutex.RLock()
proxy, exists := proxyCache[target.String()]
cacheMutex.RUnlock()
if exists {
return proxy
}
cacheMutex.Lock()
defer cacheMutex.Unlock()
if proxy, exists = proxyCache[target.String()]; exists {
return proxy
}
proxy = httputil.NewSingleHostReverseProxy(target)
proxyCache[target.String()] = proxy
return proxy
}
|