Răsfoiți Sursa

Replaced all login redirection with relative path

TC pushbot 5 4 ani în urmă
părinte
comite
77afdf38a5

+ 2 - 1
auth.go

@@ -6,6 +6,7 @@ import (
 	"net/http"
 
 	auth "imuslab.com/arozos/mod/auth"
+	"imuslab.com/arozos/mod/common"
 	prout "imuslab.com/arozos/mod/prouter"
 )
 
@@ -33,7 +34,7 @@ func AuthInit() {
 	authAgent = auth.NewAuthenticationAgent("ao_auth", []byte(*session_key), sysdb, *allow_public_registry, func(w http.ResponseWriter, r *http.Request) {
 		//Login Redirection Handler, redirect it login.system
 		w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
-		http.Redirect(w, r, "/login.system?redirect="+r.URL.Path, 307)
+		http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect="+r.URL.Path, 307)
 	})
 
 	if *allow_autologin == true {

+ 2 - 2
main.router.go

@@ -13,6 +13,7 @@ import (
 	"strconv"
 	"strings"
 
+	"imuslab.com/arozos/mod/common"
 	fs "imuslab.com/arozos/mod/filesystem"
 )
 
@@ -143,10 +144,9 @@ func mrouter(h http.Handler) http.Handler {
 				h.ServeHTTP(w, r)
 			} else {
 				//Other paths
-
 				//Rediect to login page
 				w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
-				http.Redirect(w, r, "/login.system?redirect="+r.URL.Path, 307)
+				http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect="+r.URL.Path, 307)
 			}
 
 		}

+ 14 - 0
mod/common/common.go

@@ -8,6 +8,7 @@ import (
 	"log"
 	"net/http"
 	"os"
+	"strings"
 	"time"
 )
 
@@ -117,3 +118,16 @@ func LoadImageAsBase64(filepath string) (string, error) {
 	encoded := base64.StdEncoding.EncodeToString(content)
 	return string(encoded), nil
 }
+
+//Use for redirections
+func ConstructRelativePathFromRequestURL(requestURI string, redirectionLocation string) string {
+	if strings.Count(requestURI, "/") == 1 {
+		//Already root level
+		return redirectionLocation
+	}
+	for i := 0; i < strings.Count(requestURI, "/")-1; i++ {
+		redirectionLocation = "../" + redirectionLocation
+	}
+
+	return redirectionLocation
+}

+ 136 - 0
mod/network/dynamicproxy/dynamicproxy.go

@@ -0,0 +1,136 @@
+package dynamicproxy
+
+import (
+	"log"
+	"net/http"
+	"net/url"
+	"strconv"
+	"sync"
+
+	"imuslab.com/arozos/mod/network/reverseproxy"
+)
+
+/*
+	Allow users to setup manual proxying for specific path
+
+*/
+type Router struct {
+	ListenPort     int
+	ProxyEndpoints *sync.Map
+	root           *ProxyEndpoint
+	mux            http.Handler
+	useTLS         bool
+}
+
+type RouterOption struct {
+	Port int
+}
+
+type ProxyEndpoint struct {
+	Root       string
+	Domain     string
+	RequireTLS bool
+	Proxy      *reverseproxy.ReverseProxy
+}
+
+type ProxyHandler struct {
+	Parent *Router
+}
+
+func NewDynamicProxy(port int) (*Router, error) {
+	newSyncMap := sync.Map{}
+	thisRouter := Router{
+		ListenPort:     port,
+		ProxyEndpoints: &newSyncMap,
+		useTLS:         false,
+	}
+
+	thisRouter.mux = &ProxyHandler{
+		Parent: &thisRouter,
+	}
+
+	return &thisRouter, nil
+}
+
+//Start the dynamic routing
+func (router *Router) StartProxyService() {
+	go func() {
+		err := http.ListenAndServe(":"+strconv.Itoa(router.ListenPort), router.mux)
+		log.Println("[DynamicProxy] " + err.Error())
+	}()
+}
+
+/*
+	Add an URL into a custom proxy services
+*/
+func (router *Router) AddProxyService(rootname string, domain string, requireTLS bool) error {
+	if domain[len(domain)-1:] == "/" {
+		domain = domain[:len(domain)-1]
+	}
+
+	webProxyEndpoint := domain
+	if requireTLS {
+		webProxyEndpoint = "https://" + webProxyEndpoint
+	} else {
+		webProxyEndpoint = "http://" + webProxyEndpoint
+	}
+	//Create a new proxy agent for this root
+	path, err := url.Parse(webProxyEndpoint)
+	if err != nil {
+		return err
+	}
+
+	proxy := reverseproxy.NewReverseProxy(path)
+
+	router.ProxyEndpoints.Store(rootname, &ProxyEndpoint{
+		Root:       rootname,
+		Domain:     domain,
+		RequireTLS: requireTLS,
+		Proxy:      proxy,
+	})
+	return nil
+}
+
+/*
+	Add an default router for the proxy server
+*/
+func (router *Router) SetRootProxy(proxyLocation string, requireTLS bool) error {
+	if proxyLocation[len(proxyLocation)-1:] == "/" {
+		proxyLocation = proxyLocation[:len(proxyLocation)-1]
+	}
+
+	webProxyEndpoint := proxyLocation
+	if requireTLS {
+		webProxyEndpoint = "https://" + webProxyEndpoint
+	} else {
+		webProxyEndpoint = "http://" + webProxyEndpoint
+	}
+	//Create a new proxy agent for this root
+	path, err := url.Parse(webProxyEndpoint)
+	if err != nil {
+		return err
+	}
+
+	proxy := reverseproxy.NewReverseProxy(path)
+
+	rootEndpoint := ProxyEndpoint{
+		Root:       "/",
+		Domain:     proxyLocation,
+		RequireTLS: requireTLS,
+		Proxy:      proxy,
+	}
+
+	router.root = &rootEndpoint
+	return nil
+}
+
+//Do all the main routing in here
+func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	targetProxyEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(r.RequestURI)
+	log.Println(targetProxyEndpoint)
+	if targetProxyEndpoint != nil {
+		h.proxyRequest(w, r, targetProxyEndpoint)
+	} else {
+		h.proxyRequest(w, r, h.Parent.root)
+	}
+}

