184 lines
4.6 KiB
Go
184 lines
4.6 KiB
Go
package server
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
"path/filepath"
|
|
"time"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"yoresee_dropbox/internal/store"
|
|
)
|
|
|
|
type createShareRequest struct {
|
|
Password string `json:"password"`
|
|
ExpiresInHours int `json:"expires_in_hours"`
|
|
}
|
|
|
|
func (s *Server) handleCreateShare(w http.ResponseWriter, r *http.Request) {
|
|
fileID := r.PathValue("id")
|
|
var req createShareRequest
|
|
json.NewDecoder(r.Body).Decode(&req)
|
|
|
|
token := generateShareToken()
|
|
share := &store.Share{
|
|
ID: generateUUID(),
|
|
FileID: fileID,
|
|
Token: token,
|
|
CreatedAt: time.Now().Unix(),
|
|
}
|
|
|
|
if req.Password != "" {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), 10)
|
|
if err != nil {
|
|
http.Error(w, "Failed to hash password", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
share.PasswordHash = string(hash)
|
|
}
|
|
|
|
if req.ExpiresInHours > 0 {
|
|
share.ExpiresAt = time.Now().Add(time.Duration(req.ExpiresInHours) * time.Hour).Unix()
|
|
}
|
|
|
|
if err := s.store.ShareCreate(share); err != nil {
|
|
http.Error(w, "Failed to create share", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusCreated)
|
|
json.NewEncoder(w).Encode(map[string]any{
|
|
"url": "/s/" + token,
|
|
"token": token,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleListShares(w http.ResponseWriter, r *http.Request) {
|
|
shares, err := s.store.ShareList()
|
|
if err != nil {
|
|
http.Error(w, "Failed to list", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"shares": shares})
|
|
}
|
|
|
|
func (s *Server) handleDeleteShare(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
if err := s.store.ShareDelete(id); err != nil {
|
|
http.Error(w, "Failed to delete", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (s *Server) handleShareAccess(w http.ResponseWriter, r *http.Request) {
|
|
token := r.PathValue("token")
|
|
share, err := s.store.ShareGetByToken(token)
|
|
if err != nil {
|
|
http.Error(w, "Not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
if share.ExpiresAt > 0 && time.Now().Unix() > share.ExpiresAt {
|
|
s.store.ShareDelete(share.ID)
|
|
http.Error(w, "Share expired", http.StatusGone)
|
|
return
|
|
}
|
|
|
|
if share.PasswordHash != "" {
|
|
cookie, err := r.Cookie("ydropbox_share_" + share.ID)
|
|
if err != nil || !s.verifyShareCookie(share.ID, cookie.Value) {
|
|
w.Header().Set("Content-Type", "text/html")
|
|
w.Write([]byte(`<!DOCTYPE html><html><body>
|
|
<form method="POST"><input type="password" name="password"><button>Submit</button></form>
|
|
</body></html>`))
|
|
return
|
|
}
|
|
}
|
|
|
|
s.serveSharedFile(w, r, share)
|
|
}
|
|
|
|
func (s *Server) handleSharePassword(w http.ResponseWriter, r *http.Request) {
|
|
token := r.PathValue("token")
|
|
share, err := s.store.ShareGetByToken(token)
|
|
if err != nil {
|
|
http.Error(w, "Not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
key := share.ID
|
|
s.mu.Lock()
|
|
if lockTime, locked := s.shareLockout[key]; locked && time.Now().Before(lockTime) {
|
|
s.mu.Unlock()
|
|
http.Error(w, "Too many attempts, locked for 60s", http.StatusForbidden)
|
|
return
|
|
}
|
|
s.mu.Unlock()
|
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
|
|
password := r.FormValue("password")
|
|
if err := bcrypt.CompareHashAndPassword([]byte(share.PasswordHash), []byte(password)); err != nil {
|
|
s.mu.Lock()
|
|
s.shareAttempts[key]++
|
|
if s.shareAttempts[key] >= 5 {
|
|
s.shareLockout[key] = time.Now().Add(60 * time.Second)
|
|
s.shareAttempts[key] = 0
|
|
}
|
|
s.mu.Unlock()
|
|
http.Error(w, "Wrong password", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
s.mu.Lock()
|
|
delete(s.shareAttempts, key)
|
|
delete(s.shareLockout, key)
|
|
s.mu.Unlock()
|
|
|
|
cookieVal := generateSessionID()
|
|
s.mu.Lock()
|
|
if s.shareSessions == nil {
|
|
s.shareSessions = make(map[string]string)
|
|
}
|
|
s.shareSessions[cookieVal] = share.ID
|
|
s.mu.Unlock()
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "ydropbox_share_" + share.ID,
|
|
Value: cookieVal,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: 3600,
|
|
})
|
|
|
|
http.Redirect(w, r, "/s/"+token, http.StatusFound)
|
|
}
|
|
|
|
func (s *Server) serveSharedFile(w http.ResponseWriter, r *http.Request, share *store.Share) {
|
|
f, err := s.store.FileGet(share.FileID)
|
|
if err != nil {
|
|
http.Error(w, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
path := filepath.Join(s.workspace, f.Dir, f.StorageName)
|
|
w.Header().Set("Content-Disposition", "attachment; filename="+f.OriginalName)
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
http.ServeFile(w, r, path)
|
|
}
|
|
|
|
func (s *Server) verifyShareCookie(shareID, cookieVal string) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.shareSessions[cookieVal] == shareID
|
|
}
|
|
|
|
func generateShareToken() string {
|
|
b := make([]byte, 24)
|
|
rand.Read(b)
|
|
return base64.URLEncoding.EncodeToString(b)
|
|
}
|