Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c340693b24 | ||
|
|
8a90448854 | ||
|
|
6f608b757c | ||
|
|
ef39949e77 | ||
|
|
b627c832fa | ||
|
|
60241a2b16
|
||
|
|
25c283434d
|
||
|
|
12f8b18524
|
||
|
|
b5e5c3d79a
|
||
|
|
efe43045d5
|
||
|
|
2da679afc2
|
||
|
|
9fdba18256 | ||
|
|
21d8d0f005
|
||
|
|
a19f2f353c
|
||
|
|
816a679aca
|
||
|
|
b6884f8bf3
|
||
|
|
284752c2f9
|
||
|
|
b3cd32124d
|
||
|
|
855be9289a
|
||
|
|
eb37632b8e
|
||
|
|
a635b91994
|
||
|
|
2a244c986f
|
||
|
|
a44f2c1402
|
||
|
|
821acb40b8
|
||
|
|
d004069c55
|
||
|
|
19dac619ec
|
||
|
|
cc9b53db9a
|
||
|
|
27fcfbae39
|
||
|
|
df193acdff
|
||
|
|
a0d6d8f174
|
||
|
|
878af97859
|
||
|
|
daeb210dda
|
||
|
|
d803e7d3c3
|
||
|
|
1b0ba48659
|
||
|
|
8fcba02196
|
||
|
|
ed2a440872
|
||
|
|
d261297a1c
|
||
|
|
eded5ecf5a | ||
|
|
3e28db7552 | ||
|
|
976a017b4f |
@@ -0,0 +1,9 @@
|
|||||||
|
vendor/
|
||||||
|
|
||||||
|
# Ignore git directory
|
||||||
|
.git/
|
||||||
|
|
||||||
|
.gitea/
|
||||||
|
|
||||||
|
# Ignore environment files (configure via docker-compose instead)
|
||||||
|
.env*
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
SECRET_KEY=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||||
|
DB_NAME=textsender_auth_db
|
||||||
|
DB_USER=textsender_auth
|
||||||
|
DB_PASSWORD=password
|
||||||
|
DB_HOST=auth_db
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_SSLMODE=disable
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
SECRET_KEY=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||||
DB_NAME=textsender_auth_db
|
DB_NAME=textsender_auth_db
|
||||||
DB_USER=textsender_auth
|
DB_USER=textsender_auth
|
||||||
DB_PASSWORD=yEDjWZCH2vdctjn!
|
DB_PASSWORD=yEDjWZCH2vdctjn!
|
||||||
|
|||||||
+106
-24
@@ -11,36 +11,118 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04 # You can change this to macos-latest or windows-latest if needed
|
runs-on: ubuntu-24.04 # You can change this to macos-latest or windows-latest if needed
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v3
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: '1.25.1' # You can specify a specific version or 'stable'
|
go-version: '1.25.3' # You can specify a specific version or 'stable'
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: |
|
run: |
|
||||||
go build -v -ldflags "\
|
echo "Initializing config"
|
||||||
-X main.version=${{ github.ref_name }} \
|
mkdir -p ~/.ssh
|
||||||
-X main.commit=${{ github.sha }} \
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
-X main.date=$(date +%Y-%m-%dT%H:%M:%S%z)" \
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
-o textsender-auth cmd/api/main.go
|
ssh-keyscan ${{ vars.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
eval $(ssh-agent -s)
|
||||||
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
|
|
||||||
- name: Test
|
go env -w GOPRIVATE='${{ secrets.GIT_HOST_ROOT }}'
|
||||||
run: go test -v ./...
|
|
||||||
|
|
||||||
# - name: Run gofmt (optional)
|
echo "Creating local .gitconfig"
|
||||||
# Uncomment to check code formatting with gofmt
|
touch ~/.gitconfig
|
||||||
# run: |
|
cat > ~/.gitconfig << "EOF"
|
||||||
# if [ -n "$(gofmt -l.)" ]; then
|
[url "ssh://git@${{ secrets.GIT_HOST_ROOT }}"]
|
||||||
# echo "Go code is not formatted. Please run 'gofmt -w.' to fix it."
|
insteadOf = https://${{ secrets.GIT_HOST_ROOT }}
|
||||||
# exit 1
|
EOF
|
||||||
# fi
|
|
||||||
|
|
||||||
# - name: Run golint (optional)
|
echo "Building binary"
|
||||||
# Uncomment to check code style with golint
|
make build
|
||||||
# run: |
|
|
||||||
# if [ -n "$(golint./...)" ]; then
|
echo "Binary built"
|
||||||
# echo "Go code has style issues. Please run 'golint./...' to see them."
|
file textsender-auth
|
||||||
# exit 1
|
|
||||||
# fi
|
test:
|
||||||
|
name: Test
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:18.0
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: ${{ secrets.DB_TEST_USER }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||||
|
POSTGRES_DB: ${{ secrets.DB_TEST_NAME }}
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: '1.25.3'
|
||||||
|
|
||||||
|
- name: Install PostgreSQL client
|
||||||
|
run: sudo apt update && sudo apt-get install -y postgresql-client
|
||||||
|
|
||||||
|
- name: Wait for PostgreSQL to be ready
|
||||||
|
run: |
|
||||||
|
for i in {1..30}; do
|
||||||
|
if pg_isready -h postgres -p 5432; then
|
||||||
|
echo "PostgreSQL is ready"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
echo "Waiting for PostgreSQL... Attempt $i"
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "PostgreSQL did not start in time"
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
env:
|
||||||
|
DB_NAME: ${{ secrets.DB_TEST_NAME }}
|
||||||
|
DB_USER: ${{ secrets.DB_TEST_USER }}
|
||||||
|
DB_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||||
|
DB_HOST: postgres
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_SSLMODE: disable
|
||||||
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
|
run: |
|
||||||
|
echo "Parent directory"
|
||||||
|
echo `pwd`
|
||||||
|
|
||||||
|
echo "SECRET_KEY=$SECRET_KEY" >> .env
|
||||||
|
echo "DB_NAME=$DB_NAME" > .env
|
||||||
|
echo "DB_USER=$DB_USER" >> .env
|
||||||
|
echo "DB_PASSWORD=$DB_PASSWORD" >> .env
|
||||||
|
echo "DB_HOST=$DB_HOST" >> .env
|
||||||
|
echo "DB_PORT=$DB_PORT" >> .env
|
||||||
|
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
|
||||||
|
|
||||||
|
echo "Initializing config"
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
|
ssh-keyscan ${{ vars.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
eval $(ssh-agent -s)
|
||||||
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
|
|
||||||
|
go env -w GOPRIVATE='${{ secrets.GIT_HOST_ROOT }}'
|
||||||
|
|
||||||
|
echo "Creating local .gitconfig"
|
||||||
|
touch ~/.gitconfig
|
||||||
|
cat > ~/.gitconfig << "EOF"
|
||||||
|
[url "ssh://git@${{ secrets.GIT_HOST_ROOT }}"]
|
||||||
|
insteadOf = https://${{ secrets.GIT_HOST_ROOT }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
go test -v ./...
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
/textsender-auth
|
/textsender-auth
|
||||||
|
|
||||||
.env
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.docker
|
||||||
|
|
||||||
/vendor
|
/vendor
|
||||||
|
|||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
# Multi-stage Dockerfile for Go application
|
||||||
|
FROM golang:1.25.3 AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
openssh-client git
|
||||||
|
|
||||||
|
RUN mkdir -p -m 0700 ~/.ssh && \
|
||||||
|
ssh-keyscan git.kundeng.us >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
# Configure Git to use SSH for GitHub
|
||||||
|
RUN git config --global url."ssh://git@git.kundeng.us".insteadOf "https://git.kundeng.us"
|
||||||
|
|
||||||
|
# Set up the Go environment for private modules
|
||||||
|
ENV GOPRIVATE=git.kundeng.us
|
||||||
|
|
||||||
|
|
||||||
|
# Copy go mod and sum files
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
|
||||||
|
RUN --mount=type=ssh mkdir src && \
|
||||||
|
go mod download
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY ./cmd ./cmd
|
||||||
|
COPY ./internal ./internal
|
||||||
|
COPY ./Makefile .
|
||||||
|
COPY ./.env .
|
||||||
|
COPY ./migrations ./migrations
|
||||||
|
COPY ./docs ./docs
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux make build
|
||||||
|
|
||||||
|
# Runtime stage
|
||||||
|
FROM alpine:latest AS production
|
||||||
|
|
||||||
|
RUN apk --no-cache add ca-certificates
|
||||||
|
|
||||||
|
WORKDIR /root/
|
||||||
|
|
||||||
|
# Copy the pre-built binary file from the previous stage
|
||||||
|
COPY --from=builder /app/textsender-auth .
|
||||||
|
COPY --from=builder /app/.env ./
|
||||||
|
COPY --from=builder /app/migrations ./migrations
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 9080
|
||||||
|
|
||||||
|
# Command to run the executable
|
||||||
|
CMD ["./textsender-auth"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
VERSION ?= $(shell git describe --tags 2>/dev/null || echo "dev")
|
||||||
|
COMMIT ?= $(shell git rev-parse --short HEAD)
|
||||||
|
BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
GO_VERSION ?= $(shell go version | awk '{print $$3}')
|
||||||
|
|
||||||
|
.PHONY: build
|
||||||
|
build:
|
||||||
|
go build -ldflags="\
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.Version=$(VERSION)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.BuildTime=$(BUILD_TIME)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.Commit=$(COMMIT)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.GoVersion=$(GO_VERSION)'" \
|
||||||
|
-o textsender-auth cmd/api/main.go
|
||||||
|
|
||||||
|
.PHONY: install
|
||||||
|
install:
|
||||||
|
go install -ldflags="\
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.Version=$(VERSION)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.BuildTime=$(BUILD_TIME)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.Commit=$(COMMIT)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-auth/internal/version.GoVersion=$(GO_VERSION)'"
|
||||||
@@ -1,2 +1,31 @@
|
|||||||
# textsender-auth
|
# textsender-auth
|
||||||
A service that handles the authorization aspect of the textsender project.
|
A service that handles the authorization aspect of the textsender project.
|
||||||
|
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
Assumes that the postgresql database has already been created with privileges to
|
||||||
|
create and drop databases. Copy the `.env.sample` file to `.env`. Within the `.env`
|
||||||
|
file, update the database keys. The `SECRET_KEY` is used for token generation.
|
||||||
|
|
||||||
|
|
||||||
|
### Building api
|
||||||
|
```
|
||||||
|
make build
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Resetting the database
|
||||||
|
```
|
||||||
|
./textsender-auth -reset-db
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Generate API documentation
|
||||||
|
```
|
||||||
|
go install github.com/swaggo/swag/cmd/swag@latest
|
||||||
|
go get -u github.com/swaggo/http-swagger/v2
|
||||||
|
|
||||||
|
swag init --generalInfo main.go --dir ./cmd/api,./internal/handler --output docs/ --parseDependency --parseInternal
|
||||||
|
```
|
||||||
|
|
||||||
|
The API documentation can be viewed from `http://localhost:9080/swagger/index.html`.
|
||||||
|
|||||||
+46
-7
@@ -12,21 +12,37 @@ import (
|
|||||||
|
|
||||||
"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/swaggo/http-swagger/v2"
|
||||||
|
|
||||||
|
_ "git.kundeng.us/phoenix/textsender-auth/docs"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
database "git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
mdleware "git.kundeng.us/phoenix/textsender-auth/internal/middleware"
|
mdleware "git.kundeng.us/phoenix/textsender-auth/internal/middleware"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// @title textsender-auth
|
||||||
|
// @version 1.0
|
||||||
|
// @description Auth API to send text messages
|
||||||
|
|
||||||
|
// @host localhost:9080
|
||||||
|
// @BasePath /api/v1
|
||||||
|
|
||||||
|
// @securityDefinitions.apikey BearerAuth
|
||||||
|
// @in header
|
||||||
|
// @name Authorization
|
||||||
|
// @description JWT Bearer Token
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("textsender-auth")
|
|
||||||
|
|
||||||
cfg := config.Load()
|
cfg := config.Load()
|
||||||
|
if cfg == nil {
|
||||||
|
fmt.Println("Error initializing config")
|
||||||
|
os.Exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
db, err := db.NewDatabase(cfg.GetDBConnString())
|
db, err := database.NewDatabase(cfg.GetDBConnString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to connect to database: %v", err)
|
log.Fatalf("Failed to connect to database: %v", err)
|
||||||
}
|
}
|
||||||
@@ -35,17 +51,34 @@ func main() {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
if cfg.ResetDB {
|
if cfg.ResetDB {
|
||||||
log.Println("Resetting database")
|
|
||||||
if err := db.ResetDatabase(ctx); err != nil {
|
if err := db.ResetDatabase(ctx); err != nil {
|
||||||
log.Fatalf("Failed to reset database: %v", err)
|
log.Fatalf("Failed to reset database: %v", err)
|
||||||
|
} else {
|
||||||
|
log.Println("Resetting database")
|
||||||
|
log.Println("Database reset completed. Exiting.")
|
||||||
}
|
}
|
||||||
log.Println("Database reset completed. Exiting.")
|
|
||||||
return
|
return
|
||||||
|
} else {
|
||||||
|
if exists, err := database.TableExists(ctx, db.Pool, "users"); err == nil {
|
||||||
|
if !exists {
|
||||||
|
if err = db.ResetDatabase(ctx); err != nil {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Database reset")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Services
|
// Services
|
||||||
userStore := model.NewUserStore(db.Pool)
|
userStore := model.NewUserStore(db.Pool)
|
||||||
|
serviceStore := store.NewServiceStore(db.Pool)
|
||||||
|
|
||||||
userHandler := handler.NewUserHandler(userStore)
|
userHandler := handler.NewUserHandler(userStore)
|
||||||
|
loginHandler := handler.NewLoginHandler(userStore)
|
||||||
|
serviceHandler := handler.NewServiceHandler(serviceStore)
|
||||||
|
|
||||||
router := chi.NewRouter()
|
router := chi.NewRouter()
|
||||||
|
|
||||||
@@ -54,7 +87,13 @@ func main() {
|
|||||||
router.Use(middleware.Timeout(60 * time.Second))
|
router.Use(middleware.Timeout(60 * time.Second))
|
||||||
router.Use(mdleware.JSONContentType)
|
router.Use(mdleware.JSONContentType)
|
||||||
|
|
||||||
router.Post(endpoint.Register, userHandler.Register)
|
router.Method("Post", endpoint.Register, http.HandlerFunc(userHandler.Register))
|
||||||
|
router.Method("Post", endpoint.Login, http.HandlerFunc(loginHandler.Login))
|
||||||
|
router.Method("Post", endpoint.CreateServiceUser, http.HandlerFunc(serviceHandler.Register))
|
||||||
|
|
||||||
|
router.Method("GET", "/swagger/*", httpSwagger.Handler(
|
||||||
|
httpSwagger.URL(fmt.Sprintf("http://localhost:%s/swagger/doc.json", config.Port)),
|
||||||
|
))
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
var testRouter *mux.Router
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
cfg := load()
|
||||||
|
|
||||||
|
database, err := db.NewDatabase(cfg.GetDBConnString())
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
panic("Failed to initialize database")
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
err = database.ResetDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
panic("Failed to initialize database")
|
||||||
|
}
|
||||||
|
|
||||||
|
userStore := model.NewUserStore(database.Pool)
|
||||||
|
serviceStore := store.NewServiceStore(database.Pool)
|
||||||
|
userHandler := handler.NewUserHandler(userStore)
|
||||||
|
loginHandler := handler.NewLoginHandler(userStore)
|
||||||
|
serviceHandler := handler.NewServiceHandler(serviceStore)
|
||||||
|
|
||||||
|
testRouter = mux.NewRouter()
|
||||||
|
testRouter.HandleFunc(endpoint.Register, userHandler.Register).Methods("POST")
|
||||||
|
testRouter.HandleFunc(endpoint.Login, loginHandler.Login).Methods("POST")
|
||||||
|
testRouter.HandleFunc(endpoint.CreateServiceUser, serviceHandler.Register).Methods("POST")
|
||||||
|
|
||||||
|
code := m.Run()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func load() *config.Config {
|
||||||
|
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||||
|
port := flag.String("port", config.Port, "Server port")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
envPath := path.Join(cwd, ".env")
|
||||||
|
|
||||||
|
err := godotenv.Load(envPath)
|
||||||
|
if err != nil {
|
||||||
|
envPath = path.Join(cwd, "../..", ".env")
|
||||||
|
if err := godotenv.Load(envPath); err != nil {
|
||||||
|
panic("Error loading .env file: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unpackedConnString := config.UnpackDBConnString()
|
||||||
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
|
||||||
|
return &config.Config{
|
||||||
|
DBConnString: dbConnString,
|
||||||
|
ServerPort: *port,
|
||||||
|
ResetDB: *resetDb,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetTestDB(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
_, err := db.Pool.Exec(context.Background(), "DELETE FROM users")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to reset test database: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
version: '3.8' # Use a recent version
|
||||||
|
|
||||||
|
services:
|
||||||
|
auth_api:
|
||||||
|
build: # Tells docker-compose to build the Dockerfile in the current directory
|
||||||
|
context: .
|
||||||
|
ssh: ["default"] # Uses host's SSH agent
|
||||||
|
container_name: textsender_auth # Optional: Give the container a specific name
|
||||||
|
ports:
|
||||||
|
# Map host port 8000 to container port 3000 (adjust as needed)
|
||||||
|
- "9080:9080"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
auth_db:
|
||||||
|
condition: service_healthy # Wait for the DB to be healthy before starting the app
|
||||||
|
restart: unless-stopped # Optional: Restart policy
|
||||||
|
|
||||||
|
# PostgreSQL Database Service
|
||||||
|
auth_db:
|
||||||
|
image: postgres:18.0-alpine # Use an official Postgres image (Alpine variant is smaller)
|
||||||
|
container_name: textsender_auth_db # Optional: Give the container a specific name
|
||||||
|
environment:
|
||||||
|
# These MUST match the user, password, and database name in the DATABASE_URL above
|
||||||
|
POSTGRES_USER: ${POSTGRES_AUTH_USER:-textsender_auth}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_AUTH_PASSWORD:-password}
|
||||||
|
POSTGRES_DB: ${POSTGRES_AUTH_DB:-textsender_auth_db}
|
||||||
|
volumes:
|
||||||
|
# Persist database data using a named volume
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports: []
|
||||||
|
healthcheck:
|
||||||
|
# Checks if Postgres is ready to accept connections
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s
|
||||||
|
restart: always # Optional: Restart policy
|
||||||
|
|
||||||
|
# Define the named volume for data persistence
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
driver: local # Use the default local driver
|
||||||
+323
@@ -0,0 +1,323 @@
|
|||||||
|
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||||
|
package docs
|
||||||
|
|
||||||
|
import "github.com/swaggo/swag"
|
||||||
|
|
||||||
|
const docTemplate = `{
|
||||||
|
"schemes": {{ marshal .Schemes }},
|
||||||
|
"swagger": "2.0",
|
||||||
|
"info": {
|
||||||
|
"description": "{{escape .Description}}",
|
||||||
|
"title": "{{.Title}}",
|
||||||
|
"contact": {},
|
||||||
|
"version": "{{.Version}}"
|
||||||
|
},
|
||||||
|
"host": "{{.Host}}",
|
||||||
|
"basePath": "{{.BasePath}}",
|
||||||
|
"paths": {
|
||||||
|
"/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginAccount"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Register user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterUser"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a service user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Register service user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"definitions": {
|
||||||
|
"handler.LoginAccount": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponseItem"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponseItem": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/user.ServiceUser"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"token.Login": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"expires_in": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"token_type": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user.ServiceUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"date_created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"securityDefinitions": {
|
||||||
|
"BearerAuth": {
|
||||||
|
"description": "JWT Bearer Token",
|
||||||
|
"type": "apiKey",
|
||||||
|
"name": "Authorization",
|
||||||
|
"in": "header"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`
|
||||||
|
|
||||||
|
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||||
|
var SwaggerInfo = &swag.Spec{
|
||||||
|
Version: "1.0",
|
||||||
|
Host: "localhost:9080",
|
||||||
|
BasePath: "/api/v1",
|
||||||
|
Schemes: []string{},
|
||||||
|
Title: "textsender-auth",
|
||||||
|
Description: "Auth API to send text messages",
|
||||||
|
InfoInstanceName: "swagger",
|
||||||
|
SwaggerTemplate: docTemplate,
|
||||||
|
LeftDelim: "{{",
|
||||||
|
RightDelim: "}}",
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
{
|
||||||
|
"swagger": "2.0",
|
||||||
|
"info": {
|
||||||
|
"description": "Auth API to send text messages",
|
||||||
|
"title": "textsender-auth",
|
||||||
|
"contact": {},
|
||||||
|
"version": "1.0"
|
||||||
|
},
|
||||||
|
"host": "localhost:9080",
|
||||||
|
"basePath": "/api/v1",
|
||||||
|
"paths": {
|
||||||
|
"/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginAccount"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Register user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterUser"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a service user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Register service user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"definitions": {
|
||||||
|
"handler.LoginAccount": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponseItem"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponseItem": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/user.ServiceUser"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"token.Login": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"expires_in": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"token_type": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user.ServiceUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"date_created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"securityDefinitions": {
|
||||||
|
"BearerAuth": {
|
||||||
|
"description": "JWT Bearer Token",
|
||||||
|
"type": "apiKey",
|
||||||
|
"name": "Authorization",
|
||||||
|
"in": "header"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
basePath: /api/v1
|
||||||
|
definitions:
|
||||||
|
handler.LoginAccount:
|
||||||
|
properties:
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.LoginResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/token.Login'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponseItem'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterResponseItem:
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
phone_number:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterUser:
|
||||||
|
properties:
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
phone_number:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceCreationRequest:
|
||||||
|
properties:
|
||||||
|
passphrase:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceCreationResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/user.ServiceUser'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
token.Login:
|
||||||
|
properties:
|
||||||
|
access_token:
|
||||||
|
type: string
|
||||||
|
expires_in:
|
||||||
|
type: integer
|
||||||
|
token_type:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
user.ServiceUser:
|
||||||
|
properties:
|
||||||
|
date_created:
|
||||||
|
type: string
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
passphrase:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
host: localhost:9080
|
||||||
|
info:
|
||||||
|
contact: {}
|
||||||
|
description: Auth API to send text messages
|
||||||
|
title: textsender-auth
|
||||||
|
version: "1.0"
|
||||||
|
paths:
|
||||||
|
/login:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Login and be given an access token (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to obtain a token
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginAccount'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Login
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
/register:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Create a user that can send texts (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to add user
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterUser'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Register user
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
/service/register:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Create a service user that can send texts (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to add user
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Register service user
|
||||||
|
tags:
|
||||||
|
- service users
|
||||||
|
securityDefinitions:
|
||||||
|
BearerAuth:
|
||||||
|
description: JWT Bearer Token
|
||||||
|
in: header
|
||||||
|
name: Authorization
|
||||||
|
type: apiKey
|
||||||
|
swagger: "2.0"
|
||||||
@@ -1,19 +1,40 @@
|
|||||||
module git.kundeng.us/phoenix/textsender-auth
|
module git.kundeng.us/phoenix/textsender-auth
|
||||||
|
|
||||||
go 1.25.1
|
go 1.25.3
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.8-main-3ab81c2b6d-556
|
||||||
github.com/go-chi/chi/v5 v5.2.3
|
github.com/go-chi/chi/v5 v5.2.3
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/gorilla/mux v1.8.1
|
||||||
github.com/jackc/pgx/v5 v5.7.5
|
github.com/jackc/pgx/v5 v5.7.5
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
|
github.com/stretchr/testify v1.11.1
|
||||||
|
github.com/swaggo/http-swagger/v2 v2.0.2
|
||||||
|
github.com/swaggo/swag v1.16.6
|
||||||
golang.org/x/crypto v0.42.0
|
golang.org/x/crypto v0.42.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||||
|
github.com/go-openapi/jsonreference v0.20.0 // indirect
|
||||||
|
github.com/go-openapi/spec v0.20.6 // indirect
|
||||||
|
github.com/go-openapi/swag v0.19.15 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/josharian/intern v1.0.0 // indirect
|
||||||
|
github.com/mailru/easyjson v0.7.6 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
|
github.com/swaggo/files/v2 v2.0.0 // indirect
|
||||||
|
golang.org/x/mod v0.27.0 // indirect
|
||||||
golang.org/x/sync v0.17.0 // indirect
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
golang.org/x/text v0.29.0 // indirect
|
golang.org/x/text v0.29.0 // indirect
|
||||||
|
golang.org/x/tools v0.36.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,10 +1,31 @@
|
|||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.8-main-3ab81c2b6d-556 h1:iVE8Dg3aYugoZseneN9tQtdV2cymukspShF7dfExSVw=
|
||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.8-main-3ab81c2b6d-556/go.mod h1:lx5MCnOgGgsdpwzrfi9uph5xmkeb6H8AuexUNGss2no=
|
||||||
|
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||||
|
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
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.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||||
|
github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=
|
||||||
|
github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo=
|
||||||
|
github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ=
|
||||||
|
github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA=
|
||||||
|
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
|
||||||
|
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
|
||||||
|
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
@@ -15,20 +36,55 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
|||||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
|
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||||
|
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||||
|
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||||
|
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
|
||||||
|
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||||
|
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw=
|
||||||
|
github.com/swaggo/files/v2 v2.0.0/go.mod h1:24kk2Y9NYEJ5lHuCra6iVwkMjIekMCaFq/0JQj66kyM=
|
||||||
|
github.com/swaggo/http-swagger/v2 v2.0.2 h1:FKCdLsl+sFCx60KFsyM0rDarwiUSZ8DqbfSyIKC9OBg=
|
||||||
|
github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeAHmgIyooa4xm3AQ=
|
||||||
|
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||||
|
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||||
|
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
|
||||||
|
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
|
||||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
|
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||||
|
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/version"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@@ -26,22 +28,34 @@ type ConnectionInfo struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const Port = "9080"
|
const Port = "9080"
|
||||||
|
const App_Name = "textsender_auth"
|
||||||
|
|
||||||
func (ci ConnectionInfo) Parse() string {
|
func (ci ConnectionInfo) Parse() string {
|
||||||
return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", ci.Username, ci.Password, ci.Host, ci.Port, ci.Database, ci.SslMode)
|
return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", ci.Username, ci.Password, ci.Host, ci.Port, ci.Database, ci.SslMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func PrintName() {
|
||||||
|
fmt.Println(App_Name)
|
||||||
|
fmt.Println(version.String())
|
||||||
|
}
|
||||||
|
|
||||||
func Load() *Config {
|
func Load() *Config {
|
||||||
|
versionFlag := flag.Bool("version", false, "Print version information")
|
||||||
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||||
port := flag.String("port", Port, "Server port")
|
port := flag.String("port", Port, "Server port")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
|
if *versionFlag {
|
||||||
|
fmt.Println(version.String())
|
||||||
|
os.Exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
err := godotenv.Load()
|
err := godotenv.Load()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error loading .env file")
|
log.Fatal("Error loading .env file")
|
||||||
}
|
}
|
||||||
|
|
||||||
unpackedConnString := unpackDBConnString()
|
unpackedConnString := UnpackDBConnString()
|
||||||
dbConnString := unpackedConnString.Parse()
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
|
||||||
return &Config{
|
return &Config{
|
||||||
@@ -51,7 +65,11 @@ func Load() *Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func unpackDBConnString() (connInfo ConnectionInfo) {
|
func GetSecretKey() string {
|
||||||
|
return os.Getenv("SECRET_KEY")
|
||||||
|
}
|
||||||
|
|
||||||
|
func UnpackDBConnString() (connInfo ConnectionInfo) {
|
||||||
username := os.Getenv("DB_USER")
|
username := os.Getenv("DB_USER")
|
||||||
password := os.Getenv("DB_PASSWORD")
|
password := os.Getenv("DB_PASSWORD")
|
||||||
host := os.Getenv("DB_HOST")
|
host := os.Getenv("DB_HOST")
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -44,7 +45,6 @@ func NewDatabase(connString string) (*Database, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Test the connection with a short timeout
|
// Test the connection with a short timeout
|
||||||
|
|
||||||
if err := pool.Ping(ctx); err != nil {
|
if err := pool.Ping(ctx); err != nil {
|
||||||
pool.Close()
|
pool.Close()
|
||||||
return nil, fmt.Errorf("unable to ping database: %v", err)
|
return nil, fmt.Errorf("unable to ping database: %v", err)
|
||||||
@@ -54,6 +54,25 @@ func NewDatabase(connString string) (*Database, error) {
|
|||||||
return &Database{Pool: pool}, nil
|
return &Database{Pool: pool}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TableExists(ctx context.Context, conn *pgxpool.Pool, tableName string) (bool, error) {
|
||||||
|
var exists bool
|
||||||
|
|
||||||
|
query := `
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name = $1
|
||||||
|
);
|
||||||
|
`
|
||||||
|
|
||||||
|
err := conn.QueryRow(ctx, query, tableName).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("error checking if table exists: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (db *Database) Close() {
|
func (db *Database) Close() {
|
||||||
if db.Pool != nil {
|
if db.Pool != nil {
|
||||||
db.Pool.Close()
|
db.Pool.Close()
|
||||||
@@ -82,12 +101,16 @@ func (db *Database) ResetDatabase(ctx context.Context) error {
|
|||||||
|
|
||||||
schemaContent, err := os.ReadFile("migrations/schema.sql")
|
schemaContent, err := os.ReadFile("migrations/schema.sql")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error reading schema file: %v", err)
|
log.Println("Default migrations not found. Checking different directory")
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
migrationsPath := path.Join(cwd, "../..", "migrations/schema.sql")
|
||||||
|
schemaContent, err = os.ReadFile(migrationsPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error reading schema file: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
statements := strings.Split(string(schemaContent), ";")
|
for _, stmt := range strings.Split(string(schemaContent), ";") {
|
||||||
|
|
||||||
for _, stmt := range statements {
|
|
||||||
stmt = strings.TrimSpace(stmt)
|
stmt = strings.TrimSpace(stmt)
|
||||||
if stmt == "" {
|
if stmt == "" {
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -2,3 +2,5 @@ package endpoint
|
|||||||
|
|
||||||
// Endpoint for registering a user
|
// Endpoint for registering a user
|
||||||
const Register = "/api/v1/register"
|
const Register = "/api/v1/register"
|
||||||
|
const Login = "/api/v1/login"
|
||||||
|
const CreateServiceUser = "/api/v1/service/register"
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/token"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LoginAccount struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []token.Login `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginHandler struct {
|
||||||
|
UserStore model.UserStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoginHandler(userStore model.UserStore) *LoginHandler {
|
||||||
|
return &LoginHandler{UserStore: userStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login godoc
|
||||||
|
// @Summary Login
|
||||||
|
// @Description Login and be given an access token (requires JWT)
|
||||||
|
// @Tags users
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body LoginAccount true "Data to obtain a token"
|
||||||
|
// @Success 200 {object} LoginResponse
|
||||||
|
// @Failure 400 {object} LoginResponse
|
||||||
|
// @Failure 500 {object} LoginResponse
|
||||||
|
// @Router /login [post]
|
||||||
|
func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req LoginAccount
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp LoginResponse
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
||||||
|
fmt.Printf("Error: %v", err)
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if !exists {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Failure in user check"
|
||||||
|
} else {
|
||||||
|
if user, err := l.UserStore.GetUserByUsername(ctx, req.Username); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
hashing := utility.HashMash{Password: req.Password}
|
||||||
|
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
||||||
|
var tokGen utility.TokenGenerator
|
||||||
|
secretKey := config.GetSecretKey()
|
||||||
|
tokGen.SetSecretKey(secretKey)
|
||||||
|
if myToken, err := tokGen.GenerateToken(*user); err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = "Error generating token"
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, *myToken)
|
||||||
|
resp.Message = "Successful"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "User not found"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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 := mock.NewMockUserStore()
|
||||||
|
handler := NewLoginHandler(mockstore)
|
||||||
|
|
||||||
|
testUser := GetTestUser()
|
||||||
|
unhashedPassword := testUser.Password
|
||||||
|
hashing := utility.HashMash{Password: testUser.Password}
|
||||||
|
hashedPassword, err := hashing.HashPassword()
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
testUser.Password = hashedPassword
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
mockstore.CreateUser(ctx, &testUser)
|
||||||
|
|
||||||
|
loginUser := LoginAccount{Username: testUser.Username, Password: unhashedPassword}
|
||||||
|
jsonValue, _ := json.Marshal(loginUser)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.Login, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.Login(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response LoginResponse
|
||||||
|
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "An access token should have been returned")
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import "net/http"
|
|
||||||
import "encoding/json"
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||||
@@ -36,13 +36,21 @@ func NewUserHandler(userStore model.UserStore) *UserHandler {
|
|||||||
return &UserHandler{UserStore: userStore}
|
return &UserHandler{UserStore: userStore}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
// Register godoc
|
||||||
if r.Method != http.MethodPost {
|
// @Summary Register user
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
// @Description Create a user that can send texts (requires JWT)
|
||||||
return
|
// @Tags users
|
||||||
}
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
user, err := extractUserFromReq(r)
|
// @Security BearerAuth
|
||||||
|
// @Param request body RegisterUser true "Data to add user"
|
||||||
|
// @Success 200 {object} RegisterResponse
|
||||||
|
// @Failure 400 {object} RegisterResponse
|
||||||
|
// @Failure 500 {object} RegisterResponse
|
||||||
|
// @Router /register [post]
|
||||||
|
func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req RegisterUser
|
||||||
|
err := ExtractFromRequest(r, &req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
@@ -51,58 +59,42 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
|
|
||||||
var statusCode int
|
var statusCode int
|
||||||
resp := RegisterResponse{}
|
var resp RegisterResponse
|
||||||
|
user := user.User{Username: req.Username, Password: req.Password, PhoneNumber: req.PhoneNumber}
|
||||||
|
|
||||||
fmt.Println("Username:", user.Username)
|
fmt.Println("Username:", user.Username)
|
||||||
|
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
||||||
exists, err := h.UserStore.UserExists(ctx, user.Username)
|
if exists, err := u.UserStore.UserExists(ctx, user.Username); err != nil {
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error: %v", err)
|
fmt.Printf("Error: %v", err)
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
}
|
|
||||||
|
|
||||||
if exists {
|
|
||||||
// User already exists
|
|
||||||
statusCode = http.StatusBadRequest
|
|
||||||
resp.Message = "Failure in creating User"
|
|
||||||
} else {
|
} else {
|
||||||
hashing := utility.HashMash{user.Password}
|
if exists {
|
||||||
hashedPassword, err := hashing.HashPassword()
|
// User already exists
|
||||||
if err != nil {
|
statusCode = http.StatusBadRequest
|
||||||
statusCode = http.StatusInternalServerError
|
resp.Message = "Failure in creating User"
|
||||||
resp.Message = err.Error()
|
|
||||||
} else {
|
} else {
|
||||||
user.Password = hashedPassword
|
hashing := utility.HashMash{Password: user.Password}
|
||||||
err := h.UserStore.CreateUser(ctx, &user)
|
if hashedPassword, err := hashing.HashPassword(); err != nil {
|
||||||
if err != nil {
|
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
} else {
|
} else {
|
||||||
resp.Message = "Successful"
|
user.Password = hashedPassword
|
||||||
statusCode = http.StatusOK
|
err := u.UserStore.CreateUser(ctx, &user)
|
||||||
resp.Data = append(resp.Data, RegisterResponseItem{Id: user.Id, PhoneNumber: user.PhoneNumber, Username: user.Username})
|
if err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
resp.Message = "Successful"
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, RegisterResponseItem{Id: user.Id, PhoneNumber: user.PhoneNumber, Username: user.Username})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
respondWithJson(w, statusCode, &resp)
|
RespondWithJson(w, statusCode, &resp)
|
||||||
}
|
|
||||||
|
|
||||||
func extractUserFromReq(r *http.Request) (user model.User, myError error) {
|
|
||||||
var usr RegisterUser
|
|
||||||
err := json.NewDecoder(r.Body).Decode(&usr)
|
|
||||||
if err != nil {
|
|
||||||
return user, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return model.User{PhoneNumber: usr.PhoneNumber, Username: usr.Username, Password: usr.Password}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func respondWithJson(w http.ResponseWriter, statusCode int, data interface{}) {
|
|
||||||
w.Header().Set("Content-type", "application/json")
|
|
||||||
w.WriteHeader(statusCode)
|
|
||||||
json.NewEncoder(w).Encode(data)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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 TestCreateUserWithMock(t *testing.T) {
|
||||||
|
mockstore := mock.NewMockUserStore()
|
||||||
|
handler := NewUserHandler(mockstore)
|
||||||
|
|
||||||
|
testUser := GetTestUser()
|
||||||
|
jsonValue, _ := json.Marshal(testUser)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.Register, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.Register(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response RegisterResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||||
|
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RespondWithJson(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||||
|
w.Header().Set("Content-type", "application/json")
|
||||||
|
w.WriteHeader(statusCode)
|
||||||
|
json.NewEncoder(w).Encode(data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetTestUser() user.User {
|
||||||
|
return user.User{Username: "ghost", PhoneNumber: "+1234567890", Password: "dfgdffddfd"}
|
||||||
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
package model
|
|
||||||
+15
-19
@@ -7,21 +7,17 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
|
||||||
Id uuid.UUID `json:"id"`
|
|
||||||
PhoneNumber string `json:"phone_number"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserStore interface {
|
type UserStore interface {
|
||||||
CreateUser(ctx context.Context, user *User) error
|
CreateUser(ctx context.Context, user *user.User) error
|
||||||
GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
|
GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error)
|
||||||
GetUserByUsername(ctx context.Context, username string) (*User, error)
|
GetUserByUsername(ctx context.Context, username string) (*user.User, error)
|
||||||
GetAllUsers(ctx context.Context) ([]*User, error)
|
GetAllUsers(ctx context.Context) ([]*user.User, error)
|
||||||
UserExists(ctx context.Context, email string) (bool, error)
|
UserExists(ctx context.Context, username string) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type PGUserStore struct {
|
type PGUserStore struct {
|
||||||
@@ -32,7 +28,7 @@ func NewUserStore(db *pgxpool.Pool) *PGUserStore {
|
|||||||
return &PGUserStore{db: db}
|
return &PGUserStore{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PGUserStore) CreateUser(ctx context.Context, user *User) error {
|
func (s *PGUserStore) CreateUser(ctx context.Context, user *user.User) error {
|
||||||
query := `
|
query := `
|
||||||
INSERT INTO users (phone_number, username, password)
|
INSERT INTO users (phone_number, username, password)
|
||||||
VALUES ($1, $2, $3)
|
VALUES ($1, $2, $3)
|
||||||
@@ -44,10 +40,10 @@ func (s *PGUserStore) CreateUser(ctx context.Context, user *User) error {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error) {
|
func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error) {
|
||||||
query := `SELECT id, username, password, phone_number FROM users WHERE id = $1`
|
query := `SELECT id, username, password, phone_number FROM users WHERE id = $1`
|
||||||
|
|
||||||
var user User
|
var user user.User
|
||||||
err := s.db.QueryRow(ctx, query, id).Scan(
|
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||||
)
|
)
|
||||||
@@ -62,10 +58,10 @@ func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*User, err
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*User, error) {
|
func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*user.User, error) {
|
||||||
query := `SELECT id, username, password, phone_number FROM users WHERE username = $1`
|
query := `SELECT id, username, password, phone_number FROM users WHERE username = $1`
|
||||||
|
|
||||||
var user User
|
var user user.User
|
||||||
err := s.db.QueryRow(ctx, query, username).Scan(
|
err := s.db.QueryRow(ctx, query, username).Scan(
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||||
)
|
)
|
||||||
@@ -80,7 +76,7 @@ func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*User, error) {
|
func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*user.User, error) {
|
||||||
query := `SELECT id, username, password, phone_number FROM users`
|
query := `SELECT id, username, password, phone_number FROM users`
|
||||||
|
|
||||||
rows, err := s.db.Query(ctx, query)
|
rows, err := s.db.Query(ctx, query)
|
||||||
@@ -89,9 +85,9 @@ func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*User, error) {
|
|||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
var users []*User
|
var users []*user.User
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var user User
|
var user user.User
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package mock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MockUserStore struct {
|
||||||
|
Users map[uuid.UUID]*user.User
|
||||||
|
UsersByUsername map[string]*user.User
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockUserStore() *MockUserStore {
|
||||||
|
return &MockUserStore{
|
||||||
|
Users: make(map[uuid.UUID]*user.User),
|
||||||
|
UsersByUsername: make(map[string]*user.User),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) CreateUser(ctx context.Context, user *user.User) 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.UsersByUsername[user.Username]; exists {
|
||||||
|
return errors.New("User with email already exists")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Users[user.Id] = user
|
||||||
|
m.UsersByUsername[user.Username] = user
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
user, exists := m.Users[id]
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) GetUserByUsername(ctx context.Context, username string) (*user.User, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
user, exists := m.UsersByUsername[username]
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) GetAllUsers(ctx context.Context) ([]*user.User, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
users := make([]*user.User, 0, len(m.Users))
|
||||||
|
for _, user := range m.Users {
|
||||||
|
users = append(users, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
return users, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) UserExists(ctx context.Context, username string) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return false, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
_, exists := m.UsersByUsername[username]
|
||||||
|
if !exists {
|
||||||
|
return exists, nil
|
||||||
|
} else {
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package utility
|
package utility
|
||||||
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package utility
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/token"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ROLE_TYPE = "regular"
|
||||||
|
const TOKEN_TYPE = "Bearer"
|
||||||
|
|
||||||
|
type TokenGenerator struct {
|
||||||
|
SecretKey []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) SetSecretKey(secretKey string) {
|
||||||
|
t.SecretKey = []byte(secretKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) GenerateToken(user user.User) (*token.Login, error) {
|
||||||
|
issuedAt := time.Now()
|
||||||
|
expirationTime := time.Now().Add(4 * time.Hour)
|
||||||
|
claims := t.generateClaims(user, TOKEN_TYPE, issuedAt, expirationTime)
|
||||||
|
|
||||||
|
myToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
if tokenString, err := myToken.SignedString(t.SecretKey); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return &token.Login{AccessToken: tokenString, TokenType: TOKEN_TYPE, ExpiresIn: expirationTime.Unix()}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) generateClaims(user user.User, role string, issuedAt time.Time, expiredAt time.Time) token.Claims {
|
||||||
|
return token.Claims{
|
||||||
|
UserId: user.Id,
|
||||||
|
Role: role,
|
||||||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
|
Issuer: config.App_Name,
|
||||||
|
ExpiresAt: jwt.NewNumericDate(expiredAt),
|
||||||
|
IssuedAt: jwt.NewNumericDate(issuedAt),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package version
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var (
|
||||||
|
Version = "dev"
|
||||||
|
BuildTime = "unknown"
|
||||||
|
Commit = "unknown"
|
||||||
|
GoVersion = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
func String() string {
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"Version: %s\nBuild Date: %s\nCommit: %s\nGo Version: %s",
|
||||||
|
Version, BuildTime, Commit, GoVersion,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||||
|
|
||||||
DROP TABLE IF EXISTS users CASCADE;
|
DROP TABLE IF EXISTS users CASCADE;
|
||||||
|
DROP TABLE IF EXISTS service_users CASCADE;
|
||||||
|
|
||||||
CREATE TABLE users (
|
CREATE TABLE users (
|
||||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
@@ -9,3 +10,9 @@ CREATE TABLE users (
|
|||||||
password TEXT NOT NULL
|
password TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE service_users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
passphrase TEXT NOT NULL,
|
||||||
|
created timestamptz DEFAULT now()
|
||||||
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user