Compare commits

...

6 Commits

7 changed files with 101 additions and 17 deletions

View File

@ -1,7 +1,9 @@
FROM golang:alpine as build FROM golang:alpine as build
RUN apk add --no-cache git
WORKDIR /app WORKDIR /app
COPY go.sum /app/go.sum COPY go.sum /app/go.sum
COPY go.mod /app/go.mod COPY go.mod /app/go.mod
ENV GOPRIVATE=git.t-juice.club
RUN go mod download RUN go mod download
COPY . /app COPY . /app
RUN go build -o mf-users cmd/main.go RUN go build -o mf-users cmd/main.go

4
go.mod
View File

@ -1,6 +1,6 @@
module git.t-juice.club/microfilm/users module git.t-juice.club/microfilm/users
go 1.21 go 1.21.3
require ( require (
github.com/go-chi/chi/v5 v5.0.10 github.com/go-chi/chi/v5 v5.0.10
@ -11,6 +11,8 @@ require (
) )
require ( require (
git.t-juice.club/microfilm/auth v0.1.1 // indirect
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect github.com/klauspost/compress v1.17.0 // indirect
github.com/nats-io/nkeys v0.4.5 // indirect github.com/nats-io/nkeys v0.4.5 // indirect
github.com/nats-io/nuid v1.0.1 // indirect github.com/nats-io/nuid v1.0.1 // indirect

4
go.sum
View File

@ -1,8 +1,12 @@
git.t-juice.club/microfilm/auth v0.1.1 h1:usg48CEd94Ha2rkEdCU+mhczJvLwwxVouOl478YdZFE=
git.t-juice.club/microfilm/auth v0.1.1/go.mod h1:sfgaIWxnNgERWyx611596OtEBc3cF4g3FSqKd073Te4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= 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/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= 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/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 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=

View File

@ -5,6 +5,7 @@ import "golang.org/x/crypto/bcrypt"
type User struct { type User struct {
ID string `json:"id"` ID string `json:"id"`
Username string `json:"username"` Username string `json:"username"`
Role string `json:"role"`
HashedPassword []byte `json:"-"` HashedPassword []byte `json:"-"`
} }
@ -35,6 +36,7 @@ type ErrorResponse struct {
type CreateUserRequest struct { type CreateUserRequest struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
Role string `json:"role"`
} }
type CreateUserResponse struct { type CreateUserResponse struct {

25
server/middleware.go Normal file
View File

@ -0,0 +1,25 @@
package server
import (
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
)
func (s *UserServer) MiddlewareLogging(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func(ww middleware.WrapResponseWriter) {
s.Logger.Info("Served request.",
"status", ww.Status(),
"path", r.URL.Path,
"duration", time.Since(t1),
"written", ww.BytesWritten())
}(ww)
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}

View File

@ -8,6 +8,8 @@ import (
"net/http" "net/http"
"os" "os"
"git.t-juice.club/microfilm/auth"
"git.t-juice.club/microfilm/auth/authmw"
"git.t-juice.club/microfilm/users" "git.t-juice.club/microfilm/users"
"git.t-juice.club/microfilm/users/store" "git.t-juice.club/microfilm/users/store"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@ -20,7 +22,7 @@ type UserServer struct {
store store.UserStore store store.UserStore
config *Config config *Config
nats *nats.Conn nats *nats.Conn
logger *slog.Logger Logger *slog.Logger
} }
func NewServer(config *Config) (*UserServer, error) { func NewServer(config *Config) (*UserServer, error) {
@ -28,20 +30,37 @@ func NewServer(config *Config) (*UserServer, error) {
srv := &UserServer{} srv := &UserServer{}
srv.config = config srv.config = config
srv.logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ srv.Logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug, Level: slog.LevelDebug,
})) }))
r.Get("/", InfoHandler) r.Use(srv.MiddlewareLogging)
r.Post("/users", srv.CreateUserHandler)
r.Post("/users/:id/password", srv.SetPasswordHandler) verifyAdmin := authmw.VerifyToken("http://mf-auth:8082", []string{auth.RoleAdmin})
r.Post("/users/:username/verify", srv.VerifyHandler)
r.Get("/info", InfoHandler)
r.With(verifyAdmin).Post("/", srv.CreateUserHandler)
r.Get("/{identifier}", srv.GetUserHandler)
r.Post("/{identifier}/password", srv.SetPasswordHandler)
r.Post("/{identifier}/verify", srv.VerifyHandler)
srv.Addr = config.ListenAddr srv.Addr = config.ListenAddr
srv.Handler = r srv.Handler = r
srv.store = store.NewMemoryStore() srv.store = store.NewMemoryStore()
// Add initial admin-user
u := users.User{
ID: uuid.Must(uuid.NewRandom()).String(),
Username: "admin",
Role: "admin",
}
password := uuid.Must(uuid.NewRandom()).String()
_ = u.SetPassword(password)
_ = srv.store.AddUser(u)
srv.Logger.Warn("Initial admin-user created.", "username", u.Username, "password", password)
conn, err := nats.Connect(config.NATSAddr) conn, err := nats.Connect(config.NATSAddr)
if err != nil { if err != nil {
return nil, err return nil, err
@ -63,8 +82,9 @@ func InfoHandler(w http.ResponseWriter, r *http.Request) {
} }
func WriteError(w http.ResponseWriter, response users.ErrorResponse) { func WriteError(w http.ResponseWriter, response users.ErrorResponse) {
encoder := json.NewEncoder(w)
w.WriteHeader(response.Status) w.WriteHeader(response.Status)
encoder := json.NewEncoder(w)
_ = encoder.Encode(&response) _ = encoder.Encode(&response)
} }
@ -97,7 +117,7 @@ func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) {
} }
if err := s.store.AddUser(u); err != nil { if err := s.store.AddUser(u); err != nil {
s.logger.Warn("Error storing user", "error", err) s.Logger.Warn("Error storing user", "error", err)
WriteError(w, users.ErrorResponse{ WriteError(w, users.ErrorResponse{
Status: http.StatusInternalServerError, Status: http.StatusInternalServerError,
Message: fmt.Sprintf("Error storing user: %s", err), Message: fmt.Sprintf("Error storing user: %s", err),
@ -116,10 +136,10 @@ func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(&buf) encoder := json.NewEncoder(&buf)
_ = encoder.Encode(&msg) _ = encoder.Encode(&msg)
if err := s.nats.Publish(sub, buf.Bytes()); err != nil { if err := s.nats.Publish(sub, buf.Bytes()); err != nil {
s.logger.Warn("Error publishing message", "error", err) s.Logger.Warn("Error publishing message", "error", err)
} }
s.logger.Info("User created.", "username", u.Username, "id", u.ID) s.Logger.Info("User created.", "username", u.Username, "id", u.ID)
response := &users.CreateUserResponse{ response := &users.CreateUserResponse{
Message: "User created.", Message: "User created.",
@ -130,6 +150,29 @@ func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) {
_ = encoder.Encode(&response) _ = encoder.Encode(&response)
} }
func (s *UserServer) GetUserHandler(w http.ResponseWriter, r *http.Request) {
identifier := chi.URLParam(r, "identifier")
u, err := s.store.GetUser(identifier)
if err != nil {
switch err {
case store.ErrNoSuchUser:
WriteError(w, users.ErrorResponse{
Message: fmt.Sprintf("No such user: %s", identifier),
Status: http.StatusNotFound,
})
return
}
WriteError(w, users.ErrorResponse{
Message: fmt.Sprintf("Unable to get user: %s", err),
Status: http.StatusInternalServerError,
})
return
}
encoder := json.NewEncoder(w)
_ = encoder.Encode(&u)
}
func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request) { func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
defer r.Body.Close() defer r.Body.Close()
@ -144,12 +187,13 @@ func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request)
return return
} }
id := chi.URLParam(r, "id") id := chi.URLParam(r, "identifier")
if id == "" { if id == "" {
WriteError(w, users.ErrorResponse{ WriteError(w, users.ErrorResponse{
Status: http.StatusBadRequest, Status: http.StatusBadRequest,
Message: fmt.Sprintf("Invalid user ID: %s", id), Message: fmt.Sprintf("Invalid user ID: %s", id),
}) })
return
} }
u, err := s.store.GetUser(id) u, err := s.store.GetUser(id)
@ -175,14 +219,16 @@ func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request)
Status: http.StatusBadRequest, Status: http.StatusBadRequest,
Message: fmt.Sprintf("Unable to set password: %s", id), Message: fmt.Sprintf("Unable to set password: %s", id),
}) })
return
} }
if err := s.store.UpdateUser(u); err != nil { if err := s.store.UpdateUser(u); err != nil {
s.logger.Warn("Unable to update user.", "id", u.ID, "error", err) s.Logger.Warn("Unable to update user.", "id", u.ID, "error", err)
WriteError(w, users.ErrorResponse{ WriteError(w, users.ErrorResponse{
Status: http.StatusInternalServerError, Status: http.StatusInternalServerError,
Message: fmt.Sprintf("Unable to set password: %s", id), Message: fmt.Sprintf("Unable to set password: %s", id),
}) })
return
} }
sub := fmt.Sprintf("%s.%s", s.config.NATSSubject, "update") sub := fmt.Sprintf("%s.%s", s.config.NATSSubject, "update")
@ -191,9 +237,9 @@ func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request)
_ = encoder.Encode(&users.MsgUserUpdate{Message: "Password updated", ID: u.ID}) _ = encoder.Encode(&users.MsgUserUpdate{Message: "Password updated", ID: u.ID})
if err := s.nats.Publish(sub, buf.Bytes()); err != nil { if err := s.nats.Publish(sub, buf.Bytes()); err != nil {
s.logger.Warn("Error publishing message", "error", err) s.Logger.Warn("Error publishing message", "error", err)
} }
s.logger.Info("User password updated.", "id", u.ID) s.Logger.Info("User password updated.", "id", u.ID)
} }
func (s *UserServer) VerifyHandler(w http.ResponseWriter, r *http.Request) { func (s *UserServer) VerifyHandler(w http.ResponseWriter, r *http.Request) {
@ -210,12 +256,13 @@ func (s *UserServer) VerifyHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
id := chi.URLParam(r, "id") id := chi.URLParam(r, "identifier")
if id == "" { if id == "" {
WriteError(w, users.ErrorResponse{ WriteError(w, users.ErrorResponse{
Status: http.StatusBadRequest, Status: http.StatusBadRequest,
Message: fmt.Sprintf("Invalid user ID: %s", id), Message: fmt.Sprintf("Invalid user ID: %s", id),
}) })
return
} }
u, err := s.store.GetUser(id) u, err := s.store.GetUser(id)
@ -242,5 +289,7 @@ func (s *UserServer) VerifyHandler(w http.ResponseWriter, r *http.Request) {
Status: http.StatusUnauthorized, Status: http.StatusUnauthorized,
Message: "Password verification failed.", Message: "Password verification failed.",
}) })
return
} }
w.WriteHeader(http.StatusOK)
} }

View File

@ -1,3 +1,3 @@
package users package users
const Version = "v0.1.1" const Version = "v0.1.2"