summaryrefslogtreecommitdiff
path: root/pkg/idec/files.go
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/idec/files.go')
-rw-r--r--pkg/idec/files.go74
1 files changed, 74 insertions, 0 deletions
diff --git a/pkg/idec/files.go b/pkg/idec/files.go
new file mode 100644
index 0000000..8fd73b4
--- /dev/null
+++ b/pkg/idec/files.go
@@ -0,0 +1,74 @@
+package idec
+
+import (
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "gitrepo.ru/neonxp/idecnode/pkg/model"
+)
+
+var ErrFileNotAllowed = errors.New("file not allowed")
+
+func (i *IDEC) FilesList(pauth string) ([]model.File, error) {
+ fileDirs := i.allowedDirs(pauth)
+ res := []model.File{}
+ for _, dir := range fileDirs {
+ files, err := filepath.Glob(dir + "/*")
+ if err != nil {
+ return nil, err
+ }
+ for _, f := range files {
+ fi, err := os.Stat(f)
+ if err != nil {
+ return nil, err
+ }
+
+ res = append(res, model.File{
+ Name: fi.Name(),
+ Size: fi.Size(),
+ FullName: strings.TrimPrefix(f, i.config.FilesDirectory),
+ })
+ }
+ }
+
+ return res, nil
+}
+
+func (i *IDEC) GetFile(pauth string, path string, w io.Writer) error {
+ file := filepath.Clean(filepath.Join(i.config.FilesDirectory, path))
+ allowed := false
+ allowedDirs := i.allowedDirs(pauth)
+ for _, dir := range allowedDirs {
+ if filepath.HasPrefix(file, dir) {
+ allowed = true
+ }
+ }
+ if !allowed {
+ return ErrFileNotAllowed
+ }
+
+ fp, err := os.Open(file)
+ if err != nil {
+ return err
+ }
+ defer fp.Close()
+
+ _, err = io.Copy(w, fp)
+
+ return err
+}
+
+func (i *IDEC) allowedDirs(pauth string) []string {
+ fileDirs := []string{
+ filepath.Join(i.config.FilesDirectory, "pub"),
+ }
+ if pauth != "" {
+ if _, err := i.GetPointByAuth(pauth); err == nil {
+ fileDirs = append(fileDirs, filepath.Join(i.config.FilesDirectory, "priv"))
+ }
+ }
+ return fileDirs
+}