Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
fdf374d541 | |||
88b5b941df | |||
5ffef4f6ad | |||
e1ed7cce66 | |||
88784363a6 | |||
e3ff8065f1 | |||
9449b37ab1 | |||
1cb169318c | |||
94e1920098 | |||
41e82fb21e | |||
d8817cc67f | |||
1caec97d81 | |||
786ae6ad94 |
16
.vscode/launch.json
vendored
Normal file
16
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Debug server",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "auto",
|
||||||
|
"program": "${workspaceFolder}/cmd/server/server.go",
|
||||||
|
"cwd": "${workspaceFolder}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
61
auth.go
Normal file
61
auth.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthService struct {
|
||||||
|
users UserStore
|
||||||
|
hmacSecret []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthService(store UserStore, signingSecret []byte) *AuthService {
|
||||||
|
return &AuthService{users: store, hmacSecret: signingSecret}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (as *AuthService) Login(username, password string) (string, error) {
|
||||||
|
user, err := as.users.Get(username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := user.ValidatePassword(password); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Set iss and aud
|
||||||
|
claims := jwt.StandardClaims{
|
||||||
|
Subject: user.Username,
|
||||||
|
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
|
||||||
|
NotBefore: time.Now().Unix(),
|
||||||
|
IssuedAt: time.Now().Unix(),
|
||||||
|
Id: uuid.NewString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
|
||||||
|
signed, err := token.SignedString(as.hmacSecret)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return signed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (as *AuthService) ValidateToken(rawToken string) error {
|
||||||
|
claims := &jwt.StandardClaims{}
|
||||||
|
token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) {
|
||||||
|
return as.hmacSecret, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !token.Valid {
|
||||||
|
return fmt.Errorf("invalid token")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
39
auth_test.go
Normal file
39
auth_test.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAuth(t *testing.T) {
|
||||||
|
t.Run("Token", func(t *testing.T) {
|
||||||
|
us := gpaste.NewMemoryUserStore()
|
||||||
|
secret := []byte(randomString(16))
|
||||||
|
as := gpaste.NewAuthService(us, secret)
|
||||||
|
|
||||||
|
username := randomString(8)
|
||||||
|
password := randomString(16)
|
||||||
|
|
||||||
|
user := &gpaste.User{Username: username}
|
||||||
|
if err := user.SetPassword(password); err != nil {
|
||||||
|
t.Fatalf("error setting user password: %s", err)
|
||||||
|
}
|
||||||
|
if err := us.Store(user); err != nil {
|
||||||
|
t.Fatalf("Error storing user: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := as.Login(username, password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error creating token: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := as.ValidateToken(token); err != nil {
|
||||||
|
t.Fatalf("Error validating token: %s", err)
|
||||||
|
}
|
||||||
|
invalidToken := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMyMjk3NjMsImp0aSI6ImUzNDk5NWI1LThiZmMtNDQyNy1iZDgxLWFmNmQ3OTRiYzM0YiIsImlhdCI6MTY0MjYyNDk2MywibmJmIjoxNjQyNjI0OTYzLCJzdWIiOiJYdE5Hemt5ZSJ9.VM6dkwSLaBv8cStkWRVVv9ADjdUrHGHrlB7GB7Ly7n8`
|
||||||
|
if err := as.ValidateToken(invalidToken); err == nil {
|
||||||
|
t.Fatalf("Invalid token passed validation")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@@ -1,7 +1,182 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
"golang.org/x/term"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
version = "dev"
|
||||||
|
commit = "none"
|
||||||
|
date = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("Starting gpaste client")
|
cli.VersionFlag = &cli.BoolFlag{Name: "version"}
|
||||||
|
|
||||||
|
app := cli.App{
|
||||||
|
Name: "gpaste",
|
||||||
|
Version: fmt.Sprintf("gpaste %s-%s (%s)", version, commit, date),
|
||||||
|
Flags: []cli.Flag{
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "config",
|
||||||
|
Usage: "Path to config-file.",
|
||||||
|
},
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "url",
|
||||||
|
Usage: "Base url of gpaste server",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Commands: []*cli.Command{
|
||||||
|
{
|
||||||
|
Name: "upload",
|
||||||
|
Usage: "Upload file(s)",
|
||||||
|
ArgsUsage: "FILE [FILE]...",
|
||||||
|
Action: ActionUpload,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "login",
|
||||||
|
Usage: "Login to gpaste server",
|
||||||
|
ArgsUsage: "USERNAME",
|
||||||
|
Action: ActionLogin,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Run(os.Args)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ActionUpload(c *cli.Context) error {
|
||||||
|
url := fmt.Sprintf("%s/api/file", c.String("url"))
|
||||||
|
client := &http.Client{}
|
||||||
|
// TODO: Change timeout
|
||||||
|
ctx, cancel := context.WithTimeout(c.Context, 10*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
mw := multipart.NewWriter(buf)
|
||||||
|
|
||||||
|
for _, arg := range c.Args().Slice() {
|
||||||
|
f, err := os.Open(arg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
fw, err := mw.CreateFormFile(uuid.Must(uuid.NewRandom()).String(), arg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := io.Copy(fw, f); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mw.Close()
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Add("Content-Type", mw.FormDataContentType())
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var expectedResp []struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(resp.Body)
|
||||||
|
if err := decoder.Decode(&expectedResp); err != nil {
|
||||||
|
return fmt.Errorf("error decoding response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range expectedResp {
|
||||||
|
fmt.Printf("Uploaded file %s\n", r.ID)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ActionLogin(c *cli.Context) error {
|
||||||
|
username := c.Args().First()
|
||||||
|
if username == "" {
|
||||||
|
return cli.Exit("USERNAME not supplied.", 1)
|
||||||
|
}
|
||||||
|
password, err := readPassword()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error reading password: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
url := fmt.Sprintf("%s/api/login", c.String("url"))
|
||||||
|
client := &http.Client{}
|
||||||
|
// TODO: Change timeout
|
||||||
|
ctx, cancel := context.WithTimeout(c.Context, 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
body := new(bytes.Buffer)
|
||||||
|
requestData := struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}{
|
||||||
|
Username: username,
|
||||||
|
Password: password,
|
||||||
|
}
|
||||||
|
encoder := json.NewEncoder(body)
|
||||||
|
if err := encoder.Encode(&requestData); err != nil {
|
||||||
|
return fmt.Errorf("error encoding response: %w", err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error creating request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to perform request: %s", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return cli.Exit("got non-ok response from server", 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
responseData := struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(resp.Body)
|
||||||
|
if err := decoder.Decode(&responseData); err != nil {
|
||||||
|
return fmt.Errorf("unable to parse response: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Token: %s", responseData.Token)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPassword() (string, error) {
|
||||||
|
fmt.Print("Enter Password: ")
|
||||||
|
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
password := string(bytePassword)
|
||||||
|
return strings.TrimSpace(password), nil
|
||||||
}
|
}
|
||||||
|
@@ -57,6 +57,7 @@ func ActionServe(c *cli.Context) error {
|
|||||||
// Setup loggers
|
// Setup loggers
|
||||||
rootLogger := getRootLogger(cfg.LogLevel)
|
rootLogger := getRootLogger(cfg.LogLevel)
|
||||||
serverLogger := rootLogger.Named("SERV")
|
serverLogger := rootLogger.Named("SERV")
|
||||||
|
accessLogger := rootLogger.Named("ACCS")
|
||||||
|
|
||||||
// Setup contexts for clean shutdown
|
// Setup contexts for clean shutdown
|
||||||
rootCtx, rootCancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
rootCtx, rootCancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||||
@@ -69,6 +70,8 @@ func ActionServe(c *cli.Context) error {
|
|||||||
go func() {
|
go func() {
|
||||||
srv := gpaste.NewHTTPServer(cfg)
|
srv := gpaste.NewHTTPServer(cfg)
|
||||||
srv.Addr = cfg.ListenAddr
|
srv.Addr = cfg.ListenAddr
|
||||||
|
srv.Logger = serverLogger
|
||||||
|
srv.AccessLogger = accessLogger
|
||||||
|
|
||||||
// Wait for cancel
|
// Wait for cancel
|
||||||
go func() {
|
go func() {
|
||||||
|
52
config.go
52
config.go
@@ -3,27 +3,67 @@ package gpaste
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/pelletier/go-toml"
|
"github.com/pelletier/go-toml"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
LogLevel string `toml:"LogLevel"`
|
LogLevel string `toml:"LogLevel"`
|
||||||
URL string `toml:"URL"`
|
URL string `toml:"URL"`
|
||||||
ListenAddr string `toml:"ListenAddr"`
|
ListenAddr string `toml:"ListenAddr"`
|
||||||
Store *ServerStoreConfig `toml:"Store"`
|
SigningSecret string `toml:"SigningSecret"`
|
||||||
|
Store *ServerStoreConfig `toml:"Store"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerStoreConfig struct {
|
type ServerStoreConfig struct {
|
||||||
Type string `toml:"Type"`
|
Type string `toml:"Type"`
|
||||||
|
FS *ServerStoreFSStoreConfig `toml:"FS"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServerStoreFSStoreConfig struct {
|
||||||
|
Dir string `toml:"Dir"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ServerConfigFromReader(r io.Reader) (*ServerConfig, error) {
|
func ServerConfigFromReader(r io.Reader) (*ServerConfig, error) {
|
||||||
decoder := toml.NewDecoder(r)
|
decoder := toml.NewDecoder(r)
|
||||||
var c ServerConfig
|
c := ServerConfig{
|
||||||
|
Store: &ServerStoreConfig{
|
||||||
|
FS: &ServerStoreFSStoreConfig{},
|
||||||
|
},
|
||||||
|
}
|
||||||
if err := decoder.Decode(&c); err != nil {
|
if err := decoder.Decode(&c); err != nil {
|
||||||
return nil, fmt.Errorf("error decoding server config: %w", err)
|
return nil, fmt.Errorf("error decoding server config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.updateFromEnv()
|
||||||
|
|
||||||
return &c, nil
|
return &c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (sc *ServerConfig) updateFromEnv() {
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_LOGLEVEL"); ok {
|
||||||
|
sc.LogLevel = strings.ToUpper(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_URL"); ok {
|
||||||
|
sc.URL = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_LISTENADDR"); ok {
|
||||||
|
sc.ListenAddr = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_SIGNINGSECRET"); ok {
|
||||||
|
sc.SigningSecret = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_STORE_TYPE"); ok {
|
||||||
|
sc.Store.Type = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if value, ok := os.LookupEnv("GPASTE_STORE_FS_DIR"); ok {
|
||||||
|
sc.Store.FS.Dir = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
97
config_test.go
Normal file
97
config_test.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestServerConfig(t *testing.T) {
|
||||||
|
t.Run("FromReader", func(t *testing.T) {
|
||||||
|
clearEnv()
|
||||||
|
simpleConfig := `
|
||||||
|
LogLevel = "INFO"
|
||||||
|
URL = "http://paste.example.org"
|
||||||
|
ListenAddr = ":8080"
|
||||||
|
SigningSecret = "abc999"
|
||||||
|
|
||||||
|
[Store]
|
||||||
|
Type = "fs"
|
||||||
|
[Store.FS]
|
||||||
|
Dir = "/tmp"
|
||||||
|
`
|
||||||
|
expected := &gpaste.ServerConfig{
|
||||||
|
LogLevel: "INFO",
|
||||||
|
URL: "http://paste.example.org",
|
||||||
|
ListenAddr: ":8080",
|
||||||
|
SigningSecret: "abc999",
|
||||||
|
Store: &gpaste.ServerStoreConfig{
|
||||||
|
Type: "fs",
|
||||||
|
FS: &gpaste.ServerStoreFSStoreConfig{
|
||||||
|
Dir: "/tmp",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
sr := strings.NewReader(simpleConfig)
|
||||||
|
|
||||||
|
c, err := gpaste.ServerConfigFromReader(sr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error parsing config: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !cmp.Equal(c, expected) {
|
||||||
|
t.Errorf("Result does not match: %s", cmp.Diff(c, expected))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("FromEnv", func(t *testing.T) {
|
||||||
|
clearEnv()
|
||||||
|
|
||||||
|
var envMap map[string]string = map[string]string{
|
||||||
|
"GPASTE_LOGLEVEL": "DEBUG",
|
||||||
|
"GPASTE_URL": "http://gpaste.example.org",
|
||||||
|
"GPASTE_STORE_TYPE": "fs",
|
||||||
|
"GPASTE_LISTENADDR": ":8000",
|
||||||
|
"GPASTE_SIGNINGSECRET": "test1345",
|
||||||
|
"GPASTE_STORE_FS_DIR": "/tmp",
|
||||||
|
}
|
||||||
|
expected := &gpaste.ServerConfig{
|
||||||
|
LogLevel: "DEBUG",
|
||||||
|
URL: "http://gpaste.example.org",
|
||||||
|
ListenAddr: ":8000",
|
||||||
|
SigningSecret: "test1345",
|
||||||
|
Store: &gpaste.ServerStoreConfig{
|
||||||
|
Type: "fs",
|
||||||
|
FS: &gpaste.ServerStoreFSStoreConfig{
|
||||||
|
Dir: "/tmp",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range envMap {
|
||||||
|
os.Setenv(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
sr := strings.NewReader("")
|
||||||
|
c, err := gpaste.ServerConfigFromReader(sr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error parsing empty config")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !cmp.Equal(c, expected) {
|
||||||
|
t.Errorf("Result does not match: %s", cmp.Diff(c, expected))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearEnv() {
|
||||||
|
for _, env := range os.Environ() {
|
||||||
|
result := strings.Split(env, "=")
|
||||||
|
value := result[0]
|
||||||
|
if strings.Contains(value, "GPASTE_") {
|
||||||
|
os.Unsetenv(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -6,11 +6,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type File struct {
|
type File struct {
|
||||||
ID string
|
ID string `json:"id"`
|
||||||
Body io.ReadCloser
|
OriginalFilename string `json:"original_filename"`
|
||||||
|
MaxViews uint `json:"max_views"`
|
||||||
|
ExpiresOn time.Time `json:"expires_on"`
|
||||||
|
|
||||||
MaxViews uint
|
Body io.ReadCloser
|
||||||
ExpiresOn time.Time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type FileStore interface {
|
type FileStore interface {
|
||||||
|
115
filestore_fs.go
Normal file
115
filestore_fs.go
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FSFileStore struct {
|
||||||
|
dir string
|
||||||
|
metadata map[string]*File
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFSFileStore(dir string) (*FSFileStore, error) {
|
||||||
|
s := &FSFileStore{
|
||||||
|
dir: dir,
|
||||||
|
metadata: make(map[string]*File),
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.readMetadata()
|
||||||
|
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
func (s *FSFileStore) Store(f *File) error {
|
||||||
|
defer f.Body.Close()
|
||||||
|
|
||||||
|
metadata := &File{
|
||||||
|
ID: f.ID,
|
||||||
|
OriginalFilename: f.OriginalFilename,
|
||||||
|
MaxViews: f.MaxViews,
|
||||||
|
ExpiresOn: f.ExpiresOn,
|
||||||
|
}
|
||||||
|
|
||||||
|
path := filepath.Join(s.dir, f.ID)
|
||||||
|
dst, err := os.Create(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer dst.Close()
|
||||||
|
|
||||||
|
if _, err := io.Copy(dst, f.Body); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.metadata[f.ID] = metadata
|
||||||
|
if err := s.writeMetadata(); err != nil {
|
||||||
|
delete(s.metadata, f.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FSFileStore) Get(id string) (*File, error) {
|
||||||
|
metadata, ok := s.metadata[id]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("no such item")
|
||||||
|
}
|
||||||
|
|
||||||
|
path := filepath.Join(s.dir, id)
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
metadata.Body = f
|
||||||
|
return metadata, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FSFileStore) Delete(id string) error {
|
||||||
|
path := filepath.Join(s.dir, id)
|
||||||
|
if err := os.Remove(path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
delete(s.metadata, id)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FSFileStore) List() ([]string, error) {
|
||||||
|
var results []string
|
||||||
|
for k := range s.metadata {
|
||||||
|
results = append(results, k)
|
||||||
|
}
|
||||||
|
return results, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FSFileStore) writeMetadata() error {
|
||||||
|
path := filepath.Join(s.dir, "metadata.json")
|
||||||
|
f, err := os.Create(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
encoder := json.NewEncoder(f)
|
||||||
|
if err := encoder.Encode(s.metadata); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *FSFileStore) readMetadata() error {
|
||||||
|
path := filepath.Join(s.dir, "metadata.json")
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
// TODO: Handle errors better
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(f)
|
||||||
|
if err := decoder.Decode(&s.metadata); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
26
filestore_fs_test.go
Normal file
26
filestore_fs_test.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFSFileStore(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
s, err := gpaste.NewFSFileStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error creating store: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
RunFilestoreTest(s, t)
|
||||||
|
persistentDir := t.TempDir()
|
||||||
|
newFunc := func() gpaste.FileStore {
|
||||||
|
s, err := gpaste.NewFSFileStore(persistentDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error creating store: %s", err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
RunPersistentFilestoreTest(newFunc, t)
|
||||||
|
}
|
@@ -3,9 +3,12 @@ package gpaste_test
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"io"
|
"io"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.t-juice.club/torjus/gpaste"
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -74,3 +77,81 @@ func RunFilestoreTest(s gpaste.FileStore, t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RunPersistentFilestoreTest(newStoreFunc func() gpaste.FileStore, t *testing.T) {
|
||||||
|
s := newStoreFunc()
|
||||||
|
|
||||||
|
files := []struct {
|
||||||
|
File *gpaste.File
|
||||||
|
ExpectedData string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
File: &gpaste.File{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
OriginalFilename: "testfile.txt",
|
||||||
|
MaxViews: 5,
|
||||||
|
ExpiresOn: time.Now().Add(10 * time.Minute),
|
||||||
|
Body: io.NopCloser(strings.NewReader("cocks!")),
|
||||||
|
},
|
||||||
|
ExpectedData: "cocks!",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
File: &gpaste.File{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
OriginalFilename: "testfile2.txt",
|
||||||
|
MaxViews: 5,
|
||||||
|
ExpiresOn: time.Now().Add(10 * time.Minute),
|
||||||
|
Body: io.NopCloser(strings.NewReader("derps!")),
|
||||||
|
},
|
||||||
|
ExpectedData: "derps!",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
err := s.Store(f.File)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error storing file: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
retrieved, err := s.Get(f.File.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Unable to retrieve file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ignoreBody := cmp.FilterPath(func(p cmp.Path) bool { return p.String() == "Body" }, cmp.Ignore())
|
||||||
|
if !cmp.Equal(retrieved, f.File, ignoreBody) {
|
||||||
|
t.Errorf("Mismatch: %s", cmp.Diff(retrieved, f.File))
|
||||||
|
}
|
||||||
|
buf := new(strings.Builder)
|
||||||
|
if _, err := io.Copy(buf, retrieved.Body); err != nil {
|
||||||
|
t.Fatalf("Error reading from body: %s", err)
|
||||||
|
}
|
||||||
|
retrieved.Body.Close()
|
||||||
|
if buf.String() != f.ExpectedData {
|
||||||
|
t.Fatalf("Data does not match. %s", cmp.Diff(buf.String(), f.ExpectedData))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reopen store, and fetch again
|
||||||
|
s = newStoreFunc()
|
||||||
|
for _, f := range files {
|
||||||
|
retrieved, err := s.Get(f.File.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Unable to retrieve file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ignoreBody := cmp.FilterPath(func(p cmp.Path) bool { return p.String() == "Body" }, cmp.Ignore())
|
||||||
|
if !cmp.Equal(retrieved, f.File, ignoreBody) {
|
||||||
|
t.Errorf("Mismatch: %s", cmp.Diff(retrieved, f.File))
|
||||||
|
}
|
||||||
|
buf := new(strings.Builder)
|
||||||
|
if _, err := io.Copy(buf, retrieved.Body); err != nil {
|
||||||
|
t.Fatalf("Error reading from body: %s", err)
|
||||||
|
}
|
||||||
|
retrieved.Body.Close()
|
||||||
|
if buf.String() != f.ExpectedData {
|
||||||
|
t.Fatalf("Data does not match. %s", cmp.Diff(buf.String(), f.ExpectedData))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
6
go.mod
6
go.mod
@@ -7,9 +7,14 @@ require github.com/google/uuid v1.3.0
|
|||||||
require github.com/go-chi/chi/v5 v5.0.7
|
require github.com/go-chi/chi/v5 v5.0.7
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||||
|
github.com/google/go-cmp v0.5.6
|
||||||
github.com/pelletier/go-toml v1.9.4
|
github.com/pelletier/go-toml v1.9.4
|
||||||
github.com/urfave/cli/v2 v2.3.0
|
github.com/urfave/cli/v2 v2.3.0
|
||||||
|
go.etcd.io/bbolt v1.3.6
|
||||||
go.uber.org/zap v1.20.0
|
go.uber.org/zap v1.20.0
|
||||||
|
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -17,4 +22,5 @@ require (
|
|||||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||||
go.uber.org/atomic v1.9.0 // indirect
|
go.uber.org/atomic v1.9.0 // indirect
|
||||||
go.uber.org/multierr v1.7.0 // indirect
|
go.uber.org/multierr v1.7.0 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
|
||||||
)
|
)
|
||||||
|
19
go.sum
19
go.sum
@@ -9,6 +9,10 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
|
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
|
||||||
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
||||||
|
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||||
|
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||||
|
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 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
@@ -31,6 +35,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
|||||||
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
|
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
|
||||||
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
|
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
|
||||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
|
go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU=
|
||||||
|
go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4=
|
||||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||||
@@ -43,28 +49,41 @@ go.uber.org/zap v1.20.0 h1:N4oPlghZwYG55MlU6LXk/Zp00FVNE9X9wrYO8CEs4lc=
|
|||||||
go.uber.org/zap v1.20.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
|
go.uber.org/zap v1.20.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce h1:Roh6XWxHFKrPgC/EQhVubSAGQ6Ozk6IdxHSzt1mR0EI=
|
||||||
|
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
|
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0=
|
||||||
|
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
130
http.go
130
http.go
@@ -4,30 +4,48 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
type HTTPServer struct {
|
type HTTPServer struct {
|
||||||
store FileStore
|
Files FileStore
|
||||||
config *ServerConfig
|
Users UserStore
|
||||||
Logger *zap.SugaredLogger
|
Auth *AuthService
|
||||||
|
config *ServerConfig
|
||||||
|
Logger *zap.SugaredLogger
|
||||||
|
AccessLogger *zap.SugaredLogger
|
||||||
http.Server
|
http.Server
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHTTPServer(cfg *ServerConfig) *HTTPServer {
|
func NewHTTPServer(cfg *ServerConfig) *HTTPServer {
|
||||||
srv := &HTTPServer{
|
srv := &HTTPServer{
|
||||||
config: cfg,
|
config: cfg,
|
||||||
Logger: zap.NewNop().Sugar(),
|
Logger: zap.NewNop().Sugar(),
|
||||||
|
AccessLogger: zap.NewNop().Sugar(),
|
||||||
}
|
}
|
||||||
srv.store = NewMemoryFileStore()
|
srv.Files = NewMemoryFileStore()
|
||||||
|
srv.Users = NewMemoryUserStore()
|
||||||
|
srv.Auth = NewAuthService(srv.Users, []byte(srv.config.SigningSecret))
|
||||||
|
|
||||||
|
// Create initial user
|
||||||
|
// TODO: Do properly
|
||||||
|
user := &User{Username: "admin"}
|
||||||
|
user.SetPassword("admin")
|
||||||
|
srv.Users.Store(user)
|
||||||
|
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
r.Use(middleware.RealIP)
|
||||||
|
r.Use(middleware.RequestID)
|
||||||
|
r.Use(srv.MiddlewareAccessLogger)
|
||||||
r.Get("/", srv.HandlerIndex)
|
r.Get("/", srv.HandlerIndex)
|
||||||
r.Post("/api/file", srv.HandlerAPIFilePost)
|
r.Post("/api/file", srv.HandlerAPIFilePost)
|
||||||
r.Get("/api/file/{id}", srv.HandlerAPIFileGet)
|
r.Get("/api/file/{id}", srv.HandlerAPIFileGet)
|
||||||
|
r.Post("/api/login", srv.HandlerAPILogin)
|
||||||
srv.Handler = r
|
srv.Handler = r
|
||||||
|
|
||||||
return srv
|
return srv
|
||||||
@@ -42,14 +60,21 @@ func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request)
|
|||||||
ID: uuid.Must(uuid.NewRandom()).String(),
|
ID: uuid.Must(uuid.NewRandom()).String(),
|
||||||
Body: r.Body,
|
Body: r.Body,
|
||||||
}
|
}
|
||||||
|
reqID := middleware.GetReqID(r.Context())
|
||||||
|
|
||||||
err := s.store.Store(f)
|
// Check if multipart form
|
||||||
if err != nil {
|
ct := r.Header.Get("Content-Type")
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
if strings.Contains(ct, "multipart/form-data") {
|
||||||
s.Logger.Warnw("Error storing file.", "erorr", err, "id", f.ID, "remote_addr", r.RemoteAddr)
|
s.processMultiPartFormUpload(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Logger.Infow("Stored file.", "id", f.ID, "remote_addr", r.RemoteAddr)
|
err := s.Files.Store(f)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
s.Logger.Warnw("Error storing file.", "req_id", reqID, "error", err, "id", f.ID, "remote_addr", r.RemoteAddr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.Logger.Infow("Stored file.", "req_id", reqID, "id", f.ID, "remote_addr", r.RemoteAddr)
|
||||||
var resp = struct {
|
var resp = struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -62,7 +87,7 @@ func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request)
|
|||||||
w.WriteHeader(http.StatusAccepted)
|
w.WriteHeader(http.StatusAccepted)
|
||||||
encoder := json.NewEncoder(w)
|
encoder := json.NewEncoder(w)
|
||||||
if err := encoder.Encode(&resp); err != nil {
|
if err := encoder.Encode(&resp); err != nil {
|
||||||
s.Logger.Warnw("Error encoding response to client.", "error", err, "remote_addr", r.RemoteAddr)
|
s.Logger.Warnw("Error encoding response to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +98,7 @@ func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
f, err := s.store.Get(id)
|
f, err := s.Files.Get(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// TODO: LOG
|
// TODO: LOG
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
@@ -82,6 +107,83 @@ func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
if _, err := io.Copy(w, f.Body); err != nil {
|
if _, err := io.Copy(w, f.Body); err != nil {
|
||||||
s.Logger.Warnw("Error writing file to client.", "error", err, "remote_addr", r.RemoteAddr)
|
reqID := middleware.GetReqID(r.Context())
|
||||||
|
s.Logger.Warnw("Error writing file to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
reqID := middleware.GetReqID(r.Context())
|
||||||
|
type resp struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var responses []resp
|
||||||
|
|
||||||
|
if err := r.ParseMultipartForm(1024 * 1024 * 10); err != nil {
|
||||||
|
s.Logger.Warnw("Error parsing multipart form.", "req_id", reqID, "err", err)
|
||||||
|
}
|
||||||
|
for k := range r.MultipartForm.File {
|
||||||
|
ff, fh, err := r.FormFile(k)
|
||||||
|
if err != nil {
|
||||||
|
s.Logger.Warnw("Error reading file from multipart form.", "req_id", reqID, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f := &File{
|
||||||
|
ID: uuid.Must(uuid.NewRandom()).String(),
|
||||||
|
OriginalFilename: fh.Filename,
|
||||||
|
Body: ff,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Files.Store(f); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
s.Logger.Warnw("Error storing file.", "req_id", reqID, "error", err, "id", f.ID, "remote_addr", r.RemoteAddr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.Logger.Infow("Stored file.", "req_id", reqID, "id", f.ID, "filename", f.OriginalFilename, "remote_addr", r.RemoteAddr)
|
||||||
|
|
||||||
|
responses = append(responses, resp{Message: "OK", ID: f.ID, URL: "TODO"})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
|
if err := encoder.Encode(&responses); err != nil {
|
||||||
|
s.Logger.Warnw("Error encoding response to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *HTTPServer) HandlerAPILogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
reqID := middleware.GetReqID(r.Context())
|
||||||
|
expectedRequest := struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}{}
|
||||||
|
decoder := json.NewDecoder(r.Body)
|
||||||
|
defer r.Body.Close()
|
||||||
|
if err := decoder.Decode(&expectedRequest); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := s.Auth.Login(expectedRequest.Username, expectedRequest.Password)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response := struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}{
|
||||||
|
Token: token,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.Logger.Infow("User logged in.", "req_id", reqID, "username", expectedRequest.Username)
|
||||||
|
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
|
if err := encoder.Encode(&response); err != nil {
|
||||||
|
s.Logger.Infow("Error encoding json response to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
144
http_test.go
Normal file
144
http_test.go
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHandlers(t *testing.T) {
|
||||||
|
cfg := &gpaste.ServerConfig{
|
||||||
|
SigningSecret: "abc123",
|
||||||
|
Store: &gpaste.ServerStoreConfig{
|
||||||
|
Type: "memory",
|
||||||
|
},
|
||||||
|
URL: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
hs := gpaste.NewHTTPServer(cfg)
|
||||||
|
|
||||||
|
t.Run("HandlerIndex", func(t *testing.T) {
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
|
||||||
|
hs.Handler.ServeHTTP(rr, req)
|
||||||
|
|
||||||
|
if status := rr.Code; status != http.StatusOK {
|
||||||
|
t.Errorf("Returned unexpected status")
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedBody := "index"
|
||||||
|
if body := rr.Body.String(); body != expectedBody {
|
||||||
|
t.Errorf("Body does not match expected. Got %s want %s", body, expectedBody)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("HandlerAPIFilePost", func(t *testing.T) {
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
mw := multipart.NewWriter(buf)
|
||||||
|
fw, err := mw.CreateFormFile("test", "test.txt")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Unable to create form file: %s", err)
|
||||||
|
}
|
||||||
|
expectedData := "Test OMEGALUL PLS."
|
||||||
|
if _, err := io.WriteString(fw, expectedData); err != nil {
|
||||||
|
t.Fatalf("Unable to write body to buffer: %s", err)
|
||||||
|
}
|
||||||
|
mw.Close()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/file", buf)
|
||||||
|
req.Header.Add("Content-Type", mw.FormDataContentType())
|
||||||
|
|
||||||
|
hs.Handler.ServeHTTP(rr, req)
|
||||||
|
|
||||||
|
if status := rr.Code; status != http.StatusAccepted {
|
||||||
|
t.Errorf("Returned unexpected status. Got %d want %d", status, http.StatusAccepted)
|
||||||
|
}
|
||||||
|
|
||||||
|
var expectedResp []struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(rr.Result().Body)
|
||||||
|
if err := decoder.Decode(&expectedResp); err != nil {
|
||||||
|
t.Fatalf("error decoding response: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if l := len(expectedResp); l != 1 {
|
||||||
|
t.Errorf("Response has wrong length. Got %d want %d", l, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadID := expectedResp[0].ID
|
||||||
|
if uploadID == "" {
|
||||||
|
t.Errorf("Response has empty id")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("HandlerAPIFileGet", func(t *testing.T) {
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
url := fmt.Sprintf("/api/file/%s", uploadID)
|
||||||
|
req := httptest.NewRequest(http.MethodGet, url, nil)
|
||||||
|
|
||||||
|
hs.Handler.ServeHTTP(rr, req)
|
||||||
|
|
||||||
|
if status := rr.Code; status != http.StatusOK {
|
||||||
|
t.Errorf("Returned unexpected status. Got %d want %d", status, http.StatusAccepted)
|
||||||
|
t.Logf(url)
|
||||||
|
}
|
||||||
|
if body := rr.Body.String(); body != expectedData {
|
||||||
|
t.Errorf("Returned body does not match expected.")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.Run("HandlerAPILogin", func(t *testing.T) {
|
||||||
|
// TODO: Add test
|
||||||
|
username := "admin"
|
||||||
|
password := "admin"
|
||||||
|
user := &gpaste.User{Username: username}
|
||||||
|
if err := user.SetPassword(password); err != nil {
|
||||||
|
t.Fatalf("Error setting user password: %s", err)
|
||||||
|
}
|
||||||
|
if err := hs.Users.Store(user); err != nil {
|
||||||
|
t.Fatalf("Error storing user: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requestData := struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}{
|
||||||
|
Username: username,
|
||||||
|
Password: password,
|
||||||
|
}
|
||||||
|
|
||||||
|
body := new(bytes.Buffer)
|
||||||
|
encoder := json.NewEncoder(body)
|
||||||
|
if err := encoder.Encode(&requestData); err != nil {
|
||||||
|
t.Fatalf("Error encoding request body: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/login", body)
|
||||||
|
|
||||||
|
hs.Handler.ServeHTTP(rr, req)
|
||||||
|
|
||||||
|
responseData := struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(rr.Body)
|
||||||
|
if err := decoder.Decode(&responseData); err != nil {
|
||||||
|
t.Fatalf("Error decoding response: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := hs.Auth.ValidateToken(responseData.Token); err != nil {
|
||||||
|
t.Fatalf("Unable to validate received token: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
30
middleware.go
Normal file
30
middleware.go
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
|
||||||
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||||
|
t1 := time.Now()
|
||||||
|
|
||||||
|
reqID := middleware.GetReqID(r.Context())
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
s.AccessLogger.Infow(r.Method,
|
||||||
|
"path", r.URL.Path,
|
||||||
|
"status", ww.Status(),
|
||||||
|
"written", ww.BytesWritten(),
|
||||||
|
"remote_addr", r.RemoteAddr,
|
||||||
|
"processing_time_ms", time.Since(t1).Milliseconds(),
|
||||||
|
"req_id", reqID)
|
||||||
|
}()
|
||||||
|
|
||||||
|
next.ServeHTTP(ww, r)
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(fn)
|
||||||
|
}
|
27
user.go
Normal file
27
user.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import "golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
HashedPassword []byte `json:"hashed_password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserStore interface {
|
||||||
|
Get(username string) (*User, error)
|
||||||
|
Store(user *User) error
|
||||||
|
Delete(username string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *User) ValidatePassword(password string) error {
|
||||||
|
return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *User) SetPassword(password string) error {
|
||||||
|
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
u.HashedPassword = hashed
|
||||||
|
return nil
|
||||||
|
}
|
37
user_test.go
Normal file
37
user_test.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUser(t *testing.T) {
|
||||||
|
t.Run("Password", func(t *testing.T) {
|
||||||
|
userMap := make(map[string]string)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
userMap[randomString(8)] = randomString(16)
|
||||||
|
}
|
||||||
|
|
||||||
|
for username, password := range userMap {
|
||||||
|
user := &gpaste.User{Username: username}
|
||||||
|
if err := user.SetPassword(password); err != nil {
|
||||||
|
t.Fatalf("Error setting password: %s", err)
|
||||||
|
}
|
||||||
|
if err := user.ValidatePassword(password); err != nil {
|
||||||
|
t.Fatalf("Error validating password: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomString(length int) string {
|
||||||
|
const charset = "abcdefghijklmnopqrstabcdefghijklmnopqrstuvwxyz" +
|
||||||
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
b[i] = charset[rand.Intn(len(charset))]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
69
userstore_bolt.go
Normal file
69
userstore_bolt.go
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"go.etcd.io/bbolt"
|
||||||
|
)
|
||||||
|
|
||||||
|
var keyUsers = []byte("users")
|
||||||
|
|
||||||
|
type BoltUserStore struct {
|
||||||
|
db *bbolt.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBoltUserStore(path string) (*BoltUserStore, error) {
|
||||||
|
db, err := bbolt.Open(path, 0666, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Update(func(tx *bbolt.Tx) error {
|
||||||
|
_, err := tx.CreateBucketIfNotExists(keyUsers)
|
||||||
|
return err
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &BoltUserStore{db: db}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BoltUserStore) Close() error {
|
||||||
|
return s.db.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BoltUserStore) Get(username string) (*User, error) {
|
||||||
|
var user User
|
||||||
|
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||||
|
bkt := tx.Bucket(keyUsers)
|
||||||
|
rawUser := bkt.Get([]byte(username))
|
||||||
|
if err := json.Unmarshal(rawUser, &user); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BoltUserStore) Store(user *User) error {
|
||||||
|
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||||
|
bkt := tx.Bucket(keyUsers)
|
||||||
|
|
||||||
|
data, err := json.Marshal(user)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bkt.Put([]byte(user.Username), data)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BoltUserStore) Delete(username string) error {
|
||||||
|
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||||
|
bkt := tx.Bucket(keyUsers)
|
||||||
|
return bkt.Delete([]byte(username))
|
||||||
|
})
|
||||||
|
}
|
27
userstore_bolt_test.go
Normal file
27
userstore_bolt_test.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBoltUserStore(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
newFunc := func() (func(), gpaste.UserStore) {
|
||||||
|
tmpFile := filepath.Join(tmpDir, randomString(8))
|
||||||
|
|
||||||
|
store, err := gpaste.NewBoltUserStore(tmpFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error creating store: %s", err)
|
||||||
|
}
|
||||||
|
cleanup := func() {
|
||||||
|
store.Close()
|
||||||
|
}
|
||||||
|
return cleanup, store
|
||||||
|
}
|
||||||
|
|
||||||
|
RunUserStoreTest(newFunc, t)
|
||||||
|
|
||||||
|
}
|
39
userstore_memory.go
Normal file
39
userstore_memory.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package gpaste
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MemoryUserStore struct {
|
||||||
|
users map[string]*User
|
||||||
|
lock sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMemoryUserStore() *MemoryUserStore {
|
||||||
|
return &MemoryUserStore{users: make(map[string]*User)}
|
||||||
|
}
|
||||||
|
func (s *MemoryUserStore) Get(username string) (*User, error) {
|
||||||
|
s.lock.Lock()
|
||||||
|
defer s.lock.Unlock()
|
||||||
|
user, ok := s.users[username]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("no such user: %s", username)
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MemoryUserStore) Store(user *User) error {
|
||||||
|
s.lock.Lock()
|
||||||
|
defer s.lock.Unlock()
|
||||||
|
s.users[user.Username] = user
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MemoryUserStore) Delete(username string) error {
|
||||||
|
s.lock.Lock()
|
||||||
|
defer s.lock.Unlock()
|
||||||
|
delete(s.users, username)
|
||||||
|
return nil
|
||||||
|
}
|
15
userstore_memory_test.go
Normal file
15
userstore_memory_test.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMemoryUserStore(t *testing.T) {
|
||||||
|
newFunc := func() (func(), gpaste.UserStore) {
|
||||||
|
return func() {}, gpaste.NewMemoryUserStore()
|
||||||
|
}
|
||||||
|
|
||||||
|
RunUserStoreTest(newFunc, t)
|
||||||
|
}
|
41
userstore_test.go
Normal file
41
userstore_test.go
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package gpaste_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.t-juice.club/torjus/gpaste"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RunUserStoreTest(newFunc func() (func(), gpaste.UserStore), t *testing.T) {
|
||||||
|
t.Run("Basics", func(t *testing.T) {
|
||||||
|
cleanup, s := newFunc()
|
||||||
|
t.Cleanup(cleanup)
|
||||||
|
|
||||||
|
userMap := make(map[string]string)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
userMap[randomString(8)] = randomString(16)
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range userMap {
|
||||||
|
user := &gpaste.User{
|
||||||
|
Username: k,
|
||||||
|
}
|
||||||
|
if err := user.SetPassword(v); err != nil {
|
||||||
|
t.Fatalf("Error setting password: %s", err)
|
||||||
|
}
|
||||||
|
if err := s.Store(user); err != nil {
|
||||||
|
t.Fatalf("Error storing user: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range userMap {
|
||||||
|
user, err := s.Get(k)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Error getting user: %s", err)
|
||||||
|
}
|
||||||
|
if err := user.ValidatePassword(v); err != nil {
|
||||||
|
t.Errorf("Error verifying password: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
Reference in New Issue
Block a user