75 lines
1.4 KiB
Go
75 lines
1.4 KiB
Go
|
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
|
||
|
}
|