filebrowser/http/share.go
Henrique Dias 12b2c21522 feat: v2 (#599)
Read https://github.com/filebrowser/filebrowser/pull/575.

Former-commit-id: 7aedcaaf72b863033e3f089d6df308d41a3fd00c [formerly bdbe4d49161b901c4adf9c245895a1be2d62e4a7] [formerly acfc1ec67c423e0b3e065a8c1f8897c5249af65b [formerly d309066def8319e9da89d00ca6463ec4aea62d34]]
Former-commit-id: 0c7d925a38a68ccabdf2c4bbd8c302ee89b93509 [formerly a6173925a1382955d93b334ded93f70d6dddd694]
Former-commit-id: e032e0804dd051df86f42962de2b39caec5318b7
2019-01-05 22:44:33 +00:00

108 lines
2.3 KiB
Go

package http
import (
"crypto/rand"
"encoding/base64"
"net/http"
"strconv"
"strings"
"time"
"github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/share"
)
func withPermShare(fn handleFunc) handleFunc {
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if !d.user.Perm.Share {
return http.StatusForbidden, nil
}
return fn(w, r, d)
})
}
var shareGetsHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
s, err := d.store.Share.Gets(r.URL.Path, d.user.ID)
if err == errors.ErrNotExist {
return renderJSON(w, r, []*share.Link{})
}
if err != nil {
return http.StatusInternalServerError, err
}
return renderJSON(w, r, s)
})
var shareDeleteHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
hash := strings.TrimSuffix(r.URL.Path, "/")
hash = strings.TrimPrefix(hash, "/")
if hash == "" {
return http.StatusBadRequest, nil
}
err := d.store.Share.Delete(hash)
return errToStatus(err), err
})
var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
var s *share.Link
rawExpire := r.URL.Query().Get("expires")
unit := r.URL.Query().Get("unit")
if rawExpire == "" {
var err error
s, err = d.store.Share.GetPermanent(r.URL.Path, d.user.ID)
if err == nil {
w.Write([]byte(d.settings.BaseURL + "/share/" + s.Hash))
return 0, nil
}
}
bytes := make([]byte, 6)
_, err := rand.Read(bytes)
if err != nil {
return http.StatusInternalServerError, err
}
str := base64.URLEncoding.EncodeToString(bytes)
var expire int64 = 0
if rawExpire != "" {
num, err := strconv.Atoi(rawExpire)
if err != nil {
return http.StatusInternalServerError, err
}
var add time.Duration
switch unit {
case "seconds":
add = time.Second * time.Duration(num)
case "minutes":
add = time.Minute * time.Duration(num)
case "days":
add = time.Hour * 24 * time.Duration(num)
default:
add = time.Hour * time.Duration(num)
}
expire = time.Now().Add(add).Unix()
}
s = &share.Link{
Path: r.URL.Path,
Hash: str,
Expire: expire,
UserID: d.user.ID,
}
if err := d.store.Share.Save(s); err != nil {
return http.StatusInternalServerError, err
}
return renderJSON(w, r, s)
})