Compare commits
	
		
			10 Commits
		
	
	
		
			v0.3.3
			...
			8e88f09709
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 8e88f09709 | |||
| d44801b0ae | |||
| a4bf701ac3 | |||
| 99bddcd03f | |||
| 6fdd55def8 | |||
| e0850233dc | |||
| e7c5a672ff | |||
| faa3cc102f | |||
| d4b7702bad | |||
| c6b282fbcc | 
@@ -2,8 +2,8 @@ pipeline:
 | 
				
			|||||||
  test:
 | 
					  test:
 | 
				
			||||||
    image: golang:latest
 | 
					    image: golang:latest
 | 
				
			||||||
    commands:
 | 
					    commands:
 | 
				
			||||||
      - go build ./cmd/client/client.go
 | 
					      - go build -o gpaste-client ./cmd/client/client.go
 | 
				
			||||||
      - go build ./cmd/server/server.go
 | 
					      - go build -o gpaste-server ./cmd/server/server.go
 | 
				
			||||||
      - go test -v ./...
 | 
					      - go test -v ./...
 | 
				
			||||||
      - go vet ./...
 | 
					      - go vet ./...
 | 
				
			||||||
    when:
 | 
					    when:
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"encoding/json"
 | 
						"encoding/json"
 | 
				
			||||||
