2023-10-19 21:15:55 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-10-23 19:25:13 +00:00
|
|
|
"context"
|
2023-10-19 21:15:55 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2023-10-23 19:25:13 +00:00
|
|
|
"time"
|
2023-10-19 21:15:55 +00:00
|
|
|
|
2023-10-22 20:18:38 +00:00
|
|
|
"git.t-juice.club/microfilm/auth"
|
|
|
|
"git.t-juice.club/microfilm/auth/authmw"
|
2023-10-19 21:15:55 +00:00
|
|
|
"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"
|
2023-10-27 05:10:52 +00:00
|
|
|
"github.com/nats-io/nkeys"
|
2023-10-23 19:25:13 +00:00
|
|
|
"go.opentelemetry.io/otel"
|
|
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
|
|
|
"go.opentelemetry.io/otel/propagation"
|
|
|
|
"go.opentelemetry.io/otel/sdk/resource"
|
|
|
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
|
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
|
2023-10-19 21:15:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type UserServer struct {
|
|
|
|
http.Server
|
|
|
|
store store.UserStore
|
|
|
|
config *Config
|
|
|
|
nats *nats.Conn
|
2023-10-22 19:57:54 +00:00
|
|
|
Logger *slog.Logger
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServer(config *Config) (*UserServer, error) {
|
|
|
|
r := chi.NewRouter()
|
|
|
|
srv := &UserServer{}
|
2023-10-23 19:25:13 +00:00
|
|
|
|
|
|
|
tp, err := tracerProvider("jaeger:4318")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
otel.SetTracerProvider(tp)
|
|
|
|
|
2023-10-19 21:15:55 +00:00
|
|
|
srv.config = config
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
srv.Logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
|
2023-10-19 21:15:55 +00:00
|
|
|
Level: slog.LevelDebug,
|
|
|
|
}))
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
r.Use(srv.MiddlewareLogging)
|
2023-10-23 19:25:13 +00:00
|
|
|
r.Use(srv.MiddlewareTracing)
|
2023-10-22 19:57:54 +00:00
|
|
|
|
2023-10-22 20:18:38 +00:00
|
|
|
verifyAdmin := authmw.VerifyToken("http://mf-auth:8082", []string{auth.RoleAdmin})
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
r.Get("/info", InfoHandler)
|
2023-10-22 20:18:38 +00:00
|
|
|
r.With(verifyAdmin).Post("/", srv.CreateUserHandler)
|
2023-10-22 20:56:07 +00:00
|
|
|
r.Get("/{identifier}", srv.GetUserHandler)
|
2023-10-22 19:57:54 +00:00
|
|
|
r.Post("/{identifier}/password", srv.SetPasswordHandler)
|
|
|
|
r.Post("/{identifier}/verify", srv.VerifyHandler)
|
2023-10-19 21:15:55 +00:00
|
|
|
|
|
|
|
srv.Addr = config.ListenAddr
|
|
|
|
|
|
|
|
srv.Handler = r
|
|
|
|
srv.store = store.NewMemoryStore()
|
|
|
|
|
2023-10-22 20:02:36 +00:00
|
|
|
// Add initial admin-user
|
|
|
|
u := users.User{
|
|
|
|
ID: uuid.Must(uuid.NewRandom()).String(),
|
|
|
|
Username: "admin",
|
2023-10-22 20:56:07 +00:00
|
|
|
Role: "admin",
|
2023-10-22 20:02:36 +00:00
|
|
|
}
|
|
|
|
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)
|
|
|
|
|
2023-10-27 05:10:52 +00:00
|
|
|
if config.NATS.Enabled {
|
|
|
|
var opts []nats.Option
|
|
|
|
if config.NATS.NKeySeed != "" {
|
|
|
|
keys, err := nkeys.FromSeed([]byte(config.NATS.NKeySeed))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pubkey, err := keys.PublicKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
srv.Logger.Debug("NATS enabled with NKeys", "pubkey", pubkey)
|
|
|
|
creds := nats.Nkey(pubkey, keys.Sign)
|
|
|
|
opts = append(opts, creds)
|
|
|
|
}
|
|
|
|
|
|
|
|
conn, err := nats.Connect(config.NATS.Addr, opts...)
|
2023-10-19 21:15:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
srv.nats = conn
|
2023-10-27 05:10:52 +00:00
|
|
|
}
|
2023-10-19 21:15:55 +00:00
|
|
|
|
|
|
|
return srv, nil
|
|
|
|
}
|
|
|
|
|
2023-10-23 19:25:13 +00:00
|
|
|
func tracerProvider(url string) (*sdktrace.TracerProvider, error) {
|
|
|
|
exp, err := otlptracehttp.New(context.Background(), otlptracehttp.WithEndpoint(url), otlptracehttp.WithInsecure())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
res := resource.NewWithAttributes(semconv.SchemaURL,
|
|
|
|
semconv.ServiceName("mf-users"),
|
|
|
|
semconv.ServiceVersion(users.Version),
|
|
|
|
)
|
|
|
|
tp := sdktrace.NewTracerProvider(
|
|
|
|
sdktrace.WithBatcher(exp, sdktrace.WithBatchTimeout(time.Second)),
|
|
|
|
sdktrace.WithResource(res),
|
|
|
|
)
|
|
|
|
otel.SetTracerProvider(tp)
|
|
|
|
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
|
|
|
|
|
|
|
|
return tp, nil
|
|
|
|
}
|
|
|
|
|
2023-10-19 21:15:55 +00:00
|
|
|
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) {
|
|
|
|
w.WriteHeader(response.Status)
|
2023-10-22 19:57:54 +00:00
|
|
|
|
|
|
|
encoder := json.NewEncoder(w)
|
2023-10-19 21:15:55 +00:00
|
|
|
_ = 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 {
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Warn("Error storing user", "error", err)
|
2023-10-19 21:15:55 +00:00
|
|
|
WriteError(w, users.ErrorResponse{
|
|
|
|
Status: http.StatusInternalServerError,
|
|
|
|
Message: fmt.Sprintf("Error storing user: %s", err),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Message
|
2023-10-27 05:10:52 +00:00
|
|
|
sub := fmt.Sprintf("%s.%s", s.config.NATS.Subject, "create")
|
2023-10-19 21:15:55 +00:00
|
|
|
|
|
|
|
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 {
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Warn("Error publishing message", "error", err)
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Info("User created.", "username", u.Username, "id", u.ID)
|
2023-10-19 21:15:55 +00:00
|
|
|
|
|
|
|
response := &users.CreateUserResponse{
|
|
|
|
Message: "User created.",
|
|
|
|
User: u,
|
|
|
|
}
|
|
|
|
|
|
|
|
encoder = json.NewEncoder(w)
|
|
|
|
_ = encoder.Encode(&response)
|
|
|
|
}
|
|
|
|
|
2023-10-22 20:56:07 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-10-19 21:15:55 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
id := chi.URLParam(r, "identifier")
|
2023-10-19 21:15:55 +00:00
|
|
|
if id == "" {
|
|
|
|
WriteError(w, users.ErrorResponse{
|
|
|
|
Status: http.StatusBadRequest,
|
|
|
|
Message: fmt.Sprintf("Invalid user ID: %s", id),
|
|
|
|
})
|
2023-10-22 19:57:54 +00:00
|
|
|
return
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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),
|
|
|
|
})
|
2023-10-22 19:57:54 +00:00
|
|
|
return
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.store.UpdateUser(u); err != nil {
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Warn("Unable to update user.", "id", u.ID, "error", err)
|
2023-10-19 21:15:55 +00:00
|
|
|
WriteError(w, users.ErrorResponse{
|
|
|
|
Status: http.StatusInternalServerError,
|
|
|
|
Message: fmt.Sprintf("Unable to set password: %s", id),
|
|
|
|
})
|
2023-10-22 19:57:54 +00:00
|
|
|
return
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
2023-10-27 05:10:52 +00:00
|
|
|
sub := fmt.Sprintf("%s.%s", s.config.NATS.Subject, "update")
|
2023-10-19 21:15:55 +00:00
|
|
|
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 {
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Warn("Error publishing message", "error", err)
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
2023-10-22 19:57:54 +00:00
|
|
|
s.Logger.Info("User password updated.", "id", u.ID)
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-10-22 19:57:54 +00:00
|
|
|
id := chi.URLParam(r, "identifier")
|
2023-10-19 21:15:55 +00:00
|
|
|
if id == "" {
|
|
|
|
WriteError(w, users.ErrorResponse{
|
|
|
|
Status: http.StatusBadRequest,
|
|
|
|
Message: fmt.Sprintf("Invalid user ID: %s", id),
|
|
|
|
})
|
2023-10-22 19:57:54 +00:00
|
|
|
return
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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.",
|
|
|
|
})
|
2023-10-22 19:57:54 +00:00
|
|
|
return
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|
2023-10-22 19:57:54 +00:00
|
|
|
w.WriteHeader(http.StatusOK)
|
2023-10-19 21:15:55 +00:00
|
|
|
}
|