tsk-18: Create service user (#22)

Closes #18

Reviewed-on: phoenix/textsender-auth#22
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-11-20 19:11:36 +00:00
committed by phoenix
parent 8a90448854
commit c340693b24
17 changed files with 531 additions and 26 deletions
+1
View File
@@ -3,3 +3,4 @@ package endpoint
// Endpoint for registering a user
const Register = "/api/v1/register"
const Login = "/api/v1/login"
const CreateServiceUser = "/api/v1/service/register"
+2 -1
View File
@@ -12,11 +12,12 @@ import (
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
)
func TestLogin(t *testing.T) {
mockstore := NewMockUserStore()
mockstore := mock.NewMockUserStore()
handler := NewLoginHandler(mockstore)
testUser := GetTestUser()
+2 -1
View File
@@ -10,10 +10,11 @@ import (
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
)
func TestCreateUserWithMock(t *testing.T) {
mockstore := NewMockUserStore()
mockstore := mock.NewMockUserStore()
handler := NewUserHandler(mockstore)
testUser := GetTestUser()
+82
View File
@@ -0,0 +1,82 @@
package handler
import (
"net/http"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"git.kundeng.us/phoenix/textsender-auth/internal/store"
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
)
type ServiceCreationRequest struct {
Username string `json:"username"`
Passphrase string `json:"passphrase"`
}
type ServiceCreationResponse struct {
Message string `json:"message"`
Data []*user.ServiceUser `json:"data"`
}
type ServiceHandler struct {
ServiceStore store.ServiceStore
}
func NewServiceHandler(serviceStore store.ServiceStore) *ServiceHandler {
return &ServiceHandler{ServiceStore: serviceStore}
}
// Register godoc
// @Summary Register service user
// @Description Create a service user that can send texts (requires JWT)
// @Tags service users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body ServiceCreationRequest true "Data to add user"
// @Success 200 {object} ServiceCreationResponse
// @Failure 400 {object} ServiceCreationResponse
// @Failure 500 {object} ServiceCreationResponse
// @Router /service/register [post]
func (s *ServiceHandler) Register(w http.ResponseWriter, r *http.Request) {
var req ServiceCreationRequest
if err := ExtractFromRequest(r, &req); err != nil {
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
defer r.Body.Close()
var statusCode int
var resp ServiceCreationResponse
ctx := r.Context()
if exists, err := s.ServiceStore.CheckWithUsername(ctx, req.Username); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
if exists {
statusCode = http.StatusBadRequest
resp.Message = "Service user already exists"
} else {
hashing := utility.HashMash{Password: req.Passphrase}
if hashedPassword, err := hashing.HashPassword(); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
serviceUser := user.ServiceUser{Username: req.Username, Passphrase: hashedPassword}
if err := s.ServiceStore.Create(ctx, &serviceUser); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
statusCode = http.StatusCreated
resp.Message = "Successful"
resp.Data = append(resp.Data, &serviceUser)
}
}
}
}
RespondWithJson(w, statusCode, &resp)
}
+33
View File
@@ -0,0 +1,33 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
)
func TestCreateServiceUserWithMock(t *testing.T) {
mockStore := mock.NewMockServiceUserStore()
handler := NewServiceHandler(mockStore)
testService := ServiceCreationRequest{Username: "swoon", Passphrase: "ewrewr329n12y3x2!2"}
jsonValue, err := json.Marshal(testService)
assert.NoError(t, err, "Error marshaling request")
req, _ := http.NewRequest("POST", endpoint.CreateServiceUser, strings.NewReader(string(jsonValue)))
rr := httptest.NewRecorder()
handler.Register(rr, req)
assert.Equal(t, http.StatusCreated, rr.Code)
var response ServiceCreationResponse
err = json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err)
}
+74
View File
@@ -0,0 +1,74 @@
package mock
import (
"context"
"errors"
"sync"
"github.com/google/uuid"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
)
type MockServiceUserStore struct {
ServiceUsers map[uuid.UUID]*user.ServiceUser
ServiceUsersByUsername map[string]*user.ServiceUser
mu sync.RWMutex
Error error // Optional: simulate errors
}
func NewMockServiceUserStore() *MockServiceUserStore {
return &MockServiceUserStore{
ServiceUsers: make(map[uuid.UUID]*user.ServiceUser),
ServiceUsersByUsername: make(map[string]*user.ServiceUser),
}
}
func (m *MockServiceUserStore) Create(ctx context.Context, user *user.ServiceUser) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.Error != nil {
return m.Error
}
if user.Id == uuid.Nil {
user.Id = uuid.New()
}
if _, exists := m.ServiceUsersByUsername[user.Username]; exists {
return errors.New("service User with username already exists")
}
m.ServiceUsers[user.Id] = user
m.ServiceUsersByUsername[user.Username] = user
return nil
}
func (m *MockServiceUserStore) CheckWithUsername(ctx context.Context, username string) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.Error != nil {
return false, m.Error
}
if m.Error != nil {
return false, m.Error
}
var exists bool
for _, serviceUser := range m.ServiceUsers {
if serviceUser.Username == username {
exists = true
break
}
}
if !exists {
return exists, nil
} else {
return exists, nil
}
}
@@ -1,4 +1,4 @@
package handler
package mock
import (
"context"
+50
View File
@@ -0,0 +1,50 @@
package store
import (
"context"
"fmt"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type ServiceStore interface {
CheckWithUsername(ctx context.Context, username string) (bool, error)
Create(ctx context.Context, serviceUser *user.ServiceUser) error
}
type PGServiceStore struct {
db *pgxpool.Pool
}
func NewServiceStore(db *pgxpool.Pool) *PGServiceStore {
return &PGServiceStore{db: db}
}
func (s *PGServiceStore) CheckWithUsername(ctx context.Context, username string) (bool, error) {
var exists bool
query := `SELECT EXISTS(SELECT 1 FROM service_users WHERE Username = $1)`
if err := s.db.QueryRow(ctx, query, username).Scan(&exists); err != nil {
if err == pgx.ErrNoRows {
return exists, nil
} else {
return exists, fmt.Errorf("Error querying row: %v", err)
}
} else {
return exists, nil
}
}
func (s *PGServiceStore) Create(ctx context.Context, serviceUser *user.ServiceUser) error {
query := `
INSERT INTO service_users (username, passphrase)
VALUES ($1, $2)
RETURNING id, created
`
return s.db.QueryRow(ctx, query, serviceUser.Username, serviceUser.Passphrase).Scan(
&serviceUser.Id, &serviceUser.Created,
)
}