router.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "path/filepath"
  7. "strings"
  8. "imuslab.com/zoraxy/mod/sshprox"
  9. )
  10. /*
  11. router.go
  12. This script holds the static resources router
  13. for the reverse proxy service
  14. */
  15. func FSHandler(handler http.Handler) http.Handler {
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. /*
  18. Development Mode Override
  19. => Web root is located in /
  20. */
  21. if development && strings.HasPrefix(r.URL.Path, "/web/") {
  22. u, _ := url.Parse(strings.TrimPrefix(r.URL.Path, "/web"))
  23. r.URL = u
  24. }
  25. /*
  26. Production Mode Override
  27. => Web root is located in /web
  28. */
  29. if !development && r.URL.Path == "/" {
  30. //Redirect to web UI
  31. http.Redirect(w, r, "/web/", http.StatusTemporaryRedirect)
  32. return
  33. }
  34. // Allow access to /script/*, /img/pubic/* and /login.html without authentication
  35. if strings.HasPrefix(r.URL.Path, ppf("/script/")) || strings.HasPrefix(r.URL.Path, ppf("/img/public/")) || r.URL.Path == ppf("/login.html") || r.URL.Path == ppf("/reset.html") || r.URL.Path == ppf("/favicon.png") {
  36. handler.ServeHTTP(w, r)
  37. return
  38. }
  39. // check authentication
  40. if !authAgent.CheckAuth(r) && requireAuth {
  41. http.Redirect(w, r, ppf("/login.html"), http.StatusTemporaryRedirect)
  42. return
  43. }
  44. //For WebSSH Routing
  45. //Example URL Path: /web.ssh/{{instance_uuid}}/*
  46. if strings.HasPrefix(r.URL.Path, "/web.ssh/") {
  47. requestPath := r.URL.Path
  48. parts := strings.Split(requestPath, "/")
  49. if !strings.HasSuffix(requestPath, "/") && len(parts) == 3 {
  50. http.Redirect(w, r, requestPath+"/", http.StatusTemporaryRedirect)
  51. return
  52. }
  53. if len(parts) > 2 {
  54. //Extract the instance ID from the request path
  55. instanceUUID := parts[2]
  56. fmt.Println(instanceUUID)
  57. //Rewrite the url so the proxy knows how to serve stuffs
  58. r.URL, _ = sshprox.RewriteURL("/web.ssh/"+instanceUUID, r.RequestURI)
  59. webSshManager.HandleHttpByInstanceId(instanceUUID, w, r)
  60. } else {
  61. fmt.Println(parts)
  62. http.Error(w, "Invalid Usage", http.StatusInternalServerError)
  63. }
  64. return
  65. }
  66. //Authenticated
  67. handler.ServeHTTP(w, r)
  68. })
  69. }
  70. // Production path fix wrapper. Fix the path on production or development environment
  71. func ppf(relativeFilepath string) string {
  72. if !development {
  73. return strings.ReplaceAll(filepath.Join("/web/", relativeFilepath), "\\", "/")
  74. }
  75. return relativeFilepath
  76. }