Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
ed4a10c966 | |||
ff8c6aca64 |
18
api/http.go
18
api/http.go
@@ -49,6 +49,7 @@ func NewHTTPServer(cfg *gpaste.ServerConfig) *HTTPServer {
|
||||
r.Get("/", srv.HandlerIndex)
|
||||
r.Post("/api/file", srv.HandlerAPIFilePost)
|
||||
r.Get("/api/file/{id}", srv.HandlerAPIFileGet)
|
||||
r.Delete("/api/file/{id}", srv.HandlerAPIFileDelete)
|
||||
r.Post("/api/login", srv.HandlerAPILogin)
|
||||
r.Post("/api/user", srv.HandlerAPIUserCreate)
|
||||
srv.Handler = r
|
||||
@@ -117,6 +118,23 @@ func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *HTTPServer) HandlerAPIFileDelete(w http.ResponseWriter, r *http.Request) {
|
||||
// TODO: Require auth
|
||||
id := chi.URLParam(r, "id")
|
||||
if id == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err := s.Files.Delete(id)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
reqID := middleware.GetReqID(r.Context())
|
||||
s.Logger.Infow("Deleted file", "id", id, "req_id", reqID)
|
||||
}
|
||||
|
||||
func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetReqID(r.Context())
|
||||
|
||||
|
@@ -8,11 +8,15 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.t-juice.club/torjus/gpaste"
|
||||
"git.t-juice.club/torjus/gpaste/api"
|
||||
"git.t-juice.club/torjus/gpaste/files"
|
||||
"git.t-juice.club/torjus/gpaste/users"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestHandlers(t *testing.T) {
|
||||
@@ -99,6 +103,42 @@ func TestHandlers(t *testing.T) {
|
||||
}
|
||||
})
|
||||
})
|
||||
t.Run("HandlerAPIFileDelete", func(t *testing.T) {
|
||||
cfg := &gpaste.ServerConfig{
|
||||
SigningSecret: "abc123",
|
||||
Store: &gpaste.ServerStoreConfig{
|
||||
Type: "memory",
|
||||
},
|
||||
URL: "http://localhost:8080",
|
||||
}
|
||||
hs := api.NewHTTPServer(cfg)
|
||||
fileBody := io.NopCloser(strings.NewReader("roflcopter"))
|
||||
file := &files.File{
|
||||
ID: uuid.NewString(),
|
||||
OriginalFilename: "testpls.txt",
|
||||
MaxViews: 9,
|
||||
ExpiresOn: time.Now().Add(10 * time.Hour),
|
||||
Body: fileBody,
|
||||
}
|
||||
|
||||
if err := hs.Files.Store(file); err != nil {
|
||||
t.Fatalf("Error storing file: %s", err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
url := fmt.Sprintf("/api/file/%s", file.ID)
|
||||
req := httptest.NewRequest(http.MethodDelete, url, nil)
|
||||
hs.Handler.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Result().StatusCode != http.StatusOK {
|
||||
t.Fatalf("Delete returned wrong status: %s", rr.Result().Status)
|
||||
}
|
||||
|
||||
if _, err := hs.Files.Get(file.ID); err == nil {
|
||||
t.Errorf("Getting after delete returned no error")
|
||||
}
|
||||
|
||||
})
|
||||
t.Run("HandlerAPILogin", func(t *testing.T) {
|
||||
// TODO: Add test
|
||||
username := "admin"
|
||||
|
@@ -8,20 +8,61 @@ import (
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.t-juice.club/torjus/gpaste/api"
|
||||
"git.t-juice.club/torjus/gpaste/files"
|
||||
"github.com/google/uuid"
|
||||
"github.com/kirsle/configdir"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
AuthToken string
|
||||
BaseURL string `json:"base_url"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
|
||||
httpClient http.Client
|
||||
}
|
||||
|
||||
func (c *Client) WriteConfigToWriter(w io.Writer) error {
|
||||
encoder := json.NewEncoder(w)
|
||||
return encoder.Encode(c)
|
||||
}
|
||||
func (c *Client) WriteConfig() error {
|
||||
dir := configdir.LocalConfig("gpaste")
|
||||
// Ensure dir exists
|
||||
err := os.MkdirAll(dir, os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(dir, "client.json")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return c.WriteConfigToWriter(f)
|
||||
}
|
||||
|
||||
func (c *Client) LoadConfig() error {
|
||||
dir := configdir.LocalCache("gpaste")
|
||||
path := filepath.Join(dir, "client.json")
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return c.LoadConfigFromReader(f)
|
||||
}
|
||||
|
||||
func (c *Client) LoadConfigFromReader(r io.Reader) error {
|
||||
decoder := json.NewDecoder(r)
|
||||
return decoder.Decode(c)
|
||||
}
|
||||
|
||||
func (c *Client) Login(ctx context.Context, username, password string) error {
|
||||
url := fmt.Sprintf("%s/api/login", c.BaseURL)
|
||||
// TODO: Change timeout
|
||||
@@ -162,3 +203,24 @@ func (c *Client) Upload(ctx context.Context, files ...*files.File) ([]api.Respon
|
||||
|
||||
return expectedResp, nil
|
||||
}
|
||||
|
||||
func (c *Client) Delete(ctx context.Context, id string) error {
|
||||
url := fmt.Sprintf("%s/api/file/%s", c.BaseURL, id)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.AuthToken))
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to perform request: %s", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("got non-ok response from server: %s", resp.Status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package client_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"git.t-juice.club/torjus/gpaste/files"
|
||||
"git.t-juice.club/torjus/gpaste/users"
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
@@ -162,4 +164,31 @@ func TestClient(t *testing.T) {
|
||||
t.Errorf("File contents does not match: %s", cmp.Diff(buf.String(), fileContents))
|
||||
}
|
||||
})
|
||||
t.Run("Save", func(t *testing.T) {
|
||||
c := client.Client{BaseURL: "http://example.org/gpaste", AuthToken: "tokenpls"}
|
||||
expectedConfig := "{\"base_url\":\"http://example.org/gpaste\",\"auth_token\":\"tokenpls\"}\n"
|
||||
buf := new(bytes.Buffer)
|
||||
err := c.WriteConfigToWriter(buf)
|
||||
if err != nil {
|
||||
t.Fatalf("Error writing config: %s", err)
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(buf.String(), expectedConfig); diff != "" {
|
||||
t.Errorf("Written config does not match expected: %s", diff)
|
||||
}
|
||||
})
|
||||
t.Run("Load", func(t *testing.T) {
|
||||
c := client.Client{}
|
||||
config := "{\"base_url\":\"http://pasta.example.org\",\"auth_token\":\"tokenpls\"}\n"
|
||||
expectedClient := client.Client{BaseURL: "http://pasta.example.org", AuthToken: "tokenpls"}
|
||||
sr := strings.NewReader(config)
|
||||
if err := c.LoadConfigFromReader(sr); err != nil {
|
||||
t.Fatalf("Error reading config: %s", err)
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(c, expectedClient, cmpopts.IgnoreUnexported(client.Client{})); diff != "" {
|
||||
t.Errorf("Client does not match expected: %s", diff)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
@@ -39,6 +39,22 @@ func ActionUpload(c *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func ActionDelete(c *cli.Context) error {
|
||||
clnt := client.Client{
|
||||
BaseURL: c.String("url"),
|
||||
}
|
||||
for _, arg := range c.Args().Slice() {
|
||||
ctx, cancel := context.WithTimeout(c.Context, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := clnt.Delete(ctx, arg); err != nil {
|
||||
fmt.Printf("Error deleting file %s\n", arg)
|
||||
fmt.Printf("%s\n", err)
|
||||
}
|
||||
fmt.Printf("Deleted %s\n", arg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ActionLogin(c *cli.Context) error {
|
||||
username := c.Args().First()
|
||||
if username == "" {
|
||||
@@ -56,6 +72,10 @@ func ActionLogin(c *cli.Context) error {
|
||||
errmsg := fmt.Sprintf("Error logging in: %s", err)
|
||||
return cli.Exit(errmsg, 1)
|
||||
}
|
||||
if err := clnt.WriteConfig(); err != nil {
|
||||
errMsg := fmt.Sprintf("Failed to write config: %s", err)
|
||||
return cli.Exit(errMsg, 1)
|
||||
}
|
||||
// TODO: Store this somewhere, so we don't need to log in each time
|
||||
fmt.Println("Successfully logged in.")
|
||||
|
||||
|
@@ -37,6 +37,12 @@ func main() {
|
||||
ArgsUsage: "FILE [FILE]...",
|
||||
Action: actions.ActionUpload,
|
||||
},
|
||||
{
|
||||
Name: "delete",
|
||||
Usage: "Delete file(s)",
|
||||
ArgsUsage: "FILE [FILE]...",
|
||||
Action: actions.ActionDelete,
|
||||
},
|
||||
{
|
||||
Name: "login",
|
||||
Usage: "Login to gpaste server",
|
||||
|
2
go.mod
2
go.mod
@@ -9,6 +9,7 @@ require github.com/go-chi/chi/v5 v5.0.7
|
||||
require (
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/google/go-cmp v0.5.6
|
||||
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f
|
||||
github.com/pelletier/go-toml v1.9.4
|
||||
github.com/urfave/cli/v2 v2.3.0
|
||||
go.etcd.io/bbolt v1.3.6
|
||||
@@ -23,4 +24,5 @@ require (
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.7.0 // indirect
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
)
|
||||
|
2
go.sum
2
go.sum
@@ -15,6 +15,8 @@ github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f h1:dKccXx7xA56UNqOcFIbuqFjAWPVtP688j5QMgmo6OHU=
|
||||
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f/go.mod h1:4rEELDSfUAlBSyUjPG0JnaNGjf13JySHFeRdD/3dLP0=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
|
Reference in New Issue
Block a user