github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/routes/panel/backups.go (about)

     1  package panel
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net/http"
     6  	"os"
     7  	"path/filepath"
     8  	"strconv"
     9  
    10  	c "github.com/Azareal/Gosora/common"
    11  )
    12  
    13  func Backups(w http.ResponseWriter, r *http.Request, u *c.User, backupURL string) c.RouteError {
    14  	basePage, ferr := buildBasePage(w, r, u, "backups", "backups")
    15  	if ferr != nil {
    16  		return ferr
    17  	}
    18  
    19  	if backupURL != "" {
    20  		// We don't want them trying to break out of this directory, it shouldn't hurt since it's a super admin, but it's always good to practice good security hygiene, especially if this is one of many instances on a managed server not controlled by the superadmin/s
    21  		backupURL = c.Stripslashes(backupURL)
    22  
    23  		ext := filepath.Ext("./backups/" + backupURL)
    24  		if ext != ".sql" && ext != ".zip" {
    25  			return c.NotFound(w, r, basePage.Header)
    26  		}
    27  		info, err := os.Stat("./backups/" + backupURL)
    28  		if err != nil {
    29  			return c.NotFound(w, r, basePage.Header)
    30  		}
    31  
    32  		h := w.Header()
    33  		h.Set("Content-Length", strconv.FormatInt(info.Size(), 10))
    34  		if ext == ".sql" {
    35  			// TODO: Change the served filename to gosora_backup_%timestamp%.sql, the time the file was generated, not when it was modified aka what the name of it should be
    36  			h.Set("Content-Disposition", "attachment; filename=gosora_backup.sql")
    37  			h.Set("Content-Type", "application/sql")
    38  		} else {
    39  			// TODO: Change the served filename to gosora_backup_%timestamp%.zip, the time the file was generated, not when it was modified aka what the name of it should be
    40  			h.Set("Content-Disposition", "attachment; filename=gosora_backup.zip")
    41  			h.Set("Content-Type", "application/zip")
    42  		}
    43  		// TODO: Fix the problem where non-existent files aren't greeted with custom 404s on ServeFile()'s side
    44  		http.ServeFile(w, r, "./backups/"+backupURL)
    45  		err = c.AdminLogs.Create("download", 0, "backup", u.GetIP(), u.ID)
    46  		if err != nil {
    47  			return c.InternalError(err, w, r)
    48  		}
    49  		return nil
    50  	}
    51  
    52  	var backupList []c.BackupItem
    53  	backupFiles, err := ioutil.ReadDir("./backups")
    54  	if err != nil {
    55  		return c.InternalError(err, w, r)
    56  	}
    57  	for _, backupFile := range backupFiles {
    58  		ext := filepath.Ext(backupFile.Name())
    59  		if ext != ".sql" {
    60  			continue
    61  		}
    62  		backupList = append(backupList, c.BackupItem{backupFile.Name(), backupFile.ModTime()})
    63  	}
    64  
    65  	return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage, "", "", "panel_backups", c.PanelBackupPage{basePage, backupList}})
    66  }