1
0

router.go 2.5 KB

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