+ 55 - 0
mod/network/dynamicproxy/proxyRequestHandler.go

@@ -0,0 +1,55 @@
+package dynamicproxy
+
+import (
+	"fmt"
+	"log"
+	"net/http"
+	"net/url"
+
+	"imuslab.com/arozos/mod/network/websocketproxy"
+)
+
+func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
+	var targetProxyEndpoint *ProxyEndpoint = nil
+	router.ProxyEndpoints.Range(func(key, value interface{}) bool {
+		rootname := key.(string)
+		if len(requestURI) >= len(rootname) && requestURI[:len(rootname)] == rootname {
+			thisProxyEndpoint := value.(*ProxyEndpoint)
+			targetProxyEndpoint = thisProxyEndpoint
+		}
+		return true
+	})
+
+	return targetProxyEndpoint
+}
+
+func (router *Router) rewriteURL(rooturl string, requestURL string) string {
+	if len(requestURL) > len(rooturl) {
+		return requestURL[len(rooturl):]
+	}
+	return ""
+}
+
+func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
+	rewriteURL := h.Parent.rewriteURL(target.Root, r.RequestURI)
+	fmt.Println("Rewrite URL", rewriteURL)
+	r.URL, _ = url.Parse(rewriteURL)
+	r.Header.Set("X-Forwarded-Host", r.Host)
+	if r.Header["Upgrade"] != nil && r.Header["Upgrade"][0] == "websocket" {
+		//Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
+		r.Header.Set("A-Upgrade", "websocket")
+		u, _ := url.Parse("ws://" + target.Domain + r.URL.String())
+		if target.RequireTLS {
+			u, _ = url.Parse("wss://localhost:" + target.Domain + r.URL.String())
+		}
+		wspHandler := websocketproxy.NewProxy(u)
+		wspHandler.ServeHTTP(w, r)
+		return
+	}
+
+	r.Host = r.URL.Host
+	err := target.Proxy.ServeHTTP(w, r)
+	if err != nil {
+		log.Println(err.Error())
+	}
+}

+ 5 - 4
mod/share/share.go

