diff --git a/internal/server/share.go b/internal/server/share.go new file mode 100644 index 0000000..d5ad892 --- /dev/null +++ b/internal/server/share.go @@ -0,0 +1,160 @@ +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(` +
+ `)) + 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 + } + + password := r.FormValue("password") + if err := bcrypt.CompareHashAndPassword([]byte(share.PasswordHash), []byte(password)); err != nil { + http.Error(w, "Wrong password", http.StatusForbidden) + return + } + + 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) +} diff --git a/internal/server/share_test.go b/internal/server/share_test.go new file mode 100644 index 0000000..a0d119d --- /dev/null +++ b/internal/server/share_test.go @@ -0,0 +1,100 @@ +package server + +import ( + "bytes" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "yoresee_dropbox/internal/store" +) + +func TestCreateShare(t *testing.T) { + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + os.MkdirAll(filepath.Join(workspace, "inbox"), 0755) + + s, _ := store.Open(filepath.Join(dir, "test.db")) + defer s.Close() + + f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 100, CreatedAt: 1750000000} + s.FileCreate(f) + + srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)} + + body := bytes.NewBufferString(`{"file_id":"file-1"}`) + req := httptest.NewRequest("POST", "/api/files/file-1/share", body) + req.Header.Set("Content-Type", "application/json") + req.AddCookie(&http.Cookie{Name: "ydropbox_session", Value: "valid"}) + srv.sessions["valid"] = 1 + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/files/{id}/share", srv.handleCreateShare) + + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + + if w.Code != http.StatusCreated { + t.Errorf("Status = %d, want %d", w.Code, http.StatusCreated) + } +} + +func TestShareAccessNoPassword(t *testing.T) { + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + os.MkdirAll(filepath.Join(workspace, "inbox"), 0755) + os.WriteFile(filepath.Join(workspace, "inbox", "uuid-1"), []byte("content"), 0644) + + s, _ := store.Open(filepath.Join(dir, "test.db")) + defer s.Close() + + f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 7, CreatedAt: 1750000000} + s.FileCreate(f) + + sh := &store.Share{ID: "share-1", FileID: "file-1", Token: "tok-abc", CreatedAt: 1750000000} + s.ShareCreate(sh) + + srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)} + + req := httptest.NewRequest("GET", "/s/tok-abc", nil) + + mux := http.NewServeMux() + mux.HandleFunc("GET /s/{token}", srv.handleShareAccess) + + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Errorf("Status = %d, want %d", w.Code, http.StatusOK) + } +} + +func TestShareAccessExpired(t *testing.T) { + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + os.MkdirAll(filepath.Join(workspace, "inbox"), 0755) + + s, _ := store.Open(filepath.Join(dir, "test.db")) + defer s.Close() + + f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 7, CreatedAt: 1750000000} + s.FileCreate(f) + + sh := &store.Share{ID: "share-1", FileID: "file-1", Token: "tok-exp", ExpiresAt: 1, CreatedAt: 1750000000} + s.ShareCreate(sh) + + srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)} + + req := httptest.NewRequest("GET", "/s/tok-exp", nil) + + mux := http.NewServeMux() + mux.HandleFunc("GET /s/{token}", srv.handleShareAccess) + + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + + if w.Code != http.StatusGone { + t.Errorf("Status = %d, want %d", w.Code, http.StatusGone) + } +}