From 97f540d7fcd1571e93f375d401474aec7464ff40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Thu, 19 Oct 2023 23:15:55 +0200 Subject: [PATCH] Initial commit --- Dockerfile | 12 +++ cmd/main.go | 30 ++++++ go.mod | 18 ++++ go.sum | 34 +++++++ mf-users.toml | 3 + model.go | 62 ++++++++++++ server/config.go | 23 +++++ server/server.go | 245 +++++++++++++++++++++++++++++++++++++++++++++++ store/memory.go | 61 ++++++++++++ store/store.go | 10 ++ version.go | 3 + 11 files changed, 501 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 mf-users.toml create mode 100644 model.go create mode 100644 server/config.go create mode 100644 server/server.go create mode 100644 store/memory.go create mode 100644 store/store.go create mode 100644 version.go diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e0c7e83 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM golang:alpine as build +WORKDIR /app +COPY go.sum /app/go.sum +COPY go.mod /app/go.mod +RUN go mod download +COPY . /app +RUN go build -o mf-users cmd/main.go + +FROM golang:alpine +COPY --from=build /app/mf-users /usr/bin/mf-users +WORKDIR /app +CMD ["/usr/bin/mf-users"] \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..a1578f0 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "os" + + "git.t-juice.club/microfilm/users/server" +) + +func main() { + f, err := os.Open("mf-users.toml") + if err != nil { + fmt.Printf("Error opening config: %s", err) + os.Exit(1) + } + + cfg, err := server.ConfigFromReader(f) + if err != nil { + fmt.Printf("Error parsing config: %s", err) + os.Exit(1) + } + srv, err := server.NewServer(cfg) + if err != nil { + fmt.Printf("Error parsing config: %s", err) + os.Exit(2) + } + + fmt.Printf("Starting server: %s\n", srv.Addr) + srv.ListenAndServe() +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e0ffecc --- /dev/null +++ b/go.mod @@ -0,0 +1,18 @@ +module git.t-juice.club/microfilm/users + +go 1.21 + +require ( + github.com/go-chi/chi/v5 v5.0.10 + github.com/google/uuid v1.3.1 + github.com/nats-io/nats.go v1.31.0 + github.com/pelletier/go-toml/v2 v2.1.0 + golang.org/x/crypto v0.14.0 +) + +require ( + github.com/klauspost/compress v1.17.0 // indirect + github.com/nats-io/nkeys v0.4.5 // indirect + github.com/nats-io/nuid v1.0.1 // indirect + golang.org/x/sys v0.13.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e54c58a --- /dev/null +++ b/go.sum @@ -0,0 +1,34 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= +github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= +github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/nats-io/nats.go v1.31.0 h1:/WFBHEc/dOKBF6qf1TZhrdEfTmOZ5JzdJ+Y3m6Y/p7E= +github.com/nats-io/nats.go v1.31.0/go.mod h1:di3Bm5MLsoB4Bx61CBTsxuarI36WbhAwOm8QrW39+i8= +github.com/nats-io/nkeys v0.4.5 h1:Zdz2BUlFm4fJlierwvGK+yl20IAKUm7eV6AAZXEhkPk= +github.com/nats-io/nkeys v0.4.5/go.mod h1:XUkxdLPTufzlihbamfzQ7mw/VGx6ObUs+0bN5sNvt64= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= +github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/mf-users.toml b/mf-users.toml new file mode 100644 index 0000000..6976c62 --- /dev/null +++ b/mf-users.toml @@ -0,0 +1,3 @@ +ListenAddr = ":8080" +NATSAddr = "nats:4222" +NATSSubject = "microfilm.users.v1" \ No newline at end of file diff --git a/model.go b/model.go new file mode 100644 index 0000000..ed181ca --- /dev/null +++ b/model.go @@ -0,0 +1,62 @@ +package users + +import "golang.org/x/crypto/bcrypt" + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + HashedPassword []byte `json:"-"` +} + +func (u *User) SetPassword(password string) error { + hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + + u.HashedPassword = hashed + + return nil +} + +func (u *User) ComparePassword(password string) error { + return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password)) +} + +type InfoResponse struct { + Version string `json:"version"` +} + +type ErrorResponse struct { + Status int `json:"status"` + Message string `json:"message"` +} + +type CreateUserRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type CreateUserResponse struct { + Message string `json:"message"` + User User `json:"user"` +} + +type SetPasswordRequest struct { + NewPassword string `json:"newPassword"` +} + +type VerifyRequest struct { + Password string `json:"password"` +} + +// Messages +type MsgUserUpdate struct { + Message string `json:"message"` + ID string `json:"id"` +} + +type MsgUserCreate struct { + Message string `json:"message"` + User User `json:"user"` +} diff --git a/server/config.go b/server/config.go new file mode 100644 index 0000000..c69eced --- /dev/null +++ b/server/config.go @@ -0,0 +1,23 @@ +package server + +import ( + "io" + + "github.com/pelletier/go-toml/v2" +) + +type Config struct { + ListenAddr string `toml:"ListenAddr"` + NATSAddr string `toml:"NATSAddr"` + NATSSubject string `toml:"NATSSubject"` +} + +func ConfigFromReader(r io.Reader) (*Config, error) { + decoder := toml.NewDecoder(r) + var c Config + if err := decoder.Decode(&c); err != nil { + return nil, err + } + + return &c, nil +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..aa57c3c --- /dev/null +++ b/server/server.go @@ -0,0 +1,245 @@ +package server + +import ( + "bytes" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "os" + + "git.t-juice.club/microfilm/users" + "git.t-juice.club/microfilm/users/store" + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + "github.com/nats-io/nats.go" +) + +type UserServer struct { + http.Server + store store.UserStore + config *Config + nats *nats.Conn + logger *slog.Logger +} + +func NewServer(config *Config) (*UserServer, error) { + r := chi.NewRouter() + srv := &UserServer{} + srv.config = config + + srv.logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelDebug, + })) + + r.Get("/", InfoHandler) + r.Post("/users", srv.CreateUserHandler) + r.Post("/users/:id/password", srv.SetPasswordHandler) + + srv.Addr = config.ListenAddr + + srv.Handler = r + srv.store = store.NewMemoryStore() + + conn, err := nats.Connect(config.NATSAddr) + if err != nil { + return nil, err + } + + srv.nats = conn + + return srv, nil +} + +func InfoHandler(w http.ResponseWriter, r *http.Request) { + enc := json.NewEncoder(w) + + data := &users.InfoResponse{ + Version: users.Version, + } + + _ = enc.Encode(data) +} + +func WriteError(w http.ResponseWriter, response users.ErrorResponse) { + encoder := json.NewEncoder(w) + w.WriteHeader(response.Status) + _ = encoder.Encode(&response) +} + +func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) { + decoder := json.NewDecoder(r.Body) + defer r.Body.Close() + + var request users.CreateUserRequest + + if err := decoder.Decode(&request); err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Error parsing request: %s", err), + }) + return + } + + id := uuid.Must(uuid.NewRandom()) + u := users.User{ + ID: id.String(), + Username: request.Username, + } + + if err := u.SetPassword(request.Password); err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusInternalServerError, + Message: fmt.Sprintf("Error setting user password: %s", err), + }) + return + } + + if err := s.store.AddUser(u); err != nil { + s.logger.Warn("Error storing user", "error", err) + WriteError(w, users.ErrorResponse{ + Status: http.StatusInternalServerError, + Message: fmt.Sprintf("Error storing user: %s", err), + }) + return + } + + // Message + sub := fmt.Sprintf("%s.%s", s.config.NATSSubject, "create") + + var buf bytes.Buffer + msg := &users.MsgUserCreate{ + Message: "User created.", + User: u, + } + encoder := json.NewEncoder(&buf) + _ = encoder.Encode(&msg) + if err := s.nats.Publish(sub, buf.Bytes()); err != nil { + s.logger.Warn("Error publishing message", "error", err) + } + + s.logger.Info("User created.", "username", u.Username, "id", u.ID) + + response := &users.CreateUserResponse{ + Message: "User created.", + User: u, + } + + encoder = json.NewEncoder(w) + _ = encoder.Encode(&response) +} + +func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request) { + decoder := json.NewDecoder(r.Body) + defer r.Body.Close() + + var request users.SetPasswordRequest + + if err := decoder.Decode(&request); err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Error parsing request: %s", err), + }) + return + } + + id := chi.URLParam(r, "id") + if id == "" { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Invalid user ID: %s", id), + }) + } + + u, err := s.store.GetUser(id) + if err != nil { + msg := fmt.Sprintf("Server error: %s", err) + status := http.StatusInternalServerError + + switch err { + case store.ErrNoSuchUser: + msg = "No user with that ID" + status = http.StatusNotFound + } + + WriteError(w, users.ErrorResponse{ + Status: status, + Message: msg, + }) + return + } + + if err := u.SetPassword(request.NewPassword); err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Unable to set password: %s", id), + }) + } + + if err := s.store.UpdateUser(u); err != nil { + s.logger.Warn("Unable to update user.", "id", u.ID, "error", err) + WriteError(w, users.ErrorResponse{ + Status: http.StatusInternalServerError, + Message: fmt.Sprintf("Unable to set password: %s", id), + }) + } + + sub := fmt.Sprintf("%s.%s", s.config.NATSSubject, "update") + var buf bytes.Buffer + encoder := json.NewEncoder(&buf) + _ = encoder.Encode(&users.MsgUserUpdate{Message: "Password updated", ID: u.ID}) + + if err := s.nats.Publish(sub, buf.Bytes()); err != nil { + s.logger.Warn("Error publishing message", "error", err) + } + s.logger.Info("User password updated.", "id", u.ID) +} + +func (s *UserServer) VerifyHandler(w http.ResponseWriter, r *http.Request) { + decoder := json.NewDecoder(r.Body) + defer r.Body.Close() + + var request users.VerifyRequest + + if err := decoder.Decode(&request); err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Error parsing request: %s", err), + }) + return + } + + id := chi.URLParam(r, "id") + if id == "" { + WriteError(w, users.ErrorResponse{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("Invalid user ID: %s", id), + }) + } + + u, err := s.store.GetUser(id) + if err != nil { + msg := fmt.Sprintf("Server error: %s", err) + status := http.StatusInternalServerError + + switch err { + case store.ErrNoSuchUser: + msg = "No user with that ID" + status = http.StatusNotFound + } + + WriteError(w, users.ErrorResponse{ + Status: status, + Message: msg, + }) + return + } + + err = u.ComparePassword(request.Password) + if err != nil { + WriteError(w, users.ErrorResponse{ + Status: http.StatusUnauthorized, + Message: "Password verification failed.", + }) + } +} diff --git a/store/memory.go b/store/memory.go new file mode 100644 index 0000000..a3610f8 --- /dev/null +++ b/store/memory.go @@ -0,0 +1,61 @@ +package store + +import ( + "fmt" + + "git.t-juice.club/microfilm/users" +) + +var ( + ErrNoSuchUser = fmt.Errorf("no such user") + ErrUserExists = fmt.Errorf("user alread exists") +) + +type MemoryStore struct { + Users map[string]users.User +} + +func NewMemoryStore() *MemoryStore { + return &MemoryStore{ + Users: make(map[string]users.User), + } +} + +func (s *MemoryStore) AddUser(u users.User) error { + if _, ok := s.Users[u.ID]; ok { + return ErrUserExists + } + + s.Users[u.ID] = u + + return nil +} + +func (s *MemoryStore) DeleteUser(id string) error { + if _, ok := s.Users[id]; !ok { + return ErrNoSuchUser + } + + delete(s.Users, id) + + return nil +} + +func (s *MemoryStore) UpdateUser(u users.User) error { + if _, ok := s.Users[u.ID]; !ok { + return ErrNoSuchUser + } + + s.Users[u.ID] = u + + return nil +} + +func (s *MemoryStore) GetUser(id string) (users.User, error) { + u, ok := s.Users[id] + if !ok { + return u, ErrNoSuchUser + } + + return u, nil +} diff --git a/store/store.go b/store/store.go new file mode 100644 index 0000000..45a3612 --- /dev/null +++ b/store/store.go @@ -0,0 +1,10 @@ +package store + +import "git.t-juice.club/microfilm/users" + +type UserStore interface { + AddUser(users.User) error + DeleteUser(id string) error + UpdateUser(users.User) error + GetUser(id string) (users.User, error) +} diff --git a/version.go b/version.go new file mode 100644 index 0000000..0460a4d --- /dev/null +++ b/version.go @@ -0,0 +1,3 @@ +package users + +const Version = "v0.1.0"