@@ -25,6 +25,7 @@ import (
 
 	uuid "github.com/satori/go.uuid"
 	"imuslab.com/arozos/mod/auth"
+	"imuslab.com/arozos/mod/common"
 	"imuslab.com/arozos/mod/database"
 	filesystem "imuslab.com/arozos/mod/filesystem"
 	"imuslab.com/arozos/mod/user"
@@ -121,7 +122,7 @@ func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
 					w.WriteHeader(http.StatusUnauthorized)
 					w.Write([]byte("401 - Unauthorized"))
 				} else {
-					http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
+					http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share?id="+id, 307)
 				}
 				return
 			} else {
@@ -134,7 +135,7 @@ func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
 					w.WriteHeader(http.StatusUnauthorized)
 					w.Write([]byte("401 - Unauthorized"))
 				} else {
-					http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
+					http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share?id="+id, 307)
 				}
 				return
 			}
@@ -174,7 +175,7 @@ func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
 					w.WriteHeader(http.StatusUnauthorized)
 					w.Write([]byte("401 - Unauthorized"))
 				} else {
-					http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
+					http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share?id="+id, 307)
 				}
 				return
 			}
@@ -200,7 +201,7 @@ func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
 					w.WriteHeader(http.StatusUnauthorized)
 					w.Write([]byte("401 - Unauthorized"))
 				} else {
-					http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
+					http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share?id="+id, 307)
 				}
 				return
 			}

+ 0 - 15
mod/subservice/subservice.go

@@ -91,21 +91,6 @@ func (sr *SubServiceRouter) Launch(servicePath string, startupMode bool) error {
 		binaryExecPath = binaryExecPath + "_" + runtime.GOOS + "_" + runtime.GOARCH
 	}
 
-	/*if runtime.GOOS == "linux" {
-		if runtime.GOARCH == "arm" {
-			binaryExecPath = binaryExecPath + "_linux_arm"
-		} else if runtime.GOARCH == "arm64" {
-			binaryExecPath = binaryExecPath + "_linux_arm64"
-		} else if runtime.GOARCH == "386" {
-			binaryExecPath = binaryExecPath + "_linux_386"
-		} else if runtime.GOARCH == "amd64" {
-			binaryExecPath = binaryExecPath + "_linux_amd64"
-		}
-	} else if runtime.GOOS == "darwin" {
-
-	}
-	*/
-
 	if runtime.GOOS == "windows" && !fileExists(servicePath+"/"+binaryExecPath) {
 		if startupMode {
 			log.Println("Failed to load subservice: "+serviceRoot, " File not exists "+servicePath+"/"+binaryExecPath+". Skipping this service")

+ 26 - 0
reverseproxy.go

@@ -0,0 +1,26 @@
+package main
+
+import (
+	"log"
+
+	"imuslab.com/arozos/mod/network/dynamicproxy"
+)
+
+var (
+	dynamicProxyRouter *dynamicproxy.Router
+)
+
+//Add user customizable reverse proxy
+func ReverseProxtInit() {
+	return
+	dynamicProxyRouter, err := dynamicproxy.NewDynamicProxy(80)
+	if err != nil {
+		log.Println(err.Error())
+		return
+	}
+	dynamicProxyRouter.SetRootProxy("localhost:8080/www/TC/", false)
+	dynamicProxyRouter.AddProxyService("/imus", "192.168.0.107:8080", false)
+	dynamicProxyRouter.AddProxyService("/hkwtc", "hkwtc.org:9091", false)
+	dynamicProxyRouter.StartProxyService()
+	log.Println("Dynamic Proxy service started")
+}

+ 3 - 2
startup.go

@@ -58,8 +58,9 @@ func RunStartup() {
 	//StorageDaemonInit() //Start File System handler daemon (for backup and other sync process)
 
 	//8 Start AGI and Subservice modules (Must start after module)
-	AGIInit()        //ArOZ Javascript Gateway Interface, must start after fs
-	SubserviceInit() //Subservice Handler
+	AGIInit()          //ArOZ Javascript Gateway Interface, must start after fs
+	SubserviceInit()   //Subservice Handler
+	ReverseProxtInit() //Start Dynamic Reverse Proxy
 
 	//9. Initiate System Settings Handlers
 	SystemSettingInit()       //Start System Setting Core