ServeStaticFiles configures HTTP handler that serves static files and dynamically patches index.html to embed CSRF token, etc.
(m *mux.Router, fs http.FileSystem)
| 785 | |
| 786 | // ServeStaticFiles configures HTTP handler that serves static files and dynamically patches index.html to embed CSRF token, etc. |
| 787 | func (s *Server) ServeStaticFiles(m *mux.Router, fs http.FileSystem) { |
| 788 | h := http.FileServer(fs) |
| 789 | |
| 790 | // read bytes from 'index.html'. |
| 791 | indexBytes := maybeReadIndexBytes(fs) |
| 792 | |
| 793 | m.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 794 | if s.isKnownUIRoute(r.URL.Path) { |
| 795 | r2 := new(http.Request) |
| 796 | *r2 = *r |
| 797 | r2.URL = new(url.URL) |
| 798 | *r2.URL = *r.URL |
| 799 | r2.URL.Path = "/" |
| 800 | r = r2 |
| 801 | } |
| 802 | |
| 803 | rc := s.captureRequestContext(w, r) |
| 804 | |
| 805 | //nolint:contextcheck |
| 806 | if !s.isAuthenticated(rc) { |
| 807 | return |
| 808 | } |
| 809 | |
| 810 | //nolint:contextcheck |
| 811 | if !requireUIUser(rc.req.Context(), rc) { |
| 812 | http.Error(w, `UI Access denied. See https://github.com/kopia/kopia/issues/880#issuecomment-798421751 for more information.`, http.StatusForbidden) |
| 813 | return |
| 814 | } |
| 815 | |
| 816 | if r.URL.Path == "/" && indexBytes != nil { |
| 817 | var sessionID string |
| 818 | |
| 819 | if cookie, err := r.Cookie(kopiaSessionCookie); err == nil { |
| 820 | // already in a session, likely a new tab was opened |
| 821 | sessionID = cookie.Value |
| 822 | } else { |
| 823 | sessionID = uuid.NewString() |
| 824 | |
| 825 | http.SetCookie(w, &http.Cookie{ |
| 826 | Name: kopiaSessionCookie, |
| 827 | Value: sessionID, |
| 828 | Path: "/", |
| 829 | }) |
| 830 | } |
| 831 | |
| 832 | http.ServeContent(w, r, "/", clock.Now(), bytes.NewReader(s.patchIndexBytes(sessionID, indexBytes))) |
| 833 | |
| 834 | return |
| 835 | } |
| 836 | |
| 837 | h.ServeHTTP(w, r) |
| 838 | }) |
| 839 | } |
| 840 | |
| 841 | // Options encompasses all API server options. |
| 842 | type Options struct { |
no test coverage detected