Browse Source

Tokenize file manager

Toby Chui 7 months ago
parent
commit
a48119f5ac

+ 14 - 6
mod/acme/autorenew.go

@@ -140,7 +140,7 @@ func (a *AutoRenewer) StopAutoRenewTicker() {
 // opr = setSelected -> Enter a list of file names (or matching rules) for auto renew
 // opr = setAuto -> Set to use auto detect certificates and renew
 func (a *AutoRenewer) HandleSetAutoRenewDomains(w http.ResponseWriter, r *http.Request) {
-	opr, err := utils.GetPara(r, "opr")
+	opr, err := utils.PostPara(r, "opr")
 	if err != nil {
 		utils.SendErrorResponse(w, "Operation not set")
 		return
@@ -170,6 +170,8 @@ func (a *AutoRenewer) HandleSetAutoRenewDomains(w http.ResponseWriter, r *http.R
 		a.RenewerConfig.RenewAll = true
 		a.saveRenewConfigToFile()
 		utils.SendOK(w)
+	} else {
+		utils.SendErrorResponse(w, "invalid operation given")
 	}
 
 }
@@ -213,19 +215,22 @@ func (a *AutoRenewer) HandleRenewNow(w http.ResponseWriter, r *http.Request) {
 	utils.SendJSONResponse(w, string(js))
 }
 
+// HandleAutoRenewEnable get and set the auto renew enable state
 func (a *AutoRenewer) HandleAutoRenewEnable(w http.ResponseWriter, r *http.Request) {
-	val, err := utils.PostPara(r, "enable")
-	if err != nil {
+	if r.Method == http.MethodGet {
 		js, _ := json.Marshal(a.RenewerConfig.Enabled)
 		utils.SendJSONResponse(w, string(js))
-	} else {
-		if val == "true" {
+	} else if r.Method == http.MethodPost {
+		val, err := utils.PostBool(r, "enable")
+		if err != nil {
+			utils.SendErrorResponse(w, "invalid or empty enable state")
+		}
+		if val {
 			//Check if the email is not empty
 			if a.RenewerConfig.Email == "" {
 				utils.SendErrorResponse(w, "Email is not set")
 				return
 			}
-
 			a.RenewerConfig.Enabled = true
 			a.saveRenewConfigToFile()
 			log.Println("[ACME] ACME auto renew enabled")
@@ -236,7 +241,10 @@ func (a *AutoRenewer) HandleAutoRenewEnable(w http.ResponseWriter, r *http.Reque
 			log.Println("[ACME] ACME auto renew disabled")
 			a.StopAutoRenewTicker()
 		}
+	} else {
+		http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
 	}
+
 }
 
 func (a *AutoRenewer) HandleACMEEmail(w http.ResponseWriter, r *http.Request) {

+ 3 - 3
mod/webserv/filemanager/filemanager.go

@@ -173,7 +173,7 @@ func (fm *FileManager) HandleDownload(w http.ResponseWriter, r *http.Request) {
 // HandleNewFolder creates a new folder in the specified directory
 func (fm *FileManager) HandleNewFolder(w http.ResponseWriter, r *http.Request) {
 	// Parse the directory name from the request
-	dirName, err := utils.GetPara(r, "path")
+	dirName, err := utils.PostPara(r, "path")
 	if err != nil {
 		utils.SendErrorResponse(w, "invalid directory name")
 		return
@@ -268,13 +268,13 @@ func (fm *FileManager) HandleFileCopy(w http.ResponseWriter, r *http.Request) {
 
 func (fm *FileManager) HandleFileMove(w http.ResponseWriter, r *http.Request) {
 	// Parse the source and destination paths from the request
-	srcPath, err := utils.GetPara(r, "srcpath")
+	srcPath, err := utils.PostPara(r, "srcpath")
 	if err != nil {
 		utils.SendErrorResponse(w, "invalid source path")
 		return
 	}
 
-	destPath, err := utils.GetPara(r, "destpath")
+	destPath, err := utils.PostPara(r, "destpath")
 	if err != nil {
 		utils.SendErrorResponse(w, "invalid destination path")
 		return

+ 2 - 2
reverseproxy.go

@@ -1100,13 +1100,13 @@ func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
 //List all the custom header defined in this proxy rule
 
 func HandleCustomHeaderList(w http.ResponseWriter, r *http.Request) {
-	epType, err := utils.PostPara(r, "type")
+	epType, err := utils.GetPara(r, "type")
 	if err != nil {
 		utils.SendErrorResponse(w, "endpoint type not defined")
 		return
 	}
 
-	domain, err := utils.PostPara(r, "domain")
+	domain, err := utils.GetPara(r, "domain")
 	if err != nil {
 		utils.SendErrorResponse(w, "domain or matching rule not defined")
 		return

+ 1 - 1
upstreams.go

@@ -19,7 +19,7 @@ import (
 
 // List upstreams from a endpoint
 func ReverseProxyUpstreamList(w http.ResponseWriter, r *http.Request) {
-	endpoint, err := utils.PostPara(r, "ep")
+	endpoint, err := utils.GetPara(r, "ep")
 	if err != nil {
 		utils.SendErrorResponse(w, "endpoint not defined")
 		return

+ 4 - 2
web/components/httprp.html

@@ -432,16 +432,18 @@
                 method: "POST",
                 data: {ep: epoint},
                 success: function(data){
-                    if (data.error != undefined){
+                    if (data.error == undefined){
                         listProxyEndpoints();
                         msgbox("Proxy Rule Deleted", true);
                         reloadUptimeList();
+                    }else{
+                        msgbox(data.error, false);
                     }
                 }
             })
         }
     }
-    
+
     
     /* button events */
     function editBasicAuthCredentials(uuid){

+ 2 - 1
web/script/utils.js

@@ -30,7 +30,8 @@ Object.defineProperty(String.prototype, 'capitalize', {
 
 //Add a new function to jquery for ajax override with csrf token injected
 $.cjax = function(payload){
-    if (payload.method == "POST" || payload.type == "POST"){
+    let requireTokenMethod = ["POST", "PUT", "DELETE"];;
+    if (requireTokenMethod.includes(payload.method) || requireTokenMethod.includes(payload.type)){
         //csrf token is required
         let csrfToken = document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content");
         payload.headers = {

+ 5 - 3
web/snippet/accessRuleEditor.html

@@ -3,9 +3,11 @@
   <head>
       <!-- Notes: This should be open in its original path-->
       <meta charset="utf-8">
+      <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
       <link rel="stylesheet" href="../script/semantic/semantic.min.css">
       <script src="../script/jquery-3.6.0.min.js"></script>
       <script src="../script/semantic/semantic.min.js"></script>
+      <script src="../script/utils.js"></script>
       <style>
         #refreshAccessRuleListBtn{
             position: absolute;
@@ -94,7 +96,7 @@
         $("#accessRuleForm input[name='accessRuleName']").val("");
         $("#accessRuleForm textarea[name='description']").val("");
 
-        $.ajax({
+        $.cjax({
             url: "/api/access/create",
             method: "POST",
             data: {
@@ -162,7 +164,7 @@
         console.log('Access Rule Name:', accessRuleName);
         console.log('Description:', description);
 
-        $.ajax({
+        $.cjax({
             url: "/api/access/update",
             method: "POST",
             data: {
@@ -238,7 +240,7 @@
         }
         let accessRuleName = $("#modifyRuleInfo input[name='accessRuleName']").val();
         if (confirm("Confirm removing access rule " + accessRuleName + "?")){
-            $.ajax({
+            $.cjax({
                 url: "/api/access/remove",
                 data: {
                     "id": accessRuleUUID

+ 29 - 22
web/snippet/acme.html

@@ -3,9 +3,11 @@
   <head>
       <!-- Notes: This should be open in its original path-->
       <meta charset="utf-8">
+      <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
       <link rel="stylesheet" href="../script/semantic/semantic.min.css">
       <script src="../script/jquery-3.6.0.min.js"></script>
       <script src="../script/semantic/semantic.min.js"></script>
+      <script src="../script/utils.js"></script>
       <style>
         .disabled.table{
           opacity: 0.5;
@@ -234,8 +236,9 @@
     initRenewerConfigFromFile();
 
     function saveEmailToConfig(btn){
-      $.ajax({
+      $.cjax({
         url: "/api/acme/autoRenew/email",
+        method: "POST",
         data: {set: $("#caRegisterEmail").val()},
         success: function(data){
           if (data.error != undefined){
@@ -256,27 +259,29 @@
 
     function toggleAutoRenew(){
       var enabled = $("#enableCertAutoRenew").parent().checkbox("is checked");
-      $.post("/api/acme/autoRenew/enable?enable=" + enabled, function(data){
-        if (data.error){
-          parent.msgbox(data.error, false, 5000);
-          if (enabled){
-            enableTrigerOnChangeEvent = false;
-            $("#enableCertAutoRenew").parent().checkbox("set unchecked");
-            enableTrigerOnChangeEvent = true;
-          }
-          if (parent && parent.setACMEEnableStates){
-            parent.setACMEEnableStates(!enabled);
-          }
-        }else{
-          $("#enableToggleSucc").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
-          if (parent && parent.setACMEEnableStates){
-            parent.setACMEEnableStates(enabled);
+      $.cjax({
+        url: "/api/acme/autoRenew/enable",
+        method: "POST",
+        data: {"enable": enabled},
+        success: function(data){
+          if (data.error){
+            parent.msgbox(data.error, false, 5000);
+            if (enabled){
+              enableTrigerOnChangeEvent = false;
+              $("#enableCertAutoRenew").parent().checkbox("set unchecked");
+              enableTrigerOnChangeEvent = true;
+            }
+            if (parent && parent.setACMEEnableStates){
+               parent.setACMEEnableStates(!enabled);
+            }
+          }else{
+            $("#enableToggleSucc").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
+            if (parent && parent.setACMEEnableStates){
+              parent.setACMEEnableStates(enabled);
+            }
           }
         }
       });
-
-      
-      
     }
 
     //Render the domains table that exists in this zoraxy host
@@ -630,7 +635,7 @@
         return;
       }
 
-      $.ajax({
+      $.cjax({
         url: "/api/acme/autoRenew/setDNS",
         method: "POST",
         data: {
@@ -843,8 +848,9 @@
     function saveAutoRenewPolicy(){
       let autoRenewAll = $("#renewAllSupported").parent().checkbox("is checked");
       if (autoRenewAll == true){
-        $.ajax({
+        $.cjax({
           url: "/api/acme/autoRenew/setDomains",
+          method: "POST",
           data: {opr: "setAuto"},
           success: function(data){
             parent.msgbox("Renew policy rule updated")
@@ -856,8 +862,9 @@
           checkedNames.push($(this).attr('name'));
         });
 
-        $.ajax({
+        $.cjax({
           url: "/api/acme/autoRenew/setDomains",
+          method: "POST",
           data: {opr: "setSelected", domains: JSON.stringify(checkedNames)},
           success: function(data){
             parent.msgbox("Renew policy rule updated")

+ 3 - 1
web/snippet/advanceStatsOprs.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
     </head>
     <body>
         <br>
@@ -46,7 +48,7 @@
 
             function handleResetStats(){
                 if (confirm("Confirm remove statistics from " + startDate + " to " + endDate +"?")){
-                    $.ajax({
+                    $.cjax({
                         url: "/api/analytic/resetRange?start=" + startDate + "&end=" + endDate,
                         method: "DELETE",
                         success: function(data){

+ 4 - 2
web/snippet/aliasEditor.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
     </head>
     <body>
         <br>
@@ -71,7 +73,7 @@
             }
 
             function initAliasNames(){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/detail",
                     method: "POST",
                     data: {
@@ -130,7 +132,7 @@
             }
 
             function saveCurrentAliasList(callback=undefined){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/setAlias",
                     method: "POST",
                     data:{

+ 5 - 3
web/snippet/basicAuthEditor.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
     </head>
     <body>
         <br>
@@ -174,7 +176,7 @@
                     parent.msgbox("Matching prefix cannot be empty!", false, 5000);
                     return;
                 }
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/auth/exceptions/add",
                     data:{
                         ep: editingEndpoint.ep,
@@ -195,7 +197,7 @@
 
             function removeExceptionPath(object){
                 let matchingPrefix = $(object).attr("prefix");
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/auth/exceptions/delete",
                     data:{
                         ep: editingEndpoint.ep,
@@ -290,7 +292,7 @@
             }
 
             function saveCredentials(){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/updateCredentials",
                     method: "POST",
                     data: {

+ 16 - 13
web/snippet/configTools.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
     </head>
     <body>
         <br>
@@ -70,10 +72,10 @@
                 }
             }
 
-            document.getElementById("uploadForm").addEventListener("submit", function(event) {
+            $("#uploadForm").submit(function(event) {
                 event.preventDefault(); // Prevent the form from submitting normally
 
-                var fileInput = document.getElementById("fileInput");
+                var fileInput = $("#fileInput")[0];
                 var file = fileInput.files[0];
                 if (!file) {
                     alert("Missing file.");
@@ -83,18 +85,19 @@
                 var formData = new FormData();
                 formData.append("file", file);
 
-                var xhr = new XMLHttpRequest();
-                xhr.open("POST", "/api/conf/import", true);
-                xhr.onreadystatechange = function() {
-                    if (xhr.readyState === XMLHttpRequest.DONE) {
-                        if (xhr.status === 200) {
-                            parent.msgbox("Config restore succeed. Restart Zoraxy to apply changes.")
-                        } else {
-                            parent.msgbox("Restore failed: " + xhr.responseText, false, 5000);
-                        }
+                $.cjax({
+                    url: "/api/conf/import",
+                    type: "POST",
+                    data: formData,
+                    processData: false, // Not to process the data
+                    contentType: false, // Not to set contentType
+                    success: function(response) {
+                        parent.msgbox("Config restore succeed. Restart Zoraxy to apply changes.");
+                    },
+                    error: function(xhr) {
+                        parent.msgbox("Restore failed: " + xhr.responseText, false, 5000);
                     }
-                };
-                xhr.send(formData);
+                });
             });
         </script>
     </body>

+ 15 - 13
web/snippet/customHeaders.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
         <style>
             .ui.tabular.menu .item.narrowpadding{
                 padding: 0.6em !important;
@@ -92,9 +94,6 @@
                         </div>
                         <div class="content">
                             <br>
-                            <div class="ui yellow message">
-                                <p><i class="exclamation triangle icon"></i>Settings in this section are for advanced users. Invalid settings might cause werid, unexpected behavior.</p>
-                            </div>
                             <div class="ui container">
                                 <h4>Overwrite Host Header</h4>
                                 <p>Manual override the automatic "Host" header rewrite logic. Leave empty for automatic.</p>
@@ -112,7 +111,9 @@
                                     <label>Remove Hop-by-hop Header<br>
                                     <small>This should be ON by default</small></label>
                                 </div>
-                                <div class="ui divider"></div>
+                                <div class="ui yellow message">
+                                    <p><i class="exclamation triangle icon"></i>Settings in this section are for advanced users. Invalid settings might cause werid, unexpected behavior.</p>
+                                </div>
                             </div>
                         </div>
                     </div>
@@ -247,8 +248,9 @@
                     }
                 }
 
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/header/add",
+                    method: "POST",
                     data: {
                         "type": getHeaderEditMode(),
                         "domain": editingEndpoint.ep,
@@ -279,10 +281,10 @@
             }
 
             function deleteCustomHeader(name){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/header/remove",
+                    method: "POST",
                     data: {
-                        //"type": editingEndpoint.ept,
                         "domain": editingEndpoint.ep,
                         "name": name,
                     },
@@ -299,6 +301,7 @@
                 $("#headerTable").html(`<tr><td colspan="3"><i class="ui loading spinner icon"></i> Loading</td></tr>`);
                 $.ajax({
                     url: "/api/proxy/header/list",
+                    method: "GET",
                     data: {
                         "type": editingEndpoint.ept,
                         "domain": editingEndpoint.ep,
@@ -307,7 +310,6 @@
                         if (data.error != undefined){
                             alert(data.error);
                         }else{
-                           
                             $("#headerTable").html("");
                             data.forEach(header => {
                                 let editModeIcon = header.IsRemove?`<i class="ui red times circle icon"></i>`:`<i class="ui green add circle icon"></i>`;
@@ -351,7 +353,7 @@
                     /* Bind events to toggles */
                     $("#enableHSTS").on("change", function(){
                         let HSTSEnabled = $("#enableHSTS")[0].checked;
-                        $.ajax({
+                        $.cjax({
                             url: "/api/proxy/header/handleHSTS",
                             method: "POST",
                             data: {
@@ -426,7 +428,7 @@
                             $("#permissionPolicyEditor").addClass("disabled");
                         }
 
-                        $.ajax({
+                        $.cjax({
                             url: "/api/proxy/header/handlePermissionPolicy",
                             method: "POST",
                             data: {
@@ -532,7 +534,7 @@
                 let permissionPolicy = generatePermissionPolicyObject();
                 let domain = editingEndpoint.ep;
 
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/header/handlePermissionPolicy",
                     method: "PUT",
                     data: {
@@ -576,7 +578,7 @@
 
             function updateManualHostOverwriteVal(callback=undefined){
                 let newHostname = $("#manualHostOverwrite").val().trim();
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/header/handleHostOverwrite",
                     method: "POST",
                     data: {
@@ -615,7 +617,7 @@
                         //Bind event to the checkbox
                         $("#removeHopByHop").on("change", function(evt){
                             let isChecked = $(this)[0].checked;
-                            $.ajax({
+                            $.cjax({
                                 url: "/api/proxy/header/handleHopByHop",
                                 method: "POST",
                                 data: {

+ 4 - 4
web/snippet/hostAccessEditor.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
         <style>
             .accessRule{
                 cursor: pointer;
@@ -124,12 +126,10 @@
                         }
                     }
                 });
-
-
             }
 
             initAccessRuleList(function(){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/detail",
                     method: "POST",
                     data: {"type":"host", "epname": editingEndpoint.ep },
@@ -160,7 +160,7 @@
             function applyChangeAndClose(){
                 let newAccessRuleID = $(".accessRule.active").attr("ruleid");
                 let targetEndpoint = editingEndpoint.ep;
-                $.ajax({
+                $.cjax({
                     url: "/api/access/attach",
                     method: "POST",
                     data: {

+ 2 - 0
web/snippet/placeholder.html

@@ -2,9 +2,11 @@
 <html>
     <head>
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
         <style>
             body{
                 height: 100%;

+ 11 - 7
web/snippet/upstreams.html

@@ -3,9 +3,11 @@
     <head>
         <!-- Notes: This should be open in its original path-->
         <meta charset="utf-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <link rel="stylesheet" href="../script/semantic/semantic.min.css">
         <script src="../script/jquery-3.6.0.min.js"></script>
         <script src="../script/semantic/semantic.min.js"></script>
+        <script src="../script/utils.js"></script>
         <style>
             .upstreamActions{
                 position: absolute;
@@ -133,7 +135,7 @@
             function initOriginList(){
                 $.ajax({
                     url: "/api/proxy/upstream/list",
-                    method: "POST",
+                    method: "GET",
                     data: {
                         "type":"host",
                         "ep": editingEndpoint.ep
@@ -284,8 +286,9 @@
                 }else{
                     //URL does not contains https or http protocol tag
                     //sniff header
-                    $.ajax({
+                    $.cjax({
                             url: "/api/proxy/tlscheck",
+                            method: "POST",
                             data: {url: targetDomain},
                             success: function(data){
                                 if (data.error != undefined){
@@ -313,7 +316,7 @@
                     return;
                 }
 
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/upstream/add",
                     method: "POST",
                     data:{
@@ -365,7 +368,7 @@
                 let newConfig = getUpstreamSettingFromDOM(targetDOM);
                 let isActive = $(targetDOM).find(".enableState")[0].checked;
                 console.log(newConfig);
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/upstream/update",
                     method: "POST",
                     data: {
@@ -418,8 +421,9 @@
                 }else{
                     //URL does not contains https or http protocol tag
                     //sniff header
-                    $.ajax({
+                    $.cjax({
                             url: "/api/proxy/tlscheck",
+                            method: "POST",
                             data: {url: targetDomain},
                             success: function(data){
                                 if (data.error != undefined){
@@ -460,7 +464,7 @@
 
             //Set a weight of a upstream
             function setUpstreamWeight(originIP, newWeight){
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/upstream/setPriority",
                     method: "POST",
                     data: {
@@ -489,7 +493,7 @@
                     return;
                 }
                 //Remove the upstream
-                $.ajax({
+                $.cjax({
                     url: "/api/proxy/upstream/remove",
                     method: "POST",
                     data: {

+ 31 - 26
web/tools/fs.html

@@ -2,12 +2,14 @@
     <head>
         <title>File Manager</title>
         <meta charset="UTF-8">
+        <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
         <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
         <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" />
         <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
         <link rel="stylesheet" href="fs.css">
+        <script src="../script/utils.js"></script>
         <script>
          
         </script>
@@ -199,7 +201,7 @@
                     let counter = $(".fileObject.selected").length;
                     $(".fileObject.selected").each(function(){
                         let thisFilepath = $(this).attr("filepath");
-                        $.ajax({
+                        $.cjax({
                             url: "/api/fs/del?target=" + thisFilepath,
                             method: "POST",
                             success: function(data){
@@ -241,22 +243,9 @@
                     let filename = $(this).attr("filename");
                     if (ftype != "folder"){
                         let ext = filepath.split(".").pop();
-                        if (isCodeFiles(ext)){
-                            editableCodeFiles.push({
-                                "filename": filename,
-                                "filepath": filepath
-                            });
-                        }else{
-                            openthis($(this), evt);
-                        }
-
+                        openthis($(this), evt);
                     }
                 });
-
-                if (editableCodeFiles.length > 0){
-                    let hash = encodeURIComponent(JSON.stringify(editableCodeFiles))
-                    window.open("notepad/index.html#" + hash);
-                }
             }
 
             function refresh(){
@@ -571,12 +560,19 @@
                     return;
                 }
 
-                $.post("/api/fs/newFolder?path=" + currentPath + folderName, function(data){
-                    if (data.error != undefined){
-                        msgbox(data.error, false);
-                    }else{
-                        msgbox("Folder Created");
-                        refresh();
+                $.cjax({
+                    url: "/api/fs/newFolder",
+                    method: "POST",
+                    data: {
+                        "path": currentPath + folderName,
+                    },
+                    success: function(data){
+                        if (data.error != undefined){
+                            msgbox(data.error, false);
+                        }else{
+                            msgbox("Folder Created");
+                            refresh();
+                        }
                     }
                 });
             }
@@ -597,8 +593,12 @@
                     if (newName && newName != oldName) {
                         // User entered a new name, perform renaming logic here
                         console.log(oldPath, currentPath + newName);
-                        $.ajax({
-                            url: "/api/fs/move?srcpath=" + oldPath + "&destpath=" + currentPath + newName,
+                        $.cjax({
+                            url: "/api/fs/move",
+                            data: {
+                                "srcpath": oldPath,
+                                "destpath": currentPath + newName
+                            },
                             method: "POST",
                             success: function(data){
                                 if (data.error != undefined){
@@ -826,6 +826,7 @@
                 ajax.addEventListener("error", errorHandler, false);
                 ajax.addEventListener("abort", abortHandler, false);
                 ajax.open("POST", "/api/fs/upload?dir=" + dir);
+                ajax.setRequestHeader("X-CSRF-Token", document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content"));
                 ajax.send(formdata);
             }
 
@@ -914,8 +915,12 @@
                         let filename = fileToPaste.filename;
                         let filepath = fileToPaste.filepath;
 
-                        $.ajax({
-                            url: "/api/fs/move?srcpath=" + filepath + "&destpath=" + currentPath + filename,
+                        $.cjax({
+                            url: "/api/fs/move",
+                            data:{
+                                "srcpath": filepath,
+                                "destpath": currentPath + filename,
+                            },
                             method: "POST",
                             success: function(data){
                                 if (data.error != undefined){
@@ -939,7 +944,7 @@
             function copyFirstItemInQueueUntilAllCopied(){
                 let file = copyPendingFiles.shift();
                 let startingDir = currentPath;
-                $.ajax({
+                $.cjax({
                     url: "/api/fs/copy",
                     method: "POST",
                     data: {