@@ -6,6 +6,9 @@ import (
 | 
				
			|||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
	"github.com/go-chi/chi/v5"
 | 
						"github.com/go-chi/chi/v5"
 | 
				
			||||||
	"github.com/go-chi/chi/v5/middleware"
 | 
						"github.com/go-chi/chi/v5/middleware"
 | 
				
			||||||
	"github.com/google/uuid"
 | 
						"github.com/google/uuid"
 | 
				
			||||||
@@ -13,28 +16,28 @@ import (
 | 
				
			|||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type HTTPServer struct {
 | 
					type HTTPServer struct {
 | 
				
			||||||
	Files        FileStore
 | 
						Files        files.FileStore
 | 
				
			||||||
	Users        UserStore
 | 
						Users        users.UserStore
 | 
				
			||||||
	Auth         *AuthService
 | 
						Auth         *gpaste.AuthService
 | 
				
			||||||
	config       *ServerConfig
 | 
						config       *gpaste.ServerConfig
 | 
				
			||||||
	Logger       *zap.SugaredLogger
 | 
						Logger       *zap.SugaredLogger
 | 
				
			||||||
	AccessLogger *zap.SugaredLogger
 | 
						AccessLogger *zap.SugaredLogger
 | 
				
			||||||
	http.Server
 | 
						http.Server
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func NewHTTPServer(cfg *ServerConfig) *HTTPServer {
 | 
					func NewHTTPServer(cfg *gpaste.ServerConfig) *HTTPServer {
 | 
				
			||||||
	srv := &HTTPServer{
 | 
						srv := &HTTPServer{
 | 
				
			||||||
		config:       cfg,
 | 
							config:       cfg,
 | 
				
			||||||
		Logger:       zap.NewNop().Sugar(),
 | 
							Logger:       zap.NewNop().Sugar(),
 | 
				
			||||||
		AccessLogger: zap.NewNop().Sugar(),
 | 
							AccessLogger: zap.NewNop().Sugar(),
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	srv.Files = NewMemoryFileStore()
 | 
						srv.Files = files.NewMemoryFileStore()
 | 
				
			||||||
	srv.Users = NewMemoryUserStore()
 | 
						srv.Users = users.NewMemoryUserStore()
 | 
				
			||||||
	srv.Auth = NewAuthService(srv.Users, []byte(srv.config.SigningSecret))
 | 
						srv.Auth = gpaste.NewAuthService(srv.Users, []byte(srv.config.SigningSecret))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Create initial user
 | 
						// Create initial user
 | 
				
			||||||
	// TODO: Do properly
 | 
						// TODO: Do properly
 | 
				
			||||||
	user := &User{Username: "admin"}
 | 
						user := &users.User{Username: "admin"}
 | 
				
			||||||
	user.SetPassword("admin")
 | 
						user.SetPassword("admin")
 | 
				
			||||||
	srv.Users.Store(user)
 | 
						srv.Users.Store(user)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -47,6 +50,7 @@ func NewHTTPServer(cfg *ServerConfig) *HTTPServer {
 | 
				
			|||||||
	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)
 | 
						r.Post("/api/login", srv.HandlerAPILogin)
 | 
				
			||||||
 | 
						r.Post("/api/user", srv.HandlerAPIUserCreate)
 | 
				
			||||||
	srv.Handler = r
 | 
						srv.Handler = r
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return srv
 | 
						return srv
 | 
				
			||||||
@@ -57,7 +61,7 @@ func (s *HTTPServer) HandlerIndex(w http.ResponseWriter, r *http.Request) {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request) {
 | 
					func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
	f := &File{
 | 
						f := &files.File{
 | 
				
			||||||
		ID:   uuid.Must(uuid.NewRandom()).String(),
 | 
							ID:   uuid.Must(uuid.NewRandom()).String(),
 | 
				
			||||||
		Body: r.Body,
 | 
							Body: r.Body,
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
@@ -115,13 +119,8 @@ func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
 | 
					func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
	reqID := middleware.GetReqID(r.Context())
 | 
						reqID := middleware.GetReqID(r.Context())
 | 
				
			||||||
	type resp struct {
 | 
					 | 
				
			||||||
		Message string `json:"message"`
 | 
					 | 
				
			||||||
		ID      string `json:"id"`
 | 
					 | 
				
			||||||
		URL     string `json:"url"`
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	var responses []resp
 | 
						var responses []ResponseAPIFilePost
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	if err := r.ParseMultipartForm(1024 * 1024 * 10); err != nil {
 | 
						if err := r.ParseMultipartForm(1024 * 1024 * 10); err != nil {
 | 
				
			||||||
		s.Logger.Warnw("Error parsing multipart form.", "req_id", reqID, "err", err)
 | 
							s.Logger.Warnw("Error parsing multipart form.", "req_id", reqID, "err", err)
 | 
				
			||||||
@@ -132,7 +131,7 @@ func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.R
 | 
				
			|||||||
			s.Logger.Warnw("Error reading file from multipart form.", "req_id", reqID, "error", err)
 | 
								s.Logger.Warnw("Error reading file from multipart form.", "req_id", reqID, "error", err)
 | 
				
			||||||
			return
 | 
								return
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
		f := &File{
 | 
							f := &files.File{
 | 
				
			||||||
			ID:               uuid.Must(uuid.NewRandom()).String(),
 | 
								ID:               uuid.Must(uuid.NewRandom()).String(),
 | 
				
			||||||
			OriginalFilename: fh.Filename,
 | 
								OriginalFilename: fh.Filename,
 | 
				
			||||||
			Body:             ff,
 | 
								Body:             ff,
 | 
				
			||||||
@@ -145,7 +144,7 @@ func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.R
 | 
				
			|||||||
		}
 | 
							}
 | 
				
			||||||
		s.Logger.Infow("Stored file.", "req_id", reqID, "id", f.ID, "filename", f.OriginalFilename, "remote_addr", r.RemoteAddr)
 | 
							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"})
 | 
							responses = append(responses, ResponseAPIFilePost{Message: "OK", ID: f.ID, URL: "TODO"})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -158,10 +157,7 @@ func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.R
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
func (s *HTTPServer) HandlerAPILogin(w http.ResponseWriter, r *http.Request) {
 | 
					func (s *HTTPServer) HandlerAPILogin(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
	reqID := middleware.GetReqID(r.Context())
 | 
						reqID := middleware.GetReqID(r.Context())
 | 
				
			||||||
	expectedRequest := struct {
 | 
						var expectedRequest RequestAPILogin
 | 
				
			||||||
		Username string `json:"username"`
 | 
					 | 
				
			||||||
		Password string `json:"password"`
 | 
					 | 
				
			||||||
	}{}
 | 
					 | 
				
			||||||
	decoder := json.NewDecoder(r.Body)
 | 
						decoder := json.NewDecoder(r.Body)
 | 
				
			||||||
	defer r.Body.Close()
 | 
						defer r.Body.Close()
 | 
				
			||||||
	if err := decoder.Decode(&expectedRequest); err != nil {
 | 
						if err := decoder.Decode(&expectedRequest); err != nil {
 | 
				
			||||||
@@ -175,9 +171,7 @@ func (s *HTTPServer) HandlerAPILogin(w http.ResponseWriter, r *http.Request) {
 | 
				
			|||||||
		return
 | 
							return
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	response := struct {
 | 
						response := ResponseAPILogin{
 | 
				
			||||||
		Token string `json:"token"`
 | 
					 | 
				
			||||||
	}{
 | 
					 | 
				
			||||||
		Token: token,
 | 
							Token: token,
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -188,3 +182,38 @@ func (s *HTTPServer) HandlerAPILogin(w http.ResponseWriter, r *http.Request) {
 | 
				
			|||||||
		s.Logger.Infow("Error encoding json response to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
 | 
							s.Logger.Infow("Error encoding json response to client.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (s *HTTPServer) HandlerAPIUserCreate(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						reqID := middleware.GetReqID(r.Context())
 | 
				
			||||||
 | 
						defer r.Body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						role, err := RoleFromRequest(r)
 | 
				
			||||||
 | 
						if err != nil || role != users.RoleAdmin {
 | 
				
			||||||
 | 
							w.WriteHeader(http.StatusUnauthorized)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var req RequestAPIUserCreate
 | 
				
			||||||
 | 
						decoder := json.NewDecoder(r.Body)
 | 
				
			||||||
 | 
						if err := decoder.Decode(&req); err != nil {
 | 
				
			||||||
 | 
							s.Logger.Debugw("Error parsing request.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
 | 
				
			||||||
 | 
							w.WriteHeader(http.StatusBadRequest)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// TODO: Ensure user does not already exist
 | 
				
			||||||
 | 
						user := &users.User{Username: req.Username}
 | 
				
			||||||
 | 
						if err := user.SetPassword(req.Password); err != nil {
 | 
				
			||||||
 | 
							s.Logger.Warnw("Error setting user password.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
 | 
				
			||||||
 | 
							w.WriteHeader(http.StatusBadRequest)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if err := s.Users.Store(user); err != nil {
 | 
				
			||||||
 | 
							s.Logger.Warnw("Error setting user password.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
 | 
				
			||||||
 | 
							w.WriteHeader(http.StatusInternalServerError)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						w.WriteHeader(http.StatusAccepted)
 | 
				
			||||||
 | 
						s.Logger.Infow("Created user.", "req_id", reqID, "remote_addr", r.RemoteAddr, "username", req.Username)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package api_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
						"bytes"
 | 
				
			||||||
@@ -11,6 +11,8 @@ import (
 | 
				
			|||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/api"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestHandlers(t *testing.T) {
 | 
					func TestHandlers(t *testing.T) {
 | 
				
			||||||
@@ -21,7 +23,7 @@ func TestHandlers(t *testing.T) {
 | 
				
			|||||||
		},
 | 
							},
 | 
				
			||||||
		URL: "http://localhost:8080",
 | 
							URL: "http://localhost:8080",
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	hs := gpaste.NewHTTPServer(cfg)
 | 
						hs := api.NewHTTPServer(cfg)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	t.Run("HandlerIndex", func(t *testing.T) {
 | 
						t.Run("HandlerIndex", func(t *testing.T) {
 | 
				
			||||||
		rr := httptest.NewRecorder()
 | 
							rr := httptest.NewRecorder()
 | 
				
			||||||
@@ -101,7 +103,7 @@ func TestHandlers(t *testing.T) {
 | 
				
			|||||||
		// TODO: Add test
 | 
							// TODO: Add test
 | 
				
			||||||
		username := "admin"
 | 
							username := "admin"
 | 
				
			||||||
		password := "admin"
 | 
							password := "admin"
 | 
				
			||||||
		user := &gpaste.User{Username: username}
 | 
							user := &users.User{Username: username}
 | 
				
			||||||
		if err := user.SetPassword(password); err != nil {
 | 
							if err := user.SetPassword(password); err != nil {
 | 
				
			||||||
			t.Fatalf("Error setting user password: %s", err)
 | 
								t.Fatalf("Error setting user password: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
							
								
								
									
										20
									
								
								api/json.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										20
									
								
								api/json.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,20 @@
 | 
				
			|||||||
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type RequestAPIUserCreate struct {
 | 
				
			||||||
 | 
						Username string `json:"username"`
 | 
				
			||||||
 | 
						Password string `json:"password"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type RequestAPILogin struct {
 | 
				
			||||||
 | 
						Username string `json:"username"`
 | 
				
			||||||
 | 
						Password string `json:"password"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type ResponseAPILogin struct {
 | 
				
			||||||
 | 
						Token string `json:"token"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					type ResponseAPIFilePost struct {
 | 
				
			||||||
 | 
						Message string `json:"message"`
 | 
				
			||||||
 | 
						ID      string `json:"id"`
 | 
				
			||||||
 | 
						URL     string `json:"url"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"context"
 | 
						"context"
 | 
				
			||||||
@@ -7,6 +7,8 @@ import (
 | 
				
			|||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
	"github.com/go-chi/chi/v5/middleware"
 | 
						"github.com/go-chi/chi/v5/middleware"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -15,6 +17,7 @@ type authCtxKey int
 | 
				
			|||||||
const (
 | 
					const (
 | 
				
			||||||
	authCtxUsername authCtxKey = iota
 | 
						authCtxUsername authCtxKey = iota
 | 
				
			||||||
	authCtxAuthLevel
 | 
						authCtxAuthLevel
 | 
				
			||||||
 | 
						authCtxClaims
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
 | 
					func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
 | 
				
			||||||
@@ -65,7 +68,8 @@ func (s *HTTPServer) MiddlewareAuthentication(next http.Handler) http.Handler {
 | 
				
			|||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		ctx := context.WithValue(r.Context(), authCtxUsername, claims.Subject)
 | 
							ctx := context.WithValue(r.Context(), authCtxUsername, claims.Subject)
 | 
				
			||||||
		ctx = context.WithValue(ctx, authCtxAuthLevel, AuthLevelUser)
 | 
							ctx = context.WithValue(ctx, authCtxAuthLevel, claims.Role)
 | 
				
			||||||
 | 
							ctx = context.WithValue(ctx, authCtxClaims, claims)
 | 
				
			||||||
		withCtx := r.WithContext(ctx)
 | 
							withCtx := r.WithContext(ctx)
 | 
				
			||||||
		s.Logger.Debugw("Request is authenticated.", "req_id", reqID, "username", claims.Subject)
 | 
							s.Logger.Debugw("Request is authenticated.", "req_id", reqID, "username", claims.Subject)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -78,7 +82,6 @@ func (s *HTTPServer) MiddlewareAuthentication(next http.Handler) http.Handler {
 | 
				
			|||||||
func UsernameFromRequest(r *http.Request) (string, error) {
 | 
					func UsernameFromRequest(r *http.Request) (string, error) {
 | 
				
			||||||
	rawUsername := r.Context().Value(authCtxUsername)
 | 
						rawUsername := r.Context().Value(authCtxUsername)
 | 
				
			||||||
	if rawUsername == nil {
 | 
						if rawUsername == nil {
 | 
				
			||||||
 | 
					 | 
				
			||||||
		return "", fmt.Errorf("no username")
 | 
							return "", fmt.Errorf("no username")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	username, ok := rawUsername.(string)
 | 
						username, ok := rawUsername.(string)
 | 
				
			||||||
@@ -88,14 +91,26 @@ func UsernameFromRequest(r *http.Request) (string, error) {
 | 
				
			|||||||
	return username, nil
 | 
						return username, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func AuthLevelFromRequest(r *http.Request) (AuthLevel, error) {
 | 
					func RoleFromRequest(r *http.Request) (users.Role, error) {
 | 
				
			||||||
	rawLevel := r.Context().Value(authCtxAuthLevel)
 | 
						rawLevel := r.Context().Value(authCtxAuthLevel)
 | 
				
			||||||
	if rawLevel == nil {
 | 
						if rawLevel == nil {
 | 
				
			||||||
		return AuthLevelUnset, fmt.Errorf("no username")
 | 
							return users.RoleUnset, fmt.Errorf("no username")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	level, ok := rawLevel.(AuthLevel)
 | 
						level, ok := rawLevel.(users.Role)
 | 
				
			||||||
	if !ok {
 | 
						if !ok {
 | 
				
			||||||
		return AuthLevelUnset, fmt.Errorf("no username")
 | 
							return users.RoleUnset, fmt.Errorf("no username")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	return level, nil
 | 
						return level, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func ClaimsFromRequest(r *http.Request) *gpaste.Claims {
 | 
				
			||||||
 | 
						rawClaims := r.Context().Value(authCtxAuthLevel)
 | 
				
			||||||
 | 
						if rawClaims == nil {
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						claims, ok := rawClaims.(*gpaste.Claims)
 | 
				
			||||||
 | 
						if !ok {
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return claims
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										37
									
								
								auth.go
									
									
									
									
									
								
							
							
						
						
									
										37
									
								
								auth.go
									
									
									
									
									
								
							@@ -4,24 +4,23 @@ import (
 | 
				
			|||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
	"github.com/golang-jwt/jwt"
 | 
						"github.com/golang-jwt/jwt"
 | 
				
			||||||
	"github.com/google/uuid"
 | 
						"github.com/google/uuid"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type AuthLevel int
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const (
 | 
					 | 
				
			||||||
	AuthLevelUnset AuthLevel = iota
 | 
					 | 
				
			||||||
	AuthLevelUser
 | 
					 | 
				
			||||||
	AuthLevelAdmin
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type AuthService struct {
 | 
					type AuthService struct {
 | 
				
			||||||
	users      UserStore
 | 
						users      users.UserStore
 | 
				
			||||||
	hmacSecret []byte
 | 
						hmacSecret []byte
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func NewAuthService(store UserStore, signingSecret []byte) *AuthService {
 | 
					type Claims struct {
 | 
				
			||||||
 | 
						Role users.Role `json:"role,omitempty"`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						jwt.StandardClaims
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func NewAuthService(store users.UserStore, signingSecret []byte) *AuthService {
 | 
				
			||||||
	return &AuthService{users: store, hmacSecret: signingSecret}
 | 
						return &AuthService{users: store, hmacSecret: signingSecret}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -36,13 +35,13 @@ func (as *AuthService) Login(username, password string) (string, error) {
 | 
				
			|||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// TODO: Set iss and aud
 | 
						// TODO: Set iss and aud
 | 
				
			||||||
	claims := jwt.StandardClaims{
 | 
						claims := new(Claims)
 | 
				
			||||||
		Subject:   user.Username,
 | 
						claims.Subject = user.Username
 | 
				
			||||||
		ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
 | 
						claims.ExpiresAt = time.Now().Add(7 * 24 * time.Hour).Unix()
 | 
				
			||||||
		NotBefore: time.Now().Unix(),
 | 
						claims.NotBefore = time.Now().Unix()
 | 
				
			||||||
		IssuedAt:  time.Now().Unix(),
 | 
						claims.IssuedAt = time.Now().Unix()
 | 
				
			||||||
		Id:        uuid.NewString(),
 | 
						claims.Id = uuid.NewString()
 | 
				
			||||||
	}
 | 
						claims.Role = user.Role
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
 | 
						token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
 | 
				
			||||||
	signed, err := token.SignedString(as.hmacSecret)
 | 
						signed, err := token.SignedString(as.hmacSecret)
 | 
				
			||||||
@@ -53,8 +52,8 @@ func (as *AuthService) Login(username, password string) (string, error) {
 | 
				
			|||||||
	return signed, nil
 | 
						return signed, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (as *AuthService) ValidateToken(rawToken string) (*jwt.StandardClaims, error) {
 | 
					func (as *AuthService) ValidateToken(rawToken string) (*Claims, error) {
 | 
				
			||||||
	claims := &jwt.StandardClaims{}
 | 
						claims := &Claims{}
 | 
				
			||||||
	token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) {
 | 
						token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) {
 | 
				
			||||||
		return as.hmacSecret, nil
 | 
							return as.hmacSecret, nil
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										23
									
								
								auth_test.go
									
									
									
									
									
								
							
							
						
						
									
										23
									
								
								auth_test.go
									
									
									
									
									
								
							@@ -1,21 +1,24 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package gpaste_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"math/rand"
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
 | 
						"github.com/google/go-cmp/cmp"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestAuth(t *testing.T) {
 | 
					func TestAuth(t *testing.T) {
 | 
				
			||||||
	t.Run("Token", func(t *testing.T) {
 | 
						t.Run("Token", func(t *testing.T) {
 | 
				
			||||||
		us := gpaste.NewMemoryUserStore()
 | 
							us := users.NewMemoryUserStore()
 | 
				
			||||||
		secret := []byte(randomString(16))
 | 
							secret := []byte(randomString(16))
 | 
				
			||||||
		as := gpaste.NewAuthService(us, secret)
 | 
							as := gpaste.NewAuthService(us, secret)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		username := randomString(8)
 | 
							username := randomString(8)
 | 
				
			||||||
		password := randomString(16)
 | 
							password := randomString(16)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		user := &gpaste.User{Username: username}
 | 
							user := &users.User{Username: username, Role: users.RoleAdmin}
 | 
				
			||||||
		if err := user.SetPassword(password); err != nil {
 | 
							if err := user.SetPassword(password); err != nil {
 | 
				
			||||||
			t.Fatalf("error setting user password: %s", err)
 | 
								t.Fatalf("error setting user password: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
@@ -28,12 +31,26 @@ func TestAuth(t *testing.T) {
 | 
				
			|||||||
			t.Fatalf("Error creating token: %s", err)
 | 
								t.Fatalf("Error creating token: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		if _, err := as.ValidateToken(token); err != nil {
 | 
							claims, err := as.ValidateToken(token)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
			t.Fatalf("Error validating token: %s", err)
 | 
								t.Fatalf("Error validating token: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
							if claims.Role != user.Role {
 | 
				
			||||||
 | 
								t.Fatalf("Token role is not correct: %s", cmp.Diff(claims.Role, user.Role))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
		invalidToken := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMyMjk3NjMsImp0aSI6ImUzNDk5NWI1LThiZmMtNDQyNy1iZDgxLWFmNmQ3OTRiYzM0YiIsImlhdCI6MTY0MjYyNDk2MywibmJmIjoxNjQyNjI0OTYzLCJzdWIiOiJYdE5Hemt5ZSJ9.VM6dkwSLaBv8cStkWRVVv9ADjdUrHGHrlB7GB7Ly7n8`
 | 
							invalidToken := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMyMjk3NjMsImp0aSI6ImUzNDk5NWI1LThiZmMtNDQyNy1iZDgxLWFmNmQ3OTRiYzM0YiIsImlhdCI6MTY0MjYyNDk2MywibmJmIjoxNjQyNjI0OTYzLCJzdWIiOiJYdE5Hemt5ZSJ9.VM6dkwSLaBv8cStkWRVVv9ADjdUrHGHrlB7GB7Ly7n8`
 | 
				
			||||||
		if _, err := as.ValidateToken(invalidToken); err == nil {
 | 
							if _, err := as.ValidateToken(invalidToken); err == nil {
 | 
				
			||||||
			t.Fatalf("Invalid token passed validation")
 | 
								t.Fatalf("Invalid token passed validation")
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					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)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										167
									
								
								client/client.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										167
									
								
								client/client.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,167 @@
 | 
				
			|||||||
 | 
					package client
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"bytes"
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
 | 
						"mime/multipart"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/api"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
 | 
						"github.com/google/uuid"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Client struct {
 | 
				
			||||||
 | 
						BaseURL   string
 | 
				
			||||||
 | 
						AuthToken string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						httpClient http.Client
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (c *Client) Login(ctx context.Context, username, password string) error {
 | 
				
			||||||
 | 
						url := fmt.Sprintf("%s/api/login", c.BaseURL)
 | 
				
			||||||
 | 
						// TODO: Change timeout
 | 
				
			||||||
 | 
						ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
 | 
				
			||||||
 | 
						defer cancel()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						body := new(bytes.Buffer)
 | 
				
			||||||
 | 
						requestData := api.RequestAPILogin{
 | 
				
			||||||
 | 
							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 := c.httpClient.Do(req)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return fmt.Errorf("unable to perform request: %s", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						defer resp.Body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if resp.StatusCode != http.StatusOK {
 | 
				
			||||||
 | 
							return fmt.Errorf("got non-ok response from server: %s", resp.Status)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var responseData api.ResponseAPILogin
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						decoder := json.NewDecoder(resp.Body)
 | 
				
			||||||
 | 
						if err := decoder.Decode(&responseData); err != nil {
 | 
				
			||||||
 | 
							return fmt.Errorf("unable to parse response: %s", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						c.AuthToken = responseData.Token
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (c *Client) UserCreate(ctx context.Context, username, password string) error {
 | 
				
			||||||
 | 
						url := fmt.Sprintf("%s/api/user", c.BaseURL)
 | 
				
			||||||
 | 
						body := new(bytes.Buffer)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						requestData := &api.RequestAPIUserCreate{
 | 
				
			||||||
 | 
							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)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						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)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						defer resp.Body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if resp.StatusCode != http.StatusAccepted {
 | 
				
			||||||
 | 
							return fmt.Errorf("got non-ok response from server: %s", resp.Status)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (c *Client) Download(ctx context.Context, id string) (io.ReadCloser, error) {
 | 
				
			||||||
 | 
						url := fmt.Sprintf("%s/api/file/%s", c.BaseURL, id)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, 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 nil, fmt.Errorf("unable to perform request: %s", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if resp.StatusCode != http.StatusOK {
 | 
				
			||||||
 | 
							return nil, fmt.Errorf("got non-ok response from server: %s", resp.Status)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return resp.Body, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (c *Client) Upload(ctx context.Context, files ...*files.File) ([]api.ResponseAPIFilePost, error) {
 | 
				
			||||||
 | 
						url := fmt.Sprintf("%s/api/file", c.BaseURL)
 | 
				
			||||||
 | 
						client := &http.Client{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// TODO: Change timeout
 | 
				
			||||||
 | 
						ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
 | 
				
			||||||
 | 
						defer cancel()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// TODO: Improve buffering
 | 
				
			||||||
 | 
						buf := &bytes.Buffer{}
 | 
				
			||||||
 | 
						mw := multipart.NewWriter(buf)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, file := range files {
 | 
				
			||||||
 | 
							fw, err := mw.CreateFormFile(uuid.Must(uuid.NewRandom()).String(), file.OriginalFilename)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return nil, err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							if _, err := io.Copy(fw, file.Body); err != nil {
 | 
				
			||||||
 | 
								return nil, err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							file.Body.Close()
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						mw.Close()
 | 
				
			||||||
 | 
						req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						req.Header.Add("Content-Type", mw.FormDataContentType())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						resp, err := client.Do(req)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						defer resp.Body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var expectedResp []api.ResponseAPIFilePost
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						decoder := json.NewDecoder(resp.Body)
 | 
				
			||||||
 | 
						if err := decoder.Decode(&expectedResp); err != nil {
 | 
				
			||||||
 | 
							return nil, fmt.Errorf("error decoding response: %w", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, r := range expectedResp {
 | 
				
			||||||
 | 
							fmt.Printf("Uploaded file %s\n", r.ID)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return expectedResp, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										165
									
								
								client/client_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										165
									
								
								client/client_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,165 @@
 | 
				
			|||||||
 | 
					package client_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
 | 
						"net"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/api"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/client"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
 | 
						"github.com/google/go-cmp/cmp"
 | 
				
			||||||
 | 
						"github.com/google/uuid"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestClient(t *testing.T) {
 | 
				
			||||||
 | 
						listener, err := net.Listen("tcp", ":0")
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						port := listener.Addr().(*net.TCPAddr).Port
 | 
				
			||||||
 | 
						cfg := &gpaste.ServerConfig{
 | 
				
			||||||
 | 
							LogLevel:      "ERROR",
 | 
				
			||||||
 | 
							URL:           fmt.Sprintf("http://localhost:%d", port),
 | 
				
			||||||
 | 
							SigningSecret: "TEST",
 | 
				
			||||||
 | 
							Store:         &gpaste.ServerStoreConfig{Type: "memory"},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						srv := api.NewHTTPServer(cfg)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						go func() {
 | 
				
			||||||
 | 
							srv.Serve(listener)
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						t.Cleanup(func() {
 | 
				
			||||||
 | 
							ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 | 
				
			||||||
 | 
							defer cancel()
 | 
				
			||||||
 | 
							srv.Shutdown(ctx)
 | 
				
			||||||
 | 
							listener.Close()
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Add users
 | 
				
			||||||
 | 
						username := "admin"
 | 
				
			||||||
 | 
						password := "admin"
 | 
				
			||||||
 | 
						user := &users.User{
 | 
				
			||||||
 | 
							Username: username,
 | 
				
			||||||
 | 
							Role:     users.RoleAdmin,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if err := user.SetPassword(password); err != nil {
 | 
				
			||||||
 | 
							t.Fatalf("Error setting password: %s", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if err := srv.Users.Store(user); err != nil {
 | 
				
			||||||
 | 
							t.Fatalf("Error storing user: %s", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						t.Run("Login", func(t *testing.T) {
 | 
				
			||||||
 | 
							client := client.Client{BaseURL: cfg.URL}
 | 
				
			||||||
 | 
							ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 | 
				
			||||||
 | 
							defer cancel()
 | 
				
			||||||
 | 
							if err := client.Login(ctx, username, password); err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("Error logging in: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							claims, err := srv.Auth.ValidateToken(client.AuthToken)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								t.Errorf("unable to get claims from token: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							if claims.Role != user.Role {
 | 
				
			||||||
 | 
								t.Errorf("Claims have wrong role: %s", cmp.Diff(claims.Role, user.Role))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							if claims.Subject != username {
 | 
				
			||||||
 | 
								t.Errorf("Claims have wrong role: %s", cmp.Diff(claims.Subject, username))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							t.Run("UserCreate", func(t *testing.T) {
 | 
				
			||||||
 | 
								ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 | 
				
			||||||
 | 
								defer cancel()
 | 
				
			||||||
 | 
								username := "user"
 | 
				
			||||||
 | 
								password := "user"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								if err := client.UserCreate(ctx, username, password); err != nil {
 | 
				
			||||||
 | 
									t.Fatalf("Error creating user: %s", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								user, err := srv.Users.Get(username)
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									t.Fatalf("Error getting new user: %s", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								if user.Username != username {
 | 
				
			||||||
 | 
									t.Errorf("Username does not match.")
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								if err := user.ValidatePassword(password); err != nil {
 | 
				
			||||||
 | 
									t.Errorf("Unable to validate password: %s", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
						t.Run("Upload", func(t *testing.T) {
 | 
				
			||||||
 | 
							client := client.Client{BaseURL: cfg.URL}
 | 
				
			||||||
 | 
							ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 | 
				
			||||||
 | 
							defer cancel()
 | 
				
			||||||
 | 
							fileContents := "this is the test file"
 | 
				
			||||||
 | 
							fileBody := io.NopCloser(strings.NewReader(fileContents))
 | 
				
			||||||
 | 
							file := &files.File{
 | 
				
			||||||
 | 
								OriginalFilename: "filename.txt",
 | 
				
			||||||
 | 
								Body:             fileBody,
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							resp, err := client.Upload(ctx, file)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("Error uploading: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							retrieved, err := srv.Files.Get(resp[0].ID)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("Error getting uploaded file from store: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							defer retrieved.Body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							buf := new(strings.Builder)
 | 
				
			||||||
 | 
							if _, err := io.Copy(buf, retrieved.Body); err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("error reading body from store: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							if buf.String() != fileContents {
 | 
				
			||||||
 | 
								t.Errorf("File contents does not match: %s", cmp.Diff(buf.String(), fileContents))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
						t.Run("Download", func(t *testing.T) {
 | 
				
			||||||
 | 
							client := client.Client{BaseURL: cfg.URL}
 | 
				
			||||||
 | 
							ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 | 
				
			||||||
 | 
							defer cancel()
 | 
				
			||||||
 | 
							fileContents := "this is the test file"
 | 
				
			||||||
 | 
							fileBody := io.NopCloser(strings.NewReader(fileContents))
 | 
				
			||||||
 | 
							file := &files.File{
 | 
				
			||||||
 | 
								ID:               uuid.NewString(),
 | 
				
			||||||
 | 
								OriginalFilename: "filename.txt",
 | 
				
			||||||
 | 
								Body:             fileBody,
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							if err := srv.Files.Store(file); err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("Error putting file in store: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							body, err := client.Download(ctx, file.ID)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("Error uploading: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							defer body.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							buf := new(strings.Builder)
 | 
				
			||||||
 | 
							if _, err := io.Copy(buf, body); err != nil {
 | 
				
			||||||
 | 
								t.Fatalf("error reading body from store: %s", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							if buf.String() != fileContents {
 | 
				
			||||||
 | 
								t.Errorf("File contents does not match: %s", cmp.Diff(buf.String(), fileContents))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										188
									
								
								cmd/client/actions/actions.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										188
									
								
								cmd/client/actions/actions.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,188 @@
 | 
				
			|||||||
 | 
					package actions
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"bytes"
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
 | 
						"mime/multipart"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
 | 
						"syscall"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/api"
 | 
				
			||||||
 | 
						"github.com/google/uuid"
 | 
				
			||||||
 | 
						"github.com/urfave/cli/v2"
 | 
				
			||||||
 | 
						"golang.org/x/term"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					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 ActionUserCreate(c *cli.Context) error {
 | 
				
			||||||
 | 
						// TODO: Needs to supply auth token to actually work
 | 
				
			||||||
 | 
						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/user", 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 := &api.RequestAPIUserCreate{
 | 
				
			||||||
 | 
							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.StatusAccepted {
 | 
				
			||||||
 | 
							return cli.Exit("got non-ok response from server", 0)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						fmt.Printf("Created user %s\n", username)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						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
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,21 +1,11 @@
 | 
				
			|||||||
package main
 | 
					package main
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
					 | 
				
			||||||
	"context"
 | 
					 | 
				
			||||||
	"encoding/json"
 | 
					 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"io"
 | 
					 | 
				
			||||||
	"mime/multipart"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
	"strings"
 | 
					 | 
				
			||||||
	"syscall"
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/google/uuid"
 | 
						"git.t-juice.club/torjus/gpaste/cmd/client/actions"
 | 
				
			||||||
	"github.com/urfave/cli/v2"
 | 
						"github.com/urfave/cli/v2"
 | 
				
			||||||
	"golang.org/x/term"
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
var (
 | 
					var (
 | 
				
			||||||
@@ -45,138 +35,28 @@ func main() {
 | 
				
			|||||||
				Name:      "upload",
 | 
									Name:      "upload",
 | 
				
			||||||
				Usage:     "Upload file(s)",
 | 
									Usage:     "Upload file(s)",
 | 
				
			||||||
				ArgsUsage: "FILE [FILE]...",
 | 
									ArgsUsage: "FILE [FILE]...",
 | 
				
			||||||
				Action:    ActionUpload,
 | 
									Action:    actions.ActionUpload,
 | 
				
			||||||
			},
 | 
								},
 | 
				
			||||||
			{
 | 
								{
 | 
				
			||||||
				Name:      "login",
 | 
									Name:      "login",
 | 
				
			||||||
				Usage:     "Login to gpaste server",
 | 
									Usage:     "Login to gpaste server",
 | 
				
			||||||
				ArgsUsage: "USERNAME",
 | 
									ArgsUsage: "USERNAME",
 | 
				
			||||||
				Action:    ActionLogin,
 | 
									Action:    actions.ActionLogin,
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
								{
 | 
				
			||||||
 | 
									Name:  "admin",
 | 
				
			||||||
 | 
									Usage: "Admin related commands",
 | 
				
			||||||
 | 
									Subcommands: []*cli.Command{
 | 
				
			||||||
 | 
										{
 | 
				
			||||||
 | 
											Name:      "create-user",
 | 
				
			||||||
 | 
											Usage:     "Create a new user",
 | 
				
			||||||
 | 
											ArgsUsage: "USERNAME",
 | 
				
			||||||
 | 
											Action:    actions.ActionUserCreate,
 | 
				
			||||||
 | 
										},
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
			},
 | 
								},
 | 
				
			||||||
		},
 | 
							},
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	app.Run(os.Args)
 | 
						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
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										105
									
								
								cmd/server/actions/actions.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										105
									
								
								cmd/server/actions/actions.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,105 @@
 | 
				
			|||||||
 | 
					package actions
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"os/signal"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste"
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/api"
 | 
				
			||||||
 | 
						"github.com/urfave/cli/v2"
 | 
				
			||||||
 | 
						"go.uber.org/zap"
 | 
				
			||||||
 | 
						"go.uber.org/zap/zapcore"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func ActionServe(c *cli.Context) error {
 | 
				
			||||||
 | 
						configPath := "gpaste-server.toml"
 | 
				
			||||||
 | 
						if c.IsSet("config") {
 | 
				
			||||||
 | 
							configPath = c.String("config")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						f, err := os.Open(configPath)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return cli.Exit(err, 1)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						defer f.Close()
 | 
				
			||||||
 | 
						cfg, err := gpaste.ServerConfigFromReader(f)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return cli.Exit(err, 1)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						// Setup loggers
 | 
				
			||||||
 | 
						rootLogger := getRootLogger(cfg.LogLevel)
 | 
				
			||||||
 | 
						serverLogger := rootLogger.Named("SERV")
 | 
				
			||||||
 | 
						accessLogger := rootLogger.Named("ACCS")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Setup contexts for clean shutdown
 | 
				
			||||||
 | 
						rootCtx, rootCancel := signal.NotifyContext(context.Background(), os.Interrupt)
 | 
				
			||||||
 | 
						defer rootCancel()
 | 
				
			||||||
 | 
						httpCtx, httpCancel := context.WithCancel(rootCtx)
 | 
				
			||||||
 | 
						defer httpCancel()
 | 
				
			||||||
 | 
						httpShutdownCtx, httpShutdownCancel := context.WithCancel(context.Background())
 | 
				
			||||||
 | 
						defer httpShutdownCancel()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						go func() {
 | 
				
			||||||
 | 
							srv := api.NewHTTPServer(cfg)
 | 
				
			||||||
 | 
							srv.Addr = cfg.ListenAddr
 | 
				
			||||||
 | 
							srv.Logger = serverLogger
 | 
				
			||||||
 | 
							srv.AccessLogger = accessLogger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// Wait for cancel
 | 
				
			||||||
 | 
							go func() {
 | 
				
			||||||
 | 
								<-httpCtx.Done()
 | 
				
			||||||
 | 
								timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 | 
				
			||||||
 | 
								defer cancel()
 | 
				
			||||||
 | 
								srv.Shutdown(timeoutCtx)
 | 
				
			||||||
 | 
							}()
 | 
				
			||||||
 | 
							serverLogger.Infow("Starting HTTP server.", "addr", cfg.ListenAddr)
 | 
				
			||||||
 | 
							if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
 | 
				
			||||||
 | 
								serverLogger.Errorw("Error during shutdown.", "error", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							serverLogger.Infow("HTTP server shutdown complete.", "addr", cfg.ListenAddr)
 | 
				
			||||||
 | 
							httpShutdownCancel()
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
						<-httpShutdownCtx.Done()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func getRootLogger(level string) *zap.SugaredLogger {
 | 
				
			||||||
 | 
						logEncoderConfig := zap.NewProductionEncoderConfig()
 | 
				
			||||||
 | 
						logEncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
 | 
				
			||||||
 | 
						logEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
 | 
				
			||||||
 | 
						logEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
 | 
				
			||||||
 | 
						logEncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rootLoggerConfig := &zap.Config{
 | 
				
			||||||
 | 
							Level:            zap.NewAtomicLevelAt(zap.DebugLevel),
 | 
				
			||||||
 | 
							OutputPaths:      []string{"stdout"},
 | 
				
			||||||
 | 
							ErrorOutputPaths: []string{"stdout"},
 | 
				
			||||||
 | 
							Encoding:         "console",
 | 
				
			||||||
 | 
							EncoderConfig:    logEncoderConfig,
 | 
				
			||||||
 | 
							DisableCaller:    true,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						switch strings.ToUpper(level) {
 | 
				
			||||||
 | 
						case "DEBUG":
 | 
				
			||||||
 | 
							rootLoggerConfig.DisableCaller = false
 | 
				
			||||||
 | 
							rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
 | 
				
			||||||
 | 
						case "INFO":
 | 
				
			||||||
 | 
							rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
 | 
				
			||||||
 | 
						case "WARN", "WARNING":
 | 
				
			||||||
 | 
							rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
 | 
				
			||||||
 | 
						case "ERR", "ERROR":
 | 
				
			||||||
 | 
							rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rootLogger, err := rootLoggerConfig.Build()
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return rootLogger.Sugar()
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,18 +1,11 @@
 | 
				
			|||||||
package main
 | 
					package main
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"context"
 | 
					 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
	"os/signal"
 | 
					 | 
				
			||||||
	"strings"
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/cmd/server/actions"
 | 
				
			||||||
	"github.com/urfave/cli/v2"
 | 
						"github.com/urfave/cli/v2"
 | 
				
			||||||
	"go.uber.org/zap"
 | 
					 | 
				
			||||||
	"go.uber.org/zap/zapcore"
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
var (
 | 
					var (
 | 
				
			||||||
@@ -33,97 +26,8 @@ func main() {
 | 
				
			|||||||
				Usage: "Path to config-file.",
 | 
									Usage: "Path to config-file.",
 | 
				
			||||||
			},
 | 
								},
 | 
				
			||||||
		},
 | 
							},
 | 
				
			||||||
		Action: ActionServe,
 | 
							Action: actions.ActionServe,
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	app.Run(os.Args)
 | 
						app.Run(os.Args)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					 | 
				
			||||||
func ActionServe(c *cli.Context) error {
 | 
					 | 
				
			||||||
	configPath := "gpaste-server.toml"
 | 
					 | 
				
			||||||
	if c.IsSet("config") {
 | 
					 | 
				
			||||||
		configPath = c.String("config")
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	f, err := os.Open(configPath)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		return cli.Exit(err, 1)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	defer f.Close()
 | 
					 | 
				
			||||||
	cfg, err := gpaste.ServerConfigFromReader(f)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		return cli.Exit(err, 1)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	// Setup loggers
 | 
					 | 
				
			||||||
	rootLogger := getRootLogger(cfg.LogLevel)
 | 
					 | 
				
			||||||
	serverLogger := rootLogger.Named("SERV")
 | 
					 | 
				
			||||||
	accessLogger := rootLogger.Named("ACCS")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Setup contexts for clean shutdown
 | 
					 | 
				
			||||||
	rootCtx, rootCancel := signal.NotifyContext(context.Background(), os.Interrupt)
 | 
					 | 
				
			||||||
	defer rootCancel()
 | 
					 | 
				
			||||||
	httpCtx, httpCancel := context.WithCancel(rootCtx)
 | 
					 | 
				
			||||||
	defer httpCancel()
 | 
					 | 
				
			||||||
	httpShutdownCtx, httpShutdownCancel := context.WithCancel(context.Background())
 | 
					 | 
				
			||||||
	defer httpShutdownCancel()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	go func() {
 | 
					 | 
				
			||||||
		srv := gpaste.NewHTTPServer(cfg)
 | 
					 | 
				
			||||||
		srv.Addr = cfg.ListenAddr
 | 
					 | 
				
			||||||
		srv.Logger = serverLogger
 | 
					 | 
				
			||||||
		srv.AccessLogger = accessLogger
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
		// Wait for cancel
 | 
					 | 
				
			||||||
		go func() {
 | 
					 | 
				
			||||||
			<-httpCtx.Done()
 | 
					 | 
				
			||||||
			timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 | 
					 | 
				
			||||||
			defer cancel()
 | 
					 | 
				
			||||||
			srv.Shutdown(timeoutCtx)
 | 
					 | 
				
			||||||
		}()
 | 
					 | 
				
			||||||
		serverLogger.Infow("Starting HTTP server.", "addr", cfg.ListenAddr)
 | 
					 | 
				
			||||||
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
 | 
					 | 
				
			||||||
			serverLogger.Errorw("Error during shutdown.", "error", err)
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
		serverLogger.Infow("HTTP server shutdown complete.", "addr", cfg.ListenAddr)
 | 
					 | 
				
			||||||
		httpShutdownCancel()
 | 
					 | 
				
			||||||
	}()
 | 
					 | 
				
			||||||
	<-httpShutdownCtx.Done()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return nil
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func getRootLogger(level string) *zap.SugaredLogger {
 | 
					 | 
				
			||||||
	logEncoderConfig := zap.NewProductionEncoderConfig()
 | 
					 | 
				
			||||||
	logEncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
 | 
					 | 
				
			||||||
	logEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
 | 
					 | 
				
			||||||
	logEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
 | 
					 | 
				
			||||||
	logEncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	rootLoggerConfig := &zap.Config{
 | 
					 | 
				
			||||||
		Level:            zap.NewAtomicLevelAt(zap.DebugLevel),
 | 
					 | 
				
			||||||
		OutputPaths:      []string{"stdout"},
 | 
					 | 
				
			||||||
		ErrorOutputPaths: []string{"stdout"},
 | 
					 | 
				
			||||||
		Encoding:         "console",
 | 
					 | 
				
			||||||
		EncoderConfig:    logEncoderConfig,
 | 
					 | 
				
			||||||
		DisableCaller:    true,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	switch strings.ToUpper(level) {
 | 
					 | 
				
			||||||
	case "DEBUG":
 | 
					 | 
				
			||||||
		rootLoggerConfig.DisableCaller = false
 | 
					 | 
				
			||||||
		rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
 | 
					 | 
				
			||||||
	case "INFO":
 | 
					 | 
				
			||||||
		rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
 | 
					 | 
				
			||||||
	case "WARN", "WARNING":
 | 
					 | 
				
			||||||
		rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
 | 
					 | 
				
			||||||
	case "ERR", "ERROR":
 | 
					 | 
				
			||||||
		rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	rootLogger, err := rootLoggerConfig.Build()
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		panic(err)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return rootLogger.Sugar()
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package files
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"io"
 | 
						"io"
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package files
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"encoding/json"
 | 
						"encoding/json"
 | 
				
			||||||
@@ -1,22 +1,22 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package files_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestFSFileStore(t *testing.T) {
 | 
					func TestFSFileStore(t *testing.T) {
 | 
				
			||||||
	dir := t.TempDir()
 | 
						dir := t.TempDir()
 | 
				
			||||||
	s, err := gpaste.NewFSFileStore(dir)
 | 
						s, err := files.NewFSFileStore(dir)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		t.Fatalf("Error creating store: %s", err)
 | 
							t.Fatalf("Error creating store: %s", err)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	RunFilestoreTest(s, t)
 | 
						RunFilestoreTest(s, t)
 | 
				
			||||||
	persistentDir := t.TempDir()
 | 
						persistentDir := t.TempDir()
 | 
				
			||||||
	newFunc := func() gpaste.FileStore {
 | 
						newFunc := func() files.FileStore {
 | 
				
			||||||
		s, err := gpaste.NewFSFileStore(persistentDir)
 | 
							s, err := files.NewFSFileStore(persistentDir)
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			t.Fatalf("Error creating store: %s", err)
 | 
								t.Fatalf("Error creating store: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package files
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
						"bytes"
 | 
				
			||||||
@@ -1,13 +1,13 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package files_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestMemoryFileStore(t *testing.T) {
 | 
					func TestMemoryFileStore(t *testing.T) {
 | 
				
			||||||
	s := gpaste.NewMemoryFileStore()
 | 
						s := files.NewMemoryFileStore()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	RunFilestoreTest(s, t)
 | 
						RunFilestoreTest(s, t)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package files_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
						"bytes"
 | 
				
			||||||
@@ -7,12 +7,12 @@ import (
 | 
				
			|||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/files"
 | 
				
			||||||
	"github.com/google/go-cmp/cmp"
 | 
						"github.com/google/go-cmp/cmp"
 | 
				
			||||||
	"github.com/google/uuid"
 | 
						"github.com/google/uuid"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func RunFilestoreTest(s gpaste.FileStore, t *testing.T) {
 | 
					func RunFilestoreTest(s files.FileStore, t *testing.T) {
 | 
				
			||||||
	t.Run("Basic", func(t *testing.T) {
 | 
						t.Run("Basic", func(t *testing.T) {
 | 
				
			||||||
		// Create
 | 
							// Create
 | 
				
			||||||
		dataString := "TEST_LOL_OMG"
 | 
							dataString := "TEST_LOL_OMG"
 | 
				
			||||||
@@ -20,7 +20,7 @@ func RunFilestoreTest(s gpaste.FileStore, t *testing.T) {
 | 
				
			|||||||
		bodyBuf := &bytes.Buffer{}
 | 
							bodyBuf := &bytes.Buffer{}
 | 
				
			||||||
		bodyBuf.Write([]byte(dataString))
 | 
							bodyBuf.Write([]byte(dataString))
 | 
				
			||||||
		body := io.NopCloser(bodyBuf)
 | 
							body := io.NopCloser(bodyBuf)
 | 
				
			||||||
		f := &gpaste.File{
 | 
							f := &files.File{
 | 
				
			||||||
			ID:       id,
 | 
								ID:       id,
 | 
				
			||||||
			MaxViews: 0,
 | 
								MaxViews: 0,
 | 
				
			||||||
			Body:     body,
 | 
								Body:     body,
 | 
				
			||||||
@@ -78,15 +78,15 @@ func RunFilestoreTest(s gpaste.FileStore, t *testing.T) {
 | 
				
			|||||||
	})
 | 
						})
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func RunPersistentFilestoreTest(newStoreFunc func() gpaste.FileStore, t *testing.T) {
 | 
					func RunPersistentFilestoreTest(newStoreFunc func() files.FileStore, t *testing.T) {
 | 
				
			||||||
	s := newStoreFunc()
 | 
						s := newStoreFunc()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	files := []struct {
 | 
						files := []struct {
 | 
				
			||||||
		File         *gpaste.File
 | 
							File         *files.File
 | 
				
			||||||
		ExpectedData string
 | 
							ExpectedData string
 | 
				
			||||||
	}{
 | 
						}{
 | 
				
			||||||
		{
 | 
							{
 | 
				
			||||||
			File: &gpaste.File{
 | 
								File: &files.File{
 | 
				
			||||||
				ID:               uuid.NewString(),
 | 
									ID:               uuid.NewString(),
 | 
				
			||||||
				OriginalFilename: "testfile.txt",
 | 
									OriginalFilename: "testfile.txt",
 | 
				
			||||||
				MaxViews:         5,
 | 
									MaxViews:         5,
 | 
				
			||||||
@@ -96,7 +96,7 @@ func RunPersistentFilestoreTest(newStoreFunc func() gpaste.FileStore, t *testing
 | 
				
			|||||||
			ExpectedData: "cocks!",
 | 
								ExpectedData: "cocks!",
 | 
				
			||||||
		},
 | 
							},
 | 
				
			||||||
		{
 | 
							{
 | 
				
			||||||
			File: &gpaste.File{
 | 
								File: &files.File{
 | 
				
			||||||
				ID:               uuid.NewString(),
 | 
									ID:               uuid.NewString(),
 | 
				
			||||||
				OriginalFilename: "testfile2.txt",
 | 
									OriginalFilename: "testfile2.txt",
 | 
				
			||||||
				MaxViews:         5,
 | 
									MaxViews:         5,
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package users
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import "golang.org/x/crypto/bcrypt"
 | 
					import "golang.org/x/crypto/bcrypt"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -13,7 +13,7 @@ const (
 | 
				
			|||||||
type User struct {
 | 
					type User struct {
 | 
				
			||||||
	Username       string `json:"username"`
 | 
						Username       string `json:"username"`
 | 
				
			||||||
	HashedPassword []byte `json:"hashed_password"`
 | 
						HashedPassword []byte `json:"hashed_password"`
 | 
				
			||||||
	Roles          []Role `json:"roles"`
 | 
						Role           Role   `json:"role"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type UserStore interface {
 | 
					type UserStore interface {
 | 
				
			||||||
@@ -1,10 +1,10 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package users_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"math/rand"
 | 
						"math/rand"
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestUser(t *testing.T) {
 | 
					func TestUser(t *testing.T) {
 | 
				
			||||||
@@ -15,7 +15,7 @@ func TestUser(t *testing.T) {
 | 
				
			|||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		for username, password := range userMap {
 | 
							for username, password := range userMap {
 | 
				
			||||||
			user := &gpaste.User{Username: username}
 | 
								user := &users.User{Username: username}
 | 
				
			||||||
			if err := user.SetPassword(password); err != nil {
 | 
								if err := user.SetPassword(password); err != nil {
 | 
				
			||||||
				t.Fatalf("Error setting password: %s", err)
 | 
									t.Fatalf("Error setting password: %s", err)
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package users
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"encoding/json"
 | 
						"encoding/json"
 | 
				
			||||||
@@ -1,18 +1,18 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package users_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"path/filepath"
 | 
						"path/filepath"
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestBoltUserStore(t *testing.T) {
 | 
					func TestBoltUserStore(t *testing.T) {
 | 
				
			||||||
	tmpDir := t.TempDir()
 | 
						tmpDir := t.TempDir()
 | 
				
			||||||
	newFunc := func() (func(), gpaste.UserStore) {
 | 
						newFunc := func() (func(), users.UserStore) {
 | 
				
			||||||
		tmpFile := filepath.Join(tmpDir, randomString(8))
 | 
							tmpFile := filepath.Join(tmpDir, randomString(8))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		store, err := gpaste.NewBoltUserStore(tmpFile)
 | 
							store, err := users.NewBoltUserStore(tmpFile)
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			t.Fatalf("Error creating store: %s", err)
 | 
								t.Fatalf("Error creating store: %s", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package gpaste
 | 
					package users
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
							
								
								
									
										15
									
								
								users/userstore_memory_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								users/userstore_memory_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,15 @@
 | 
				
			|||||||
 | 
					package users_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestMemoryUserStore(t *testing.T) {
 | 
				
			||||||
 | 
						newFunc := func() (func(), users.UserStore) {
 | 
				
			||||||
 | 
							return func() {}, users.NewMemoryUserStore()
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						RunUserStoreTest(newFunc, t)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,26 +1,26 @@
 | 
				
			|||||||
package gpaste_test
 | 
					package users_test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"testing"
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"git.t-juice.club/torjus/gpaste"
 | 
						"git.t-juice.club/torjus/gpaste/users"
 | 
				
			||||||
	"github.com/google/go-cmp/cmp"
 | 
						"github.com/google/go-cmp/cmp"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func RunUserStoreTest(newFunc func() (func(), gpaste.UserStore), t *testing.T) {
 | 
					func RunUserStoreTest(newFunc func() (func(), users.UserStore), t *testing.T) {
 | 
				
			||||||
	t.Run("Basics", func(t *testing.T) {
 | 
						t.Run("Basics", func(t *testing.T) {
 | 
				
			||||||
		cleanup, s := newFunc()
 | 
							cleanup, s := newFunc()
 | 
				
			||||||
		t.Cleanup(cleanup)
 | 
							t.Cleanup(cleanup)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		userMap := make(map[string]*gpaste.User)
 | 
							userMap := make(map[string]*users.User)
 | 
				
			||||||
		passwordMap := make(map[string]string)
 | 
							passwordMap := make(map[string]string)
 | 
				
			||||||
		for i := 0; i < 10; i++ {
 | 
							for i := 0; i < 10; i++ {
 | 
				
			||||||
			username := randomString(8)
 | 
								username := randomString(8)
 | 
				
			||||||
			password := randomString(16)
 | 
								password := randomString(16)
 | 
				
			||||||
			passwordMap[username] = password
 | 
								passwordMap[username] = password
 | 
				
			||||||
			user := &gpaste.User{
 | 
								user := &users.User{
 | 
				
			||||||
				Username: username,
 | 
									Username: username,
 | 
				
			||||||
				Roles:    []gpaste.Role{gpaste.RoleAdmin},
 | 
									Role:     users.RoleAdmin,
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
			if err := user.SetPassword(password); err != nil {
 | 
								if err := user.SetPassword(password); err != nil {
 | 
				
			||||||
				t.Fatalf("Error setting password: %s", err)
 | 
									t.Fatalf("Error setting password: %s", err)
 | 
				
			||||||
@@ -1,15 +0,0 @@
 | 
				
			|||||||
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)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
		Reference in New Issue
	
	Block a user