Compare commits
7 Commits
6a9061a3de
...
detached3
| Author | SHA1 | Date | |
|---|---|---|---|
| 64e34dabfe | |||
| 604dc9b82c | |||
| 39d715b49f | |||
| f503e45be1 | |||
| 588576b82f | |||
| 07d3ea44ea | |||
| 5d80a68b44 |
165
.github/workflows/test.yml
vendored
Normal file
165
.github/workflows/test.yml
vendored
Normal file
@ -0,0 +1,165 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
paths:
|
||||
- 'back/**'
|
||||
pull_request:
|
||||
branches: [ main, develop ]
|
||||
paths:
|
||||
- 'back/**'
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./back
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15
|
||||
env:
|
||||
POSTGRES_USER: test_user
|
||||
POSTGRES_PASSWORD: test_password
|
||||
POSTGRES_DB: logidex_test
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
options: >-
|
||||
--health-cmd "redis-cli ping"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
ports:
|
||||
- 6379:6379
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.24]
|
||||
test-type: [unit, integration]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Install dependencies
|
||||
run: go mod download
|
||||
|
||||
- name: Verify dependencies
|
||||
run: go mod verify
|
||||
|
||||
- name: Run linters
|
||||
run: |
|
||||
go vet ./...
|
||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
||||
golangci-lint run
|
||||
|
||||
- name: Run unit tests
|
||||
if: matrix.test-type == 'unit'
|
||||
run: |
|
||||
make test-unit
|
||||
|
||||
- name: Run integration tests
|
||||
if: matrix.test-type == 'integration'
|
||||
env:
|
||||
TEST_DB_HOST: localhost
|
||||
TEST_DB_PORT: 5432
|
||||
TEST_DB_NAME: logidex_test
|
||||
TEST_DB_USER: test_user
|
||||
TEST_DB_PASSWORD: test_password
|
||||
TEST_REDIS_HOST: localhost
|
||||
TEST_REDIS_PORT: 6379
|
||||
run: |
|
||||
make test-integration
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: |
|
||||
make test-coverage-html
|
||||
|
||||
- name: Upload coverage reports
|
||||
uses: codecov/codecov-action@v3
|
||||
with:
|
||||
file: ./coverage.out
|
||||
flags: unittests
|
||||
name: codecov-umbrella
|
||||
|
||||
- name: Check coverage threshold
|
||||
run: |
|
||||
make test-coverage-check
|
||||
|
||||
- name: Run race condition tests
|
||||
run: |
|
||||
make test-race
|
||||
|
||||
benchmark:
|
||||
name: Benchmark
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: 1.24
|
||||
|
||||
- name: Run benchmarks
|
||||
run: |
|
||||
make test-bench | tee benchmark.txt
|
||||
|
||||
- name: Store benchmark results
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: benchmark-results
|
||||
path: benchmark.txt
|
||||
|
||||
security:
|
||||
name: Security Scan
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: 1.24
|
||||
|
||||
- name: Install gosec
|
||||
run: go install github.com/securecodewarrior/gosec/v2/cmd/gosec@latest
|
||||
|
||||
- name: Run security scan
|
||||
run: gosec ./...
|
||||
|
||||
- name: Install govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
|
||||
- name: Run vulnerability check
|
||||
run: govulncheck ./...
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
||||
.idea
|
||||
combined.yaml
|
||||
166
Makefile
Normal file
166
Makefile
Normal file
@ -0,0 +1,166 @@
|
||||
# Go Test Makefile
|
||||
|
||||
.PHONY: test test-unit test-integration test-coverage test-race test-verbose test-short clean-test lint fmt build
|
||||
|
||||
# Default target
|
||||
all: test
|
||||
|
||||
# Run all tests
|
||||
test:
|
||||
go test ./...
|
||||
|
||||
# Run only unit tests (excluding integration tests)
|
||||
test-unit:
|
||||
go test -short ./...
|
||||
|
||||
# Run integration tests
|
||||
test-integration:
|
||||
go test -run TestIntegration ./test/integration/...
|
||||
|
||||
# Run tests with coverage
|
||||
test-coverage:
|
||||
go test -cover ./...
|
||||
|
||||
# Generate detailed coverage report
|
||||
test-coverage-html:
|
||||
go test -coverprofile=coverage.out ./...
|
||||
go tool cover -html=coverage.out -o coverage.html
|
||||
@echo "Coverage report generated: coverage.html"
|
||||
|
||||
# Run tests with race detection
|
||||
test-race:
|
||||
go test -race ./...
|
||||
|
||||
# Run tests in verbose mode
|
||||
test-verbose:
|
||||
go test -v ./...
|
||||
|
||||
# Run tests with short timeout (for CI/CD)
|
||||
test-short:
|
||||
go test -short -timeout=60s ./...
|
||||
|
||||
# Run specific test
|
||||
test-specific:
|
||||
@read -p "Enter test name pattern: " pattern; \
|
||||
go test -run $$pattern ./...
|
||||
|
||||
# Run benchmark tests
|
||||
test-bench:
|
||||
go test -bench=. ./...
|
||||
|
||||
# Run tests for specific package
|
||||
test-pkg:
|
||||
@read -p "Enter package path: " pkg; \
|
||||
go test ./$$pkg
|
||||
|
||||
# Clean test cache and temporary files
|
||||
clean-test:
|
||||
go clean -testcache
|
||||
rm -f coverage.out coverage.html
|
||||
|
||||
# Lint code
|
||||
lint:
|
||||
go vet ./...
|
||||
@if command -v golangci-lint >/dev/null 2>&1; then \
|
||||
golangci-lint run; \
|
||||
else \
|
||||
echo "golangci-lint not installed. Installing..."; \
|
||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest; \
|
||||
golangci-lint run; \
|
||||
fi
|
||||
|
||||
# Format code
|
||||
fmt:
|
||||
go fmt ./...
|
||||
|
||||
# Build the application
|
||||
build:
|
||||
go build ./...
|
||||
|
||||
# Run tests in watch mode (requires entr)
|
||||
test-watch:
|
||||
@if command -v entr >/dev/null 2>&1; then \
|
||||
find . -name "*.go" | entr -c go test ./...; \
|
||||
else \
|
||||
echo "entr not installed. Please install it to use watch mode."; \
|
||||
echo "On macOS: brew install entr"; \
|
||||
echo "On Ubuntu: apt-get install entr"; \
|
||||
fi
|
||||
|
||||
# Generate test mocks (if using mockgen)
|
||||
generate-mocks:
|
||||
@if command -v mockgen >/dev/null 2>&1; then \
|
||||
go generate ./...; \
|
||||
else \
|
||||
echo "mockgen not installed. Installing..."; \
|
||||
go install github.com/golang/mock/mockgen@latest; \
|
||||
go generate ./...; \
|
||||
fi
|
||||
|
||||
# Setup test environment
|
||||
setup-test:
|
||||
go mod tidy
|
||||
go mod download
|
||||
|
||||
# Run tests with JSON output for CI/CD
|
||||
test-json:
|
||||
go test -json ./... > test-results.json
|
||||
|
||||
# Check test coverage threshold
|
||||
test-coverage-check:
|
||||
@coverage=$$(go test -cover ./... | grep "coverage:" | awk '{print $$3}' | sed 's/%//' | awk '{sum+=$$1; count++} END {print sum/count}'); \
|
||||
threshold=80; \
|
||||
if [ "$$(echo "$$coverage >= $$threshold" | bc -l)" -eq 1 ]; then \
|
||||
echo "Coverage $$coverage% meets threshold of $$threshold%"; \
|
||||
else \
|
||||
echo "Coverage $$coverage% below threshold of $$threshold%"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
# Run tests with profiling
|
||||
test-profile:
|
||||
go test -cpuprofile=cpu.prof -memprofile=mem.prof ./...
|
||||
@echo "Profile files generated: cpu.prof, mem.prof"
|
||||
@echo "View CPU profile: go tool pprof cpu.prof"
|
||||
@echo "View Memory profile: go tool pprof mem.prof"
|
||||
|
||||
# Test specific layers
|
||||
test-domain:
|
||||
go test ./internal/api/*/domain/...
|
||||
|
||||
test-repo:
|
||||
go test ./internal/api/*/repo/...
|
||||
|
||||
test-service:
|
||||
go test ./internal/api/*/service/...
|
||||
|
||||
test-handler:
|
||||
go test ./internal/api/*/handler/...
|
||||
|
||||
test-utils:
|
||||
go test ./internal/phoneutil/... ./test/testutil/...
|
||||
|
||||
# Help target
|
||||
help:
|
||||
@echo "Available targets:"
|
||||
@echo " test - Run all tests"
|
||||
@echo " test-unit - Run unit tests only"
|
||||
@echo " test-integration - Run integration tests"
|
||||
@echo " test-coverage - Run tests with coverage"
|
||||
@echo " test-coverage-html- Generate HTML coverage report"
|
||||
@echo " test-race - Run tests with race detection"
|
||||
@echo " test-verbose - Run tests in verbose mode"
|
||||
@echo " test-short - Run tests with short timeout"
|
||||
@echo " test-bench - Run benchmark tests"
|
||||
@echo " test-watch - Run tests in watch mode"
|
||||
@echo " clean-test - Clean test cache and files"
|
||||
@echo " lint - Run linters"
|
||||
@echo " fmt - Format code"
|
||||
@echo " build - Build application"
|
||||
@echo " setup-test - Setup test environment"
|
||||
@echo " test-domain - Test domain layer only"
|
||||
@echo " test-service - Test service layer only"
|
||||
@echo " test-handler - Test handler layer only"
|
||||
@echo " test-repo - Test repository layer only"
|
||||
@echo " test-utils - Test utility packages"
|
||||
@echo " help - Show this help message"
|
||||
@ -137,9 +137,14 @@ components:
|
||||
type: boolean
|
||||
description: Status of the verification
|
||||
example: true
|
||||
message:
|
||||
type: string
|
||||
description: Confirmation message
|
||||
example: "OTP verified successfully"
|
||||
required:
|
||||
- redirect_url
|
||||
- ok
|
||||
- message
|
||||
AcceptConsentRequest:
|
||||
type: object
|
||||
properties:
|
||||
@ -147,8 +152,14 @@ components:
|
||||
type: string
|
||||
description: The consent challenge to accept
|
||||
example: "challenge123"
|
||||
phone_number:
|
||||
type: string
|
||||
description: Phone number associated with the consent
|
||||
example: "+79999999999"
|
||||
maxLength: 15
|
||||
required:
|
||||
- consent_challenge
|
||||
- phone_number
|
||||
AcceptConsentResponse:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@ -5,35 +5,11 @@ info:
|
||||
servers:
|
||||
- url: https://api.example.com/v1
|
||||
paths:
|
||||
/users:
|
||||
get:
|
||||
summary: Get all users
|
||||
responses:
|
||||
'200':
|
||||
description: A list of users
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/User'
|
||||
post:
|
||||
summary: Create a new user
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UserCreate'
|
||||
responses:
|
||||
'201':
|
||||
description: User created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/User'
|
||||
/users/{userId}:
|
||||
get:
|
||||
tags:
|
||||
- users
|
||||
operationId: getUserById
|
||||
summary: Get a user by ID
|
||||
parameters:
|
||||
- name: userId
|
||||
@ -47,92 +23,65 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
user:
|
||||
$ref: '#/components/schemas/User'
|
||||
required:
|
||||
- user
|
||||
|
||||
|
||||
|
||||
'404':
|
||||
description: User not found
|
||||
put:
|
||||
summary: Update a user by ID
|
||||
parameters:
|
||||
- name: userId
|
||||
in: path
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
message:
|
||||
type: string
|
||||
example: "User not found"
|
||||
required:
|
||||
- message
|
||||
/users:
|
||||
post:
|
||||
tags:
|
||||
- users
|
||||
operationId: createUser
|
||||
summary: "Create a new user with phone number"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UserUpdate'
|
||||
$ref: '#/components/schemas/UserCreate'
|
||||
responses:
|
||||
'200':
|
||||
description: User updated
|
||||
description: User created successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/User'
|
||||
'404':
|
||||
description: User not found
|
||||
delete:
|
||||
summary: Delete a user by ID
|
||||
parameters:
|
||||
- name: userId
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
'204':
|
||||
description: User deleted successfully
|
||||
'404':
|
||||
description: User not found
|
||||
|
||||
components:
|
||||
schemas:
|
||||
User:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
uuid:
|
||||
type: string
|
||||
example: "123"
|
||||
username:
|
||||
phone_number:
|
||||
type: string
|
||||
example: "johndoe"
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
example: "johndoe@example.com"
|
||||
required:
|
||||
- id
|
||||
- username
|
||||
- email
|
||||
- uuid
|
||||
- phone_number
|
||||
UserCreate:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
phone_number:
|
||||
type: string
|
||||
example: "johndoe"
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
example: "johndoe@example.com"
|
||||
password:
|
||||
type: string
|
||||
format: password
|
||||
|
||||
required:
|
||||
- username
|
||||
- email
|
||||
- password
|
||||
UserUpdate:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
example: "john_doe_updated"
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
example: "johnupdated@example.com"
|
||||
required:
|
||||
- username
|
||||
- email
|
||||
- phone_number
|
||||
|
||||
2
build-docker.sh
Executable file
2
build-docker.sh
Executable file
@ -0,0 +1,2 @@
|
||||
docker build -t git.logidex.ru/fakz9/id-backend:latest .
|
||||
docker push git.logidex.ru/fakz9/id-backend:latest
|
||||
@ -1,28 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
authApi "git.logidex.ru/fakz9/logidex-id/internal/api/auth/handler"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/db"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/hydra_client"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/redis"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"strconv"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/server"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
func main() {
|
||||
config.Init()
|
||||
err := redis.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
hydra_client.InitClient()
|
||||
fx.New(
|
||||
// Core dependencies
|
||||
fx.Provide(
|
||||
config.NewConfig,
|
||||
redis.NewRedisClient,
|
||||
hydra_client.NewHydraClient,
|
||||
),
|
||||
|
||||
app := fiber.New()
|
||||
api := app.Group("/api")
|
||||
authApi.RegisterApp(api)
|
||||
|
||||
err = app.Listen(":" + strconv.Itoa(config.Cfg.App.Port))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Modules
|
||||
db.Module,
|
||||
server.Module,
|
||||
user.Module,
|
||||
auth.Module,
|
||||
).Run()
|
||||
}
|
||||
|
||||
1
combine.sh
Executable file
1
combine.sh
Executable file
@ -0,0 +1 @@
|
||||
swagger-cli bundle openapi.yaml --outfile combined.yaml --type yaml
|
||||
@ -8,3 +8,11 @@ redis:
|
||||
|
||||
hydra:
|
||||
host: https://oauth2.logidex.ru/admin
|
||||
|
||||
db:
|
||||
host: localhost
|
||||
port: 5432
|
||||
user: postgres
|
||||
password: postgres
|
||||
dbname: logidex-id
|
||||
|
||||
|
||||
30
go.mod
30
go.mod
@ -2,6 +2,21 @@ module git.logidex.ru/fakz9/logidex-id
|
||||
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
github.com/gofiber/fiber/v2 v2.52.9
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.5
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/nyaruka/phonenumbers v1.6.4
|
||||
github.com/oapi-codegen/runtime v1.1.2
|
||||
github.com/ory/hydra-client-go v1.11.8
|
||||
github.com/redis/rueidis v1.0.63
|
||||
github.com/spf13/viper v1.20.1
|
||||
github.com/stretchr/testify v1.10.0
|
||||
go.uber.org/fx v1.24.0
|
||||
)
|
||||
|
||||
require (
|
||||
cel.dev/expr v0.19.1 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
@ -18,17 +33,13 @@ require (
|
||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||
github.com/go-openapi/swag v0.23.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.9.2 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||
github.com/gofiber/fiber/v2 v2.52.9 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.3.0 // indirect
|
||||
github.com/google/cel-go v0.24.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.7.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/klauspost/compress v1.17.9 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
@ -38,10 +49,9 @@ require (
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.5.0 // indirect
|
||||
github.com/oapi-codegen/runtime v1.1.2 // indirect
|
||||
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect
|
||||
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect
|
||||
github.com/ory/hydra-client-go v1.11.8 // indirect
|
||||
github.com/onsi/ginkgo v1.16.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/perimeterx/marshmallow v1.1.5 // indirect
|
||||
github.com/pganalyze/pg_query_go/v6 v6.1.0 // indirect
|
||||
@ -49,12 +59,11 @@ require (
|
||||
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
|
||||
github.com/pingcap/log v1.1.0 // indirect
|
||||
github.com/pingcap/tidb/pkg/parser v0.0.0-20250324122243-d51e00e5bbf0 // indirect
|
||||
github.com/redis/rueidis v1.0.63 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/riza-io/grpc-go v0.2.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.7.0 // indirect
|
||||
github.com/samber/lo v1.51.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/speakeasy-api/jsonpath v0.6.0 // indirect
|
||||
github.com/speakeasy-api/openapi-overlay v0.10.2 // indirect
|
||||
@ -62,9 +71,9 @@ require (
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
github.com/spf13/cobra v1.9.1 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/spf13/viper v1.20.1 // indirect
|
||||
github.com/sqlc-dev/sqlc v1.29.0 // indirect
|
||||
github.com/stoewer/go-strcase v1.2.0 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
@ -74,6 +83,7 @@ require (
|
||||
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
|
||||
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/dig v1.19.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
golang.org/x/crypto v0.40.0 // indirect
|
||||
|
||||
80
go.sum
80
go.sum
@ -69,6 +69,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
|
||||
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
@ -78,6 +80,10 @@ github.com/getkin/kin-openapi v0.132.0/go.mod h1:3OlG51PCYNsPByuiMB0t4fjnNlIDnaE
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
@ -85,8 +91,12 @@ github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ
|
||||
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
|
||||
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
|
||||
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk=
|
||||
github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/gofiber/fiber/v2 v2.52.9 h1:YjKl5DOiyP3j0mO61u3NTmK7or8GzzWzCFzkboyP5cw=
|
||||
github.com/gofiber/fiber/v2 v2.52.9/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
@ -115,6 +125,8 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/cel-go v0.24.1 h1:jsBCtxG8mM5wiUJDSGUqU0K7Mtr3w7Eyv00rw4DiZxI=
|
||||
@ -127,6 +139,8 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||
@ -137,6 +151,8 @@ github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hf
|
||||
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
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=
|
||||
@ -157,6 +173,8 @@ github.com/jackc/pgx/v5 v5.7.5 h1:JHGfMnQY+IEtGM63d+NGMjoRpysB2JBwDr5fsngwmJs=
|
||||
github.com/jackc/pgx/v5 v5.7.5/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
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/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
|
||||
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
@ -170,8 +188,12 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o
|
||||
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
||||
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
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.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
@ -186,7 +208,10 @@ github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwd
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||
github.com/nyaruka/phonenumbers v1.6.4 h1:GFAa844VqRKJvO7oboosM1q3gFVgYvyNe0O6CCbg33A=
|
||||
github.com/nyaruka/phonenumbers v1.6.4/go.mod h1:7gjs+Lchqm49adhAKB5cdcng5ZXgt6x7Jgvi0ZorUtU=
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.5.0 h1:iJvF8SdB/3/+eGOXEpsWkD8FQAHj6mqkb6Fnsoc8MFU=
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.5.0/go.mod h1:fwlMxUEMuQK5ih9aymrxKPQqNm2n8bdLk1ppjH+lr9w=
|
||||
github.com/oapi-codegen/runtime v1.1.2 h1:P2+CubHq8fO4Q6fV1tqDBZHCwpVpvPg7oKiYzQgXIyI=
|
||||
@ -199,12 +224,16 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W
|
||||
github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
|
||||
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
|
||||
github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
|
||||
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
||||
github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
|
||||
github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8=
|
||||
github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY=
|
||||
github.com/ory/hydra-client-go v1.11.8 h1:GwJjvH/DBcfYzoST4vUpi4pIRzDGH5oODKpIVuhwVyc=
|
||||
github.com/ory/hydra-client-go v1.11.8/go.mod h1:4YuBuwUEC4yiyDrnKjGYc1tB3gUXan4ZiUYMjXJbfxA=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
@ -223,6 +252,7 @@ github.com/pingcap/log v1.1.0/go.mod h1:DWQW5jICDR7UJh4HtxXSM20Churx4CQL0fwL/SoO
|
||||
github.com/pingcap/tidb/pkg/parser v0.0.0-20250324122243-d51e00e5bbf0 h1:W3rpAI3bubR6VWOcwxDIG0Gz9G5rl5b3SL116T0vBt0=
|
||||
github.com/pingcap/tidb/pkg/parser v0.0.0-20250324122243-d51e00e5bbf0/go.mod h1:+8feuexTKcXHZF/dkDfvCwEyBAmgb4paFc3/WeYV2eE=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/redis/rueidis v1.0.63 h1:zSt5focn0YgrgBAE5NcnAibyKf3ZKyv+eCQHk62jEFk=
|
||||
@ -234,11 +264,12 @@ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ
|
||||
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
|
||||
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
|
||||
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
|
||||
github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI=
|
||||
github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
@ -262,14 +293,20 @@ github.com/sqlc-dev/sqlc v1.29.0/go.mod h1:BavmYw11px5AdPOjAVHmb9fctP5A8GTziC38w
|
||||
github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=
|
||||
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
|
||||
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||
@ -291,12 +328,30 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
|
||||
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
|
||||
go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
|
||||
go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
|
||||
go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
|
||||
go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
|
||||
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
|
||||
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
|
||||
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=
|
||||
go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
||||
go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=
|
||||
go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo=
|
||||
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
@ -434,8 +489,6 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
@ -588,11 +641,14 @@ google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/
|
||||
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-20190902080502-41f04d3bba15/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/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
@ -613,14 +669,30 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
modernc.org/cc/v4 v4.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic=
|
||||
modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU=
|
||||
modernc.org/ccgo/v4 v4.25.1/go.mod h1:njjuAYiPflywOOrm3B7kCB444ONP5pAVr8PIEoE0uDw=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s=
|
||||
modernc.org/libc v1.62.1/go.mod h1:iXhATfJQLjG3NWy56a6WVU73lWOcdYVxsvwCgoPljuo=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
|
||||
modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI=
|
||||
modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
|
||||
51
internal/api/auth/domain/auth_domain.go
Normal file
51
internal/api/auth/domain/auth_domain.go
Normal file
@ -0,0 +1,51 @@
|
||||
package domain
|
||||
|
||||
import "context"
|
||||
|
||||
type AuthRepository interface {
|
||||
SaveOtpRequest(ctx context.Context, uuid string, code string) error
|
||||
GetOtpRequest(ctx context.Context, uuid string) (*string, error)
|
||||
}
|
||||
|
||||
type ErrOtpNotFound struct {
|
||||
Uuid string
|
||||
}
|
||||
|
||||
func (e ErrOtpNotFound) Error() string {
|
||||
return "OTP request not found for UUID: " + e.Uuid
|
||||
}
|
||||
|
||||
type ErrUserNotFound struct {
|
||||
PhoneNumber string
|
||||
}
|
||||
|
||||
func (e ErrUserNotFound) Error() string {
|
||||
return "User not found with phone number: " + e.PhoneNumber
|
||||
}
|
||||
|
||||
type ErrOtpInvalid struct {
|
||||
Code string
|
||||
Uuid string
|
||||
}
|
||||
|
||||
func (e ErrOtpInvalid) Error() string {
|
||||
return "Invalid OTP code: " + e.Code + " for UUID: " + e.Uuid
|
||||
}
|
||||
|
||||
type ErrInvalidHydraAccept struct {
|
||||
Message string
|
||||
Uuid string
|
||||
}
|
||||
|
||||
func (e ErrInvalidHydraAccept) Error() string {
|
||||
return "Invalid Hydra accept request: " + e.Message + " for UUID: " + e.Uuid
|
||||
}
|
||||
|
||||
type ErrInvalidPhoneNumber struct {
|
||||
PhoneNumber string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e ErrInvalidPhoneNumber) Error() string {
|
||||
return "Invalid phone number: " + e.PhoneNumber + ", error: " + e.Err.Error()
|
||||
}
|
||||
146
internal/api/auth/domain/auth_domain_test.go
Normal file
146
internal/api/auth/domain/auth_domain_test.go
Normal file
@ -0,0 +1,146 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestErrOtpNotFound_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
uuid string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message",
|
||||
uuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
want: "OTP request not found for UUID: 123e4567-e89b-12d3-a456-426614174000",
|
||||
},
|
||||
{
|
||||
name: "handles empty uuid",
|
||||
uuid: "",
|
||||
want: "OTP request not found for UUID: ",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrOtpNotFound{Uuid: tt.uuid}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrUserNotFound_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message",
|
||||
phoneNumber: "+1234567890",
|
||||
want: "User not found with phone number: +1234567890",
|
||||
},
|
||||
{
|
||||
name: "handles empty phone number",
|
||||
phoneNumber: "",
|
||||
want: "User not found with phone number: ",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrUserNotFound{PhoneNumber: tt.phoneNumber}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrOtpInvalid_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
code string
|
||||
uuid string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message",
|
||||
code: "123456",
|
||||
uuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
want: "Invalid OTP code: 123456 for UUID: 123e4567-e89b-12d3-a456-426614174000",
|
||||
},
|
||||
{
|
||||
name: "handles empty values",
|
||||
code: "",
|
||||
uuid: "",
|
||||
want: "Invalid OTP code: for UUID: ",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrOtpInvalid{Code: tt.code, Uuid: tt.uuid}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrInvalidHydraAccept_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
message string
|
||||
uuid string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message",
|
||||
message: "Invalid response",
|
||||
uuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
want: "Invalid Hydra accept request: Invalid response for UUID: 123e4567-e89b-12d3-a456-426614174000",
|
||||
},
|
||||
{
|
||||
name: "handles empty values",
|
||||
message: "",
|
||||
uuid: "",
|
||||
want: "Invalid Hydra accept request: for UUID: ",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrInvalidHydraAccept{Message: tt.message, Uuid: tt.uuid}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrInvalidPhoneNumber_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message with nested error",
|
||||
phoneNumber: "invalid",
|
||||
err: assert.AnError,
|
||||
want: "Invalid phone number: invalid, error: assert.AnError general error for testing",
|
||||
},
|
||||
{
|
||||
name: "handles empty phone number",
|
||||
phoneNumber: "",
|
||||
err: assert.AnError,
|
||||
want: "Invalid phone number: , error: assert.AnError general error for testing",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrInvalidPhoneNumber{PhoneNumber: tt.phoneNumber, Err: tt.err}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
20
internal/api/auth/fx.go
Normal file
20
internal/api/auth/fx.go
Normal file
@ -0,0 +1,20 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/handler"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/repo"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/service"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
var Module = fx.Options(
|
||||
fx.Provide(
|
||||
repo.NewAuthRepo,
|
||||
service.NewAuthService,
|
||||
handler.NewAuthHandler,
|
||||
),
|
||||
fx.Invoke(func(handler *handler.AuthHandler, router fiber.Router) {
|
||||
handler.RegisterRoutes(router)
|
||||
}),
|
||||
)
|
||||
@ -14,6 +14,9 @@ import (
|
||||
type AcceptConsentRequest struct {
|
||||
// ConsentChallenge The consent challenge to accept
|
||||
ConsentChallenge string `json:"consent_challenge"`
|
||||
|
||||
// PhoneNumber Phone number associated with the consent
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
}
|
||||
|
||||
// AcceptConsentResponse defines model for AcceptConsentResponse.
|
||||
@ -56,6 +59,9 @@ type VerifyOTPRequest struct {
|
||||
|
||||
// VerifyOTPResponse defines model for VerifyOTPResponse.
|
||||
type VerifyOTPResponse struct {
|
||||
// Message Confirmation message
|
||||
Message string `json:"message"`
|
||||
|
||||
// Ok Status of the verification
|
||||
Ok bool `json:"ok"`
|
||||
|
||||
|
||||
@ -2,113 +2,68 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/hydra_client"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/redis"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/service"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
hydraApi "github.com/ory/hydra-client-go"
|
||||
)
|
||||
|
||||
type AuthHandler struct{}
|
||||
|
||||
func (a AuthHandler) PostAuthConsentAccept(ctx context.Context, request PostAuthConsentAcceptRequestObject) (PostAuthConsentAcceptResponseObject, error) {
|
||||
hydraClient := hydra_client.GetClient()
|
||||
|
||||
hydraRequest := hydraApi.AcceptConsentRequest{}
|
||||
hydraRequest.SetGrantScope([]string{"openid"})
|
||||
hydraRequest.SetRemember(true)
|
||||
hydraRequest.SetRememberFor(3600) // 1 hour
|
||||
|
||||
hydraResponse, r, err := hydraClient.AdminApi.
|
||||
AcceptConsentRequest(ctx).
|
||||
ConsentChallenge(request.Body.ConsentChallenge).
|
||||
AcceptConsentRequest(hydraRequest).
|
||||
Execute()
|
||||
if err != nil {
|
||||
return PostAuthConsentAccept400JSONResponse{
|
||||
RedirectUrl: "",
|
||||
Ok: false,
|
||||
Message: "Failed to accept consent request",
|
||||
}, nil
|
||||
}
|
||||
fmt.Println(r)
|
||||
return PostAuthConsentAccept200JSONResponse{
|
||||
RedirectUrl: hydraResponse.RedirectTo,
|
||||
Ok: true,
|
||||
Message: "Успешно",
|
||||
}, nil
|
||||
type AuthHandler struct {
|
||||
service service.AuthService
|
||||
}
|
||||
|
||||
func (a AuthHandler) PostAuthOtpRequest(ctx context.Context, request PostAuthOtpRequestRequestObject) (PostAuthOtpRequestResponseObject, error) {
|
||||
redisClient := redis.GetClient()
|
||||
|
||||
// TODO implement OTP request logic
|
||||
|
||||
err := redisClient.Do(ctx, redisClient.B().Set().Key("otp:"+request.Body.PhoneNumber).Value("123456").Build()).Error()
|
||||
func (h AuthHandler) PostAuthOtpRequest(ctx context.Context, request PostAuthOtpRequestRequestObject) (PostAuthOtpRequestResponseObject, error) {
|
||||
err := h.service.OtpRequest(ctx, request.Body.PhoneNumber)
|
||||
if err != nil {
|
||||
return PostAuthOtpRequest400JSONResponse{
|
||||
Message: "Failed to set OTP in Redis",
|
||||
Message: err.Error(),
|
||||
Ok: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return PostAuthOtpRequest200JSONResponse{
|
||||
Message: "Код успешно отправлен",
|
||||
Message: "OTP request successful",
|
||||
Ok: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a AuthHandler) PostAuthOtpVerify(ctx context.Context, request PostAuthOtpVerifyRequestObject) (PostAuthOtpVerifyResponseObject, error) {
|
||||
redisClient := redis.GetClient()
|
||||
hydraClient := hydra_client.GetClient()
|
||||
|
||||
sentOtp, err := redisClient.Do(ctx, redisClient.B().Get().Key("otp:"+request.Body.PhoneNumber).Build()).ToString()
|
||||
func (h AuthHandler) PostAuthOtpVerify(ctx context.Context, request PostAuthOtpVerifyRequestObject) (PostAuthOtpVerifyResponseObject, error) {
|
||||
redirectUrl, err := h.service.OtpVerify(ctx, request.Body.PhoneNumber, request.Body.Otp, request.Body.LoginChallenge)
|
||||
if err != nil {
|
||||
return PostAuthOtpVerify400JSONResponse{
|
||||
RedirectUrl: "",
|
||||
Message: err.Error(),
|
||||
Ok: false,
|
||||
}, nil
|
||||
}
|
||||
if sentOtp != request.Body.Otp {
|
||||
return PostAuthOtpVerify400JSONResponse{
|
||||
RedirectUrl: "",
|
||||
Ok: false,
|
||||
}, nil
|
||||
}
|
||||
hydraRequest := hydraApi.AcceptLoginRequest{}
|
||||
// TODO read user from database by phone number
|
||||
|
||||
hydraRequest.SetSubject("some-user-id") // Replace with actual user ID
|
||||
hydraRequest.SetRemember(true)
|
||||
hydraRequest.SetRememberFor(3600) // 1 hour
|
||||
|
||||
hydraResponse, r, err := hydraClient.AdminApi.
|
||||
AcceptLoginRequest(ctx).
|
||||
LoginChallenge(request.Body.LoginChallenge).
|
||||
AcceptLoginRequest(hydraRequest).
|
||||
Execute()
|
||||
fmt.Println(r)
|
||||
if err != nil {
|
||||
return PostAuthOtpVerify400JSONResponse{
|
||||
RedirectUrl: "",
|
||||
Ok: false,
|
||||
}, nil
|
||||
}
|
||||
return PostAuthOtpVerify200JSONResponse{
|
||||
RedirectUrl: hydraResponse.RedirectTo,
|
||||
Message: "OTP verification successful",
|
||||
Ok: true,
|
||||
RedirectUrl: redirectUrl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h AuthHandler) PostAuthConsentAccept(ctx context.Context, request PostAuthConsentAcceptRequestObject) (PostAuthConsentAcceptResponseObject, error) {
|
||||
redirectUrl, err := h.service.AcceptConsent(ctx, request.Body.PhoneNumber, request.Body.ConsentChallenge)
|
||||
if err != nil {
|
||||
return PostAuthConsentAccept400JSONResponse{
|
||||
Message: err.Error(),
|
||||
Ok: false,
|
||||
RedirectUrl: "",
|
||||
}, nil
|
||||
}
|
||||
return PostAuthConsentAccept200JSONResponse{
|
||||
Message: "Consent accepted successfully",
|
||||
Ok: true,
|
||||
RedirectUrl: redirectUrl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var _ StrictServerInterface = (*AuthHandler)(nil)
|
||||
|
||||
func NewAuthHandler() *AuthHandler {
|
||||
return &AuthHandler{}
|
||||
func NewAuthHandler(service service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{service: service}
|
||||
}
|
||||
|
||||
func RegisterApp(router fiber.Router) {
|
||||
//authGroup := router.Group("/auth")
|
||||
server := NewStrictHandler(NewAuthHandler(), nil)
|
||||
func (h AuthHandler) RegisterRoutes(router fiber.Router) {
|
||||
server := NewStrictHandler(h, nil)
|
||||
RegisterHandlers(router, server)
|
||||
|
||||
}
|
||||
|
||||
293
internal/api/auth/handler/impl_test.go
Normal file
293
internal/api/auth/handler/impl_test.go
Normal file
@ -0,0 +1,293 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockAuthService implements service.AuthService
|
||||
type MockAuthService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockAuthService) OtpRequest(ctx context.Context, phoneNumber string) error {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockAuthService) OtpVerify(ctx context.Context, phoneNumber, code string, loginChallenge string) (string, error) {
|
||||
args := m.Called(ctx, phoneNumber, code, loginChallenge)
|
||||
return args.String(0), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockAuthService) AcceptConsent(ctx context.Context, phoneNumber string, challenge string) (string, error) {
|
||||
args := m.Called(ctx, phoneNumber, challenge)
|
||||
return args.String(0), args.Error(1)
|
||||
}
|
||||
|
||||
func TestNewAuthHandler(t *testing.T) {
|
||||
mockService := &MockAuthService{}
|
||||
handler := NewAuthHandler(mockService)
|
||||
|
||||
assert.NotNil(t, handler)
|
||||
assert.Equal(t, mockService, handler.service)
|
||||
assert.Implements(t, (*StrictServerInterface)(nil), handler)
|
||||
}
|
||||
|
||||
func TestAuthHandler_PostAuthOtpRequest(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
setupMock func(*MockAuthService)
|
||||
expectedStatus int
|
||||
expectedOk bool
|
||||
expectedMsg string
|
||||
}{
|
||||
{
|
||||
name: "successful otp request",
|
||||
phoneNumber: "+79161234567",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("OtpRequest", mock.Anything, "+79161234567").Return(nil).Once()
|
||||
},
|
||||
expectedStatus: 200,
|
||||
expectedOk: true,
|
||||
expectedMsg: "OTP request successful",
|
||||
},
|
||||
{
|
||||
name: "service error",
|
||||
phoneNumber: "invalid",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("OtpRequest", mock.Anything, "invalid").Return(assert.AnError).Once()
|
||||
},
|
||||
expectedStatus: 400,
|
||||
expectedOk: false,
|
||||
expectedMsg: assert.AnError.Error(),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockService := &MockAuthService{}
|
||||
handler := &AuthHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
tt.setupMock(mockService)
|
||||
|
||||
request := PostAuthOtpRequestRequestObject{
|
||||
Body: &PostAuthOtpRequestJSONRequestBody{
|
||||
PhoneNumber: tt.phoneNumber,
|
||||
},
|
||||
}
|
||||
|
||||
result, err := handler.PostAuthOtpRequest(ctx, request)
|
||||
|
||||
assert.NoError(t, err) // Handler should not return errors, only response objects
|
||||
|
||||
if tt.expectedStatus == 200 {
|
||||
response, ok := result.(PostAuthOtpRequest200JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
} else {
|
||||
response, ok := result.(PostAuthOtpRequest400JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
}
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthHandler_PostAuthOtpVerify(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
otp string
|
||||
loginChallenge string
|
||||
setupMock func(*MockAuthService)
|
||||
expectedStatus int
|
||||
expectedOk bool
|
||||
expectedMsg string
|
||||
expectedRedirect string
|
||||
}{
|
||||
{
|
||||
name: "successful otp verification",
|
||||
phoneNumber: "+79161234567",
|
||||
otp: "123456",
|
||||
loginChallenge: "challenge123",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("OtpVerify", mock.Anything, "+79161234567", "123456", "challenge123").
|
||||
Return("https://example.com/callback", nil).Once()
|
||||
},
|
||||
expectedStatus: 200,
|
||||
expectedOk: true,
|
||||
expectedMsg: "OTP verification successful",
|
||||
expectedRedirect: "https://example.com/callback",
|
||||
},
|
||||
{
|
||||
name: "service error",
|
||||
phoneNumber: "+79161234567",
|
||||
otp: "wrong",
|
||||
loginChallenge: "challenge123",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("OtpVerify", mock.Anything, "+79161234567", "wrong", "challenge123").
|
||||
Return("", assert.AnError).Once()
|
||||
},
|
||||
expectedStatus: 400,
|
||||
expectedOk: false,
|
||||
expectedMsg: assert.AnError.Error(),
|
||||
expectedRedirect: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockService := &MockAuthService{}
|
||||
handler := &AuthHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
tt.setupMock(mockService)
|
||||
|
||||
request := PostAuthOtpVerifyRequestObject{
|
||||
Body: &PostAuthOtpVerifyJSONRequestBody{
|
||||
PhoneNumber: tt.phoneNumber,
|
||||
Otp: tt.otp,
|
||||
LoginChallenge: tt.loginChallenge,
|
||||
},
|
||||
}
|
||||
|
||||
result, err := handler.PostAuthOtpVerify(ctx, request)
|
||||
|
||||
assert.NoError(t, err)
|
||||
|
||||
if tt.expectedStatus == 200 {
|
||||
response, ok := result.(PostAuthOtpVerify200JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
assert.Equal(t, tt.expectedRedirect, response.RedirectUrl)
|
||||
} else {
|
||||
response, ok := result.(PostAuthOtpVerify400JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
assert.Equal(t, tt.expectedRedirect, response.RedirectUrl)
|
||||
}
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthHandler_PostAuthConsentAccept(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
consentChallenge string
|
||||
setupMock func(*MockAuthService)
|
||||
expectedStatus int
|
||||
expectedOk bool
|
||||
expectedMsg string
|
||||
expectedRedirect string
|
||||
}{
|
||||
{
|
||||
name: "successful consent accept",
|
||||
phoneNumber: "+79161234567",
|
||||
consentChallenge: "consent123",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("AcceptConsent", mock.Anything, "+79161234567", "consent123").
|
||||
Return("https://example.com/callback", nil).Once()
|
||||
},
|
||||
expectedStatus: 200,
|
||||
expectedOk: true,
|
||||
expectedMsg: "Consent accepted successfully",
|
||||
expectedRedirect: "https://example.com/callback",
|
||||
},
|
||||
{
|
||||
name: "service error",
|
||||
phoneNumber: "+79161234567",
|
||||
consentChallenge: "invalid",
|
||||
setupMock: func(m *MockAuthService) {
|
||||
m.On("AcceptConsent", mock.Anything, "+79161234567", "invalid").
|
||||
Return("", assert.AnError).Once()
|
||||
},
|
||||
expectedStatus: 400,
|
||||
expectedOk: false,
|
||||
expectedMsg: assert.AnError.Error(),
|
||||
expectedRedirect: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockService := &MockAuthService{}
|
||||
handler := &AuthHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
tt.setupMock(mockService)
|
||||
|
||||
request := PostAuthConsentAcceptRequestObject{
|
||||
Body: &PostAuthConsentAcceptJSONRequestBody{
|
||||
PhoneNumber: tt.phoneNumber,
|
||||
ConsentChallenge: tt.consentChallenge,
|
||||
},
|
||||
}
|
||||
|
||||
result, err := handler.PostAuthConsentAccept(ctx, request)
|
||||
|
||||
assert.NoError(t, err)
|
||||
|
||||
if tt.expectedStatus == 200 {
|
||||
response, ok := result.(PostAuthConsentAccept200JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
assert.Equal(t, tt.expectedRedirect, response.RedirectUrl)
|
||||
} else {
|
||||
response, ok := result.(PostAuthConsentAccept400JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, tt.expectedOk, response.Ok)
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
assert.Equal(t, tt.expectedRedirect, response.RedirectUrl)
|
||||
}
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthHandler_EdgeCases(t *testing.T) {
|
||||
t.Run("nil request body should not panic", func(t *testing.T) {
|
||||
mockService := &MockAuthService{}
|
||||
handler := &AuthHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
// Test with nil body - this should be handled by the generated code
|
||||
// but we test that our handler doesn't panic
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Errorf("Handler panicked with nil body: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
request := PostAuthOtpRequestRequestObject{
|
||||
Body: &PostAuthOtpRequestJSONRequestBody{
|
||||
PhoneNumber: "",
|
||||
},
|
||||
}
|
||||
|
||||
mockService.On("OtpRequest", mock.Anything, "").Return(assert.AnError).Once()
|
||||
|
||||
result, err := handler.PostAuthOtpRequest(ctx, request)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
45
internal/api/auth/repo/auth_repo.go
Normal file
45
internal/api/auth/repo/auth_repo.go
Normal file
@ -0,0 +1,45 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/domain"
|
||||
"github.com/redis/rueidis"
|
||||
)
|
||||
|
||||
type authRepo struct {
|
||||
redisClient rueidis.Client
|
||||
}
|
||||
|
||||
func (a authRepo) GetOtpRequest(ctx context.Context, uuid string) (*string, error) {
|
||||
redisClient := a.redisClient
|
||||
|
||||
resp, err := redisClient.Do(ctx, redisClient.B().Get().Key("otp:"+uuid).Build()).ToString()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp == "" {
|
||||
// create error
|
||||
return nil, &domain.ErrOtpNotFound{Uuid: uuid}
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (a authRepo) SaveOtpRequest(ctx context.Context, uuid string, code string) error {
|
||||
redisClient := a.redisClient
|
||||
|
||||
err := redisClient.Do(ctx, redisClient.B().Set().Key("otp:"+uuid).Value(code).Ex(120*time.Second).Build()).Error()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func NewAuthRepo(redisClient rueidis.Client) domain.AuthRepository {
|
||||
return &authRepo{redisClient: redisClient}
|
||||
}
|
||||
34
internal/api/auth/repo/auth_repo_test.go
Normal file
34
internal/api/auth/repo/auth_repo_test.go
Normal file
@ -0,0 +1,34 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/domain"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewAuthRepo(t *testing.T) {
|
||||
// Test with nil client for interface testing
|
||||
// In real tests, you would use a mock or test container
|
||||
repo := NewAuthRepo(nil)
|
||||
|
||||
assert.NotNil(t, repo)
|
||||
assert.Implements(t, (*domain.AuthRepository)(nil), repo)
|
||||
}
|
||||
|
||||
func TestAuthRepo_Interface(t *testing.T) {
|
||||
// Test that our auth repo implements the domain interface
|
||||
var _ domain.AuthRepository = (*authRepo)(nil)
|
||||
|
||||
// Test constructor returns correct interface
|
||||
repo := NewAuthRepo(nil)
|
||||
|
||||
// Verify interface compliance
|
||||
assert.Implements(t, (*domain.AuthRepository)(nil), repo)
|
||||
}
|
||||
|
||||
// Note: Actual Redis operations testing requires either:
|
||||
// 1. Test containers with real Redis
|
||||
// 2. A simpler interface wrapper around Redis
|
||||
// 3. A Redis mock library specifically designed for rueidis
|
||||
// For now, we focus on interface compliance and constructor behavior
|
||||
191
internal/api/auth/service/auth_service.go
Normal file
191
internal/api/auth/service/auth_service.go
Normal file
@ -0,0 +1,191 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/domain"
|
||||
userDomain "git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
userService "git.logidex.ru/fakz9/logidex-id/internal/api/user/service"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/phoneutil"
|
||||
hydraApi "github.com/ory/hydra-client-go"
|
||||
)
|
||||
|
||||
type AuthService interface {
|
||||
OtpRequest(ctx context.Context, phoneNumber string) error
|
||||
OtpVerify(ctx context.Context, phoneNumber, code string, loggingChallenge string) (string, error)
|
||||
AcceptConsent(ctx context.Context, phoneNumber string, challenge string) (string, error)
|
||||
}
|
||||
|
||||
type authService struct {
|
||||
repo domain.AuthRepository
|
||||
userService userService.UserService
|
||||
hydraClient *hydraApi.APIClient
|
||||
}
|
||||
|
||||
func (a authService) validateAndFormatPhoneNumber(phoneNumber string) (string, error) {
|
||||
formattedPhone, err := phoneutil.ParseAndFormatPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
return "", domain.ErrInvalidPhoneNumber{
|
||||
PhoneNumber: phoneNumber,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return formattedPhone, nil
|
||||
}
|
||||
|
||||
func (a authService) getUserByPhoneNumber(ctx context.Context, phoneNumber string) (*userDomain.User, error) {
|
||||
user, err := a.userService.GetUserByPhoneNumber(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user == nil {
|
||||
return nil, domain.ErrUserNotFound{PhoneNumber: phoneNumber}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (a authService) getOrCreateUser(ctx context.Context, phoneNumber string) (*userDomain.User, error) {
|
||||
user, err := a.userService.GetUserByPhoneNumber(ctx, phoneNumber)
|
||||
if user == nil {
|
||||
user, err = a.userService.CreateUser(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (a authService) validateHydraResponse(rawRsp *http.Response, userUuid string) error {
|
||||
if rawRsp.StatusCode != 200 {
|
||||
return domain.ErrInvalidHydraAccept{
|
||||
Message: "Hydra response status: " + strconv.Itoa(rawRsp.StatusCode),
|
||||
Uuid: userUuid,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a authService) extractRedirectUrl(rsp interface{ GetRedirectToOk() (*string, bool) }, userUuid string) (string, error) {
|
||||
redirectTo, ok := rsp.GetRedirectToOk()
|
||||
if !ok || redirectTo == nil {
|
||||
return "", domain.ErrInvalidHydraAccept{
|
||||
Message: "Hydra redirectTo is nil",
|
||||
Uuid: userUuid,
|
||||
}
|
||||
}
|
||||
return *redirectTo, nil
|
||||
}
|
||||
|
||||
func (a authService) AcceptConsent(ctx context.Context, phoneNumber string, challenge string) (string, error) {
|
||||
phoneNumber, err := a.validateAndFormatPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
user, err := a.getUserByPhoneNumber(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
request := hydraApi.AcceptConsentRequest{}
|
||||
request.SetGrantScope([]string{"openid", "offline", "offline_access"})
|
||||
request.SetRemember(true)
|
||||
request.SetRememberFor(3600)
|
||||
|
||||
rsp, rawRsp, err := a.hydraClient.AdminApi.
|
||||
AcceptConsentRequest(ctx).
|
||||
ConsentChallenge(challenge).
|
||||
AcceptConsentRequest(request).
|
||||
Execute()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = a.validateHydraResponse(rawRsp, user.Uuid); err != nil {
|
||||
return "", err
|
||||
}
|
||||
redirectUrl, err := a.extractRedirectUrl(rsp, user.Uuid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// TODO: Verify user in the database
|
||||
_, err = a.userService.VerifyUser(ctx, user.Uuid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return redirectUrl, nil
|
||||
}
|
||||
|
||||
func (a authService) OtpRequest(ctx context.Context, phoneNumber string) error {
|
||||
phoneNumber, err := a.validateAndFormatPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user, err := a.getOrCreateUser(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
code := "123456"
|
||||
err = a.repo.SaveOtpRequest(ctx, user.Uuid, code)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// TODO implement sending OTP code via SMS
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a authService) OtpVerify(ctx context.Context, phoneNumber string, code string, loggingChallenge string) (string, error) {
|
||||
phoneNumber, err := a.validateAndFormatPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
user, err := a.getUserByPhoneNumber(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
otp, err := a.repo.GetOtpRequest(ctx, user.Uuid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if otp == nil {
|
||||
return "", domain.ErrOtpNotFound{Uuid: user.Uuid}
|
||||
}
|
||||
if *otp != code {
|
||||
return "", domain.ErrOtpInvalid{Uuid: user.Uuid, Code: code}
|
||||
}
|
||||
|
||||
request := hydraApi.AcceptLoginRequest{}
|
||||
request.SetSubject(user.Uuid)
|
||||
request.SetRemember(true)
|
||||
request.SetRememberFor(3600) // 1 hour
|
||||
|
||||
rsp, rawRsp, err := a.hydraClient.AdminApi.
|
||||
AcceptLoginRequest(ctx).
|
||||
LoginChallenge(loggingChallenge).
|
||||
AcceptLoginRequest(request).
|
||||
Execute()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = a.validateHydraResponse(rawRsp, user.Uuid); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
redirectUrl, err := a.extractRedirectUrl(rsp, user.Uuid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return redirectUrl, nil
|
||||
}
|
||||
|
||||
func NewAuthService(repo domain.AuthRepository, userService userService.UserService, hydraClient *hydraApi.APIClient) AuthService {
|
||||
return &authService{
|
||||
repo: repo,
|
||||
userService: userService,
|
||||
hydraClient: hydraClient,
|
||||
}
|
||||
}
|
||||
429
internal/api/auth/service/auth_service_test.go
Normal file
429
internal/api/auth/service/auth_service_test.go
Normal file
@ -0,0 +1,429 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/auth/domain"
|
||||
userDomain "git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
hydraApi "github.com/ory/hydra-client-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockAuthRepository implements domain.AuthRepository
|
||||
type MockAuthRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockAuthRepository) SaveOtpRequest(ctx context.Context, uuid string, code string) error {
|
||||
args := m.Called(ctx, uuid, code)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockAuthRepository) GetOtpRequest(ctx context.Context, uuid string) (*string, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*string), args.Error(1)
|
||||
}
|
||||
|
||||
// MockUserService implements userService.UserService
|
||||
type MockUserService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockUserService) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*userDomain.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*userDomain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) GetUserByUuid(ctx context.Context, uuid string) (*userDomain.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*userDomain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) CreateUser(ctx context.Context, phoneNumber string) (*userDomain.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*userDomain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) VerifyUser(ctx context.Context, uuid string) (*userDomain.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*userDomain.User), args.Error(1)
|
||||
}
|
||||
|
||||
// MockHydraResponse implements hydra response interface
|
||||
type MockHydraResponse struct {
|
||||
redirectTo *string
|
||||
}
|
||||
|
||||
func (m *MockHydraResponse) GetRedirectToOk() (*string, bool) {
|
||||
if m.redirectTo == nil {
|
||||
return nil, false
|
||||
}
|
||||
return m.redirectTo, true
|
||||
}
|
||||
|
||||
func TestNewAuthService(t *testing.T) {
|
||||
mockRepo := &MockAuthRepository{}
|
||||
mockUserService := &MockUserService{}
|
||||
mockHydraClient := &hydraApi.APIClient{}
|
||||
|
||||
service := NewAuthService(mockRepo, mockUserService, mockHydraClient)
|
||||
|
||||
assert.NotNil(t, service)
|
||||
assert.Implements(t, (*AuthService)(nil), service)
|
||||
}
|
||||
|
||||
func TestAuthService_getUserByPhoneNumber(t *testing.T) {
|
||||
mockUserService := &MockUserService{}
|
||||
service := &authService{userService: mockUserService}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "+79161234567"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *userDomain.User
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "user found",
|
||||
setupMock: func() {
|
||||
user := &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(user, nil).Once()
|
||||
},
|
||||
expectedUser: &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "user not found",
|
||||
setupMock: func() {
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, nil).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
errType: domain.ErrUserNotFound{},
|
||||
},
|
||||
{
|
||||
name: "service error",
|
||||
setupMock: func() {
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.getUserByPhoneNumber(ctx, phoneNumber)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockUserService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthService_getOrCreateUser(t *testing.T) {
|
||||
mockUserService := &MockUserService{}
|
||||
service := &authService{userService: mockUserService}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "+79161234567"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *userDomain.User
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "existing user found",
|
||||
setupMock: func() {
|
||||
user := &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(user, nil).Once()
|
||||
},
|
||||
expectedUser: &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "user not found, create new",
|
||||
setupMock: func() {
|
||||
newUser := &userDomain.User{
|
||||
Uuid: "new-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, nil).Once()
|
||||
mockUserService.On("CreateUser", ctx, phoneNumber).Return(newUser, nil).Once()
|
||||
},
|
||||
expectedUser: &userDomain.User{
|
||||
Uuid: "new-uuid",
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "get user service error",
|
||||
setupMock: func() {
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "create user service error",
|
||||
setupMock: func() {
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, nil).Once()
|
||||
mockUserService.On("CreateUser", ctx, phoneNumber).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.getOrCreateUser(ctx, phoneNumber)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockUserService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthService_validateHydraResponse(t *testing.T) {
|
||||
service := &authService{}
|
||||
userUuid := "test-uuid"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
statusCode int
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "success status",
|
||||
statusCode: 200,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "bad request status",
|
||||
statusCode: 400,
|
||||
wantErr: true,
|
||||
errType: domain.ErrInvalidHydraAccept{},
|
||||
},
|
||||
{
|
||||
name: "internal server error status",
|
||||
statusCode: 500,
|
||||
wantErr: true,
|
||||
errType: domain.ErrInvalidHydraAccept{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resp := &http.Response{StatusCode: tt.statusCode}
|
||||
|
||||
err := service.validateHydraResponse(resp, userUuid)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthService_extractRedirectUrl(t *testing.T) {
|
||||
service := &authService{}
|
||||
userUuid := "test-uuid"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
response *MockHydraResponse
|
||||
expectedUrl string
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "valid redirect url",
|
||||
response: &MockHydraResponse{
|
||||
redirectTo: stringPtr("https://example.com/callback"),
|
||||
},
|
||||
expectedUrl: "https://example.com/callback",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "nil redirect url",
|
||||
response: &MockHydraResponse{
|
||||
redirectTo: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
errType: domain.ErrInvalidHydraAccept{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.extractRedirectUrl(tt.response, userUuid)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Empty(t, result)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUrl, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthService_OtpRequest(t *testing.T) {
|
||||
mockRepo := &MockAuthRepository{}
|
||||
mockUserService := &MockUserService{}
|
||||
service := &authService{
|
||||
repo: mockRepo,
|
||||
userService: mockUserService,
|
||||
}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "89161234567" // will be formatted to +79161234567
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "success - existing user",
|
||||
setupMock: func() {
|
||||
user := &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: "+79161234567",
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, "+79161234567").Return(user, nil).Once()
|
||||
mockRepo.On("SaveOtpRequest", ctx, "test-uuid", "123456").Return(nil).Once()
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "success - create new user",
|
||||
setupMock: func() {
|
||||
newUser := &userDomain.User{
|
||||
Uuid: "new-uuid",
|
||||
PhoneNumber: "+79161234567",
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, "+79161234567").Return(nil, nil).Once()
|
||||
mockUserService.On("CreateUser", ctx, "+79161234567").Return(newUser, nil).Once()
|
||||
mockRepo.On("SaveOtpRequest", ctx, "new-uuid", "123456").Return(nil).Once()
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid phone number",
|
||||
setupMock: func() {
|
||||
// No mock setup needed for invalid phone
|
||||
},
|
||||
wantErr: true,
|
||||
errType: domain.ErrInvalidPhoneNumber{},
|
||||
},
|
||||
{
|
||||
name: "repo save error",
|
||||
setupMock: func() {
|
||||
user := &userDomain.User{
|
||||
Uuid: "test-uuid",
|
||||
PhoneNumber: "+79161234567",
|
||||
}
|
||||
mockUserService.On("GetUserByPhoneNumber", ctx, "+79161234567").Return(user, nil).Once()
|
||||
mockRepo.On("SaveOtpRequest", ctx, "test-uuid", "123456").Return(assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mocks
|
||||
mockRepo.ExpectedCalls = nil
|
||||
mockUserService.ExpectedCalls = nil
|
||||
|
||||
tt.setupMock()
|
||||
|
||||
testPhone := phoneNumber
|
||||
if tt.name == "invalid phone number" {
|
||||
testPhone = "invalid"
|
||||
}
|
||||
|
||||
err := service.OtpRequest(ctx, testPhone)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
mockUserService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to create string pointer
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
27
internal/api/user/domain/user_domain.go
Normal file
27
internal/api/user/domain/user_domain.go
Normal file
@ -0,0 +1,27 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
db "git.logidex.ru/fakz9/logidex-id/internal/db/generated"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Uuid string `json:"uuid"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
}
|
||||
|
||||
type UserRepository interface {
|
||||
GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*db.User, error)
|
||||
GetUserByUuid(ctx context.Context, uuid string) (*db.User, error)
|
||||
CreateUser(ctx context.Context, phoneNumber string) (*db.User, error)
|
||||
VerifyUser(ctx context.Context, uuid string) (*db.User, error)
|
||||
}
|
||||
|
||||
type ErrUserNotFound struct {
|
||||
PhoneNumber string
|
||||
}
|
||||
|
||||
func (e ErrUserNotFound) Error() string {
|
||||
return "User not found with phone number: " + e.PhoneNumber
|
||||
}
|
||||
53
internal/api/user/domain/user_domain_test.go
Normal file
53
internal/api/user/domain/user_domain_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUser_Structure(t *testing.T) {
|
||||
user := User{
|
||||
Uuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
PhoneNumber: "+1234567890",
|
||||
}
|
||||
|
||||
assert.Equal(t, "123e4567-e89b-12d3-a456-426614174000", user.Uuid)
|
||||
assert.Equal(t, "+1234567890", user.PhoneNumber)
|
||||
}
|
||||
|
||||
func TestErrUserNotFound_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "returns formatted error message",
|
||||
phoneNumber: "+1234567890",
|
||||
want: "User not found with phone number: +1234567890",
|
||||
},
|
||||
{
|
||||
name: "handles empty phone number",
|
||||
phoneNumber: "",
|
||||
want: "User not found with phone number: ",
|
||||
},
|
||||
{
|
||||
name: "handles international phone number",
|
||||
phoneNumber: "+44123456789",
|
||||
want: "User not found with phone number: +44123456789",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ErrUserNotFound{PhoneNumber: tt.phoneNumber}
|
||||
assert.Equal(t, tt.want, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrUserNotFound_IsError(t *testing.T) {
|
||||
err := ErrUserNotFound{PhoneNumber: "+1234567890"}
|
||||
assert.Implements(t, (*error)(nil), err)
|
||||
}
|
||||
20
internal/api/user/fx.go
Normal file
20
internal/api/user/fx.go
Normal file
@ -0,0 +1,20 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/handler"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/repo"
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/service"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
var Module = fx.Options(
|
||||
fx.Provide(
|
||||
repo.NewUserRepo,
|
||||
service.NewUserService,
|
||||
handler.NewUserHandler,
|
||||
),
|
||||
fx.Invoke(func(handler *handler.UserHandler, router fiber.Router) {
|
||||
handler.RegisterRoutes(router)
|
||||
}),
|
||||
)
|
||||
@ -9,52 +9,30 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/oapi-codegen/runtime"
|
||||
openapi_types "github.com/oapi-codegen/runtime/types"
|
||||
)
|
||||
|
||||
// User defines model for User.
|
||||
type User struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
Id string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Uuid string `json:"uuid"`
|
||||
}
|
||||
|
||||
// UserCreate defines model for UserCreate.
|
||||
type UserCreate struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
}
|
||||
|
||||
// UserUpdate defines model for UserUpdate.
|
||||
type UserUpdate struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// PostUsersJSONRequestBody defines body for PostUsers for application/json ContentType.
|
||||
type PostUsersJSONRequestBody = UserCreate
|
||||
|
||||
// PutUsersUserIdJSONRequestBody defines body for PutUsersUserId for application/json ContentType.
|
||||
type PutUsersUserIdJSONRequestBody = UserUpdate
|
||||
// CreateUserJSONRequestBody defines body for CreateUser for application/json ContentType.
|
||||
type CreateUserJSONRequestBody = UserCreate
|
||||
|
||||
// ServerInterface represents all server handlers.
|
||||
type ServerInterface interface {
|
||||
// Get all users
|
||||
// (GET /users)
|
||||
GetUsers(c *fiber.Ctx) error
|
||||
// Create a new user
|
||||
// Create a new user with phone number
|
||||
// (POST /users)
|
||||
PostUsers(c *fiber.Ctx) error
|
||||
// Delete a user by ID
|
||||
// (DELETE /users/{userId})
|
||||
DeleteUsersUserId(c *fiber.Ctx, userId string) error
|
||||
CreateUser(c *fiber.Ctx) error
|
||||
// Get a user by ID
|
||||
// (GET /users/{userId})
|
||||
GetUsersUserId(c *fiber.Ctx, userId string) error
|
||||
// Update a user by ID
|
||||
// (PUT /users/{userId})
|
||||
PutUsersUserId(c *fiber.Ctx, userId string) error
|
||||
GetUserById(c *fiber.Ctx, userId string) error
|
||||
}
|
||||
|
||||
// ServerInterfaceWrapper converts contexts to parameters.
|
||||
@ -64,20 +42,14 @@ type ServerInterfaceWrapper struct {
|
||||
|
||||
type MiddlewareFunc fiber.Handler
|
||||
|
||||
// GetUsers operation middleware
|
||||
func (siw *ServerInterfaceWrapper) GetUsers(c *fiber.Ctx) error {
|
||||
// CreateUser operation middleware
|
||||
func (siw *ServerInterfaceWrapper) CreateUser(c *fiber.Ctx) error {
|
||||
|
||||
return siw.Handler.GetUsers(c)
|
||||
return siw.Handler.CreateUser(c)
|
||||
}
|
||||
|
||||
// PostUsers operation middleware
|
||||
func (siw *ServerInterfaceWrapper) PostUsers(c *fiber.Ctx) error {
|
||||
|
||||
return siw.Handler.PostUsers(c)
|
||||
}
|
||||
|
||||
// DeleteUsersUserId operation middleware
|
||||
func (siw *ServerInterfaceWrapper) DeleteUsersUserId(c *fiber.Ctx) error {
|
||||
// GetUserById operation middleware
|
||||
func (siw *ServerInterfaceWrapper) GetUserById(c *fiber.Ctx) error {
|
||||
|
||||
var err error
|
||||
|
||||
@ -89,39 +61,7 @@ func (siw *ServerInterfaceWrapper) DeleteUsersUserId(c *fiber.Ctx) error {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter userId: %w", err).Error())
|
||||
}
|
||||
|
||||
return siw.Handler.DeleteUsersUserId(c, userId)
|
||||
}
|
||||
|
||||
// GetUsersUserId operation middleware
|
||||
func (siw *ServerInterfaceWrapper) GetUsersUserId(c *fiber.Ctx) error {
|
||||
|
||||
var err error
|
||||
|
||||
// ------------- Path parameter "userId" -------------
|
||||
var userId string
|
||||
|
||||
err = runtime.BindStyledParameterWithOptions("simple", "userId", c.Params("userId"), &userId, runtime.BindStyledParameterOptions{Explode: false, Required: true})
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter userId: %w", err).Error())
|
||||
}
|
||||
|
||||
return siw.Handler.GetUsersUserId(c, userId)
|
||||
}
|
||||
|
||||
// PutUsersUserId operation middleware
|
||||
func (siw *ServerInterfaceWrapper) PutUsersUserId(c *fiber.Ctx) error {
|
||||
|
||||
var err error
|
||||
|
||||
// ------------- Path parameter "userId" -------------
|
||||
var userId string
|
||||
|
||||
err = runtime.BindStyledParameterWithOptions("simple", "userId", c.Params("userId"), &userId, runtime.BindStyledParameterOptions{Explode: false, Required: true})
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter userId: %w", err).Error())
|
||||
}
|
||||
|
||||
return siw.Handler.PutUsersUserId(c, userId)
|
||||
return siw.Handler.GetUserById(c, userId)
|
||||
}
|
||||
|
||||
// FiberServerOptions provides options for the Fiber server.
|
||||
@ -145,143 +85,67 @@ func RegisterHandlersWithOptions(router fiber.Router, si ServerInterface, option
|
||||
router.Use(fiber.Handler(m))
|
||||
}
|
||||
|
||||
router.Get(options.BaseURL+"/users", wrapper.GetUsers)
|
||||
router.Post(options.BaseURL+"/users", wrapper.CreateUser)
|
||||
|
||||
router.Post(options.BaseURL+"/users", wrapper.PostUsers)
|
||||
|
||||
router.Delete(options.BaseURL+"/users/:userId", wrapper.DeleteUsersUserId)
|
||||
|
||||
router.Get(options.BaseURL+"/users/:userId", wrapper.GetUsersUserId)
|
||||
|
||||
router.Put(options.BaseURL+"/users/:userId", wrapper.PutUsersUserId)
|
||||
router.Get(options.BaseURL+"/users/:userId", wrapper.GetUserById)
|
||||
|
||||
}
|
||||
|
||||
type GetUsersRequestObject struct {
|
||||
type CreateUserRequestObject struct {
|
||||
Body *CreateUserJSONRequestBody
|
||||
}
|
||||
|
||||
type GetUsersResponseObject interface {
|
||||
VisitGetUsersResponse(ctx *fiber.Ctx) error
|
||||
type CreateUserResponseObject interface {
|
||||
VisitCreateUserResponse(ctx *fiber.Ctx) error
|
||||
}
|
||||
|
||||
type GetUsers200JSONResponse []User
|
||||
type CreateUser200JSONResponse User
|
||||
|
||||
func (response GetUsers200JSONResponse) VisitGetUsersResponse(ctx *fiber.Ctx) error {
|
||||
func (response CreateUser200JSONResponse) VisitCreateUserResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Response().Header.Set("Content-Type", "application/json")
|
||||
ctx.Status(200)
|
||||
|
||||
return ctx.JSON(&response)
|
||||
}
|
||||
|
||||
type PostUsersRequestObject struct {
|
||||
Body *PostUsersJSONRequestBody
|
||||
}
|
||||
|
||||
type PostUsersResponseObject interface {
|
||||
VisitPostUsersResponse(ctx *fiber.Ctx) error
|
||||
}
|
||||
|
||||
type PostUsers201JSONResponse User
|
||||
|
||||
func (response PostUsers201JSONResponse) VisitPostUsersResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Response().Header.Set("Content-Type", "application/json")
|
||||
ctx.Status(201)
|
||||
|
||||
return ctx.JSON(&response)
|
||||
}
|
||||
|
||||
type DeleteUsersUserIdRequestObject struct {
|
||||
type GetUserByIdRequestObject struct {
|
||||
UserId string `json:"userId"`
|
||||
}
|
||||
|
||||
type DeleteUsersUserIdResponseObject interface {
|
||||
VisitDeleteUsersUserIdResponse(ctx *fiber.Ctx) error
|
||||
type GetUserByIdResponseObject interface {
|
||||
VisitGetUserByIdResponse(ctx *fiber.Ctx) error
|
||||
}
|
||||
|
||||
type DeleteUsersUserId204Response struct {
|
||||
type GetUserById200JSONResponse struct {
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
func (response DeleteUsersUserId204Response) VisitDeleteUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Status(204)
|
||||
return nil
|
||||
}
|
||||
|
||||
type DeleteUsersUserId404Response struct {
|
||||
}
|
||||
|
||||
func (response DeleteUsersUserId404Response) VisitDeleteUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Status(404)
|
||||
return nil
|
||||
}
|
||||
|
||||
type GetUsersUserIdRequestObject struct {
|
||||
UserId string `json:"userId"`
|
||||
}
|
||||
|
||||
type GetUsersUserIdResponseObject interface {
|
||||
VisitGetUsersUserIdResponse(ctx *fiber.Ctx) error
|
||||
}
|
||||
|
||||
type GetUsersUserId200JSONResponse User
|
||||
|
||||
func (response GetUsersUserId200JSONResponse) VisitGetUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
func (response GetUserById200JSONResponse) VisitGetUserByIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Response().Header.Set("Content-Type", "application/json")
|
||||
ctx.Status(200)
|
||||
|
||||
return ctx.JSON(&response)
|
||||
}
|
||||
|
||||
type GetUsersUserId404Response struct {
|
||||
type GetUserById404JSONResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (response GetUsersUserId404Response) VisitGetUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Status(404)
|
||||
return nil
|
||||
}
|
||||
|
||||
type PutUsersUserIdRequestObject struct {
|
||||
UserId string `json:"userId"`
|
||||
Body *PutUsersUserIdJSONRequestBody
|
||||
}
|
||||
|
||||
type PutUsersUserIdResponseObject interface {
|
||||
VisitPutUsersUserIdResponse(ctx *fiber.Ctx) error
|
||||
}
|
||||
|
||||
type PutUsersUserId200JSONResponse User
|
||||
|
||||
func (response PutUsersUserId200JSONResponse) VisitPutUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
func (response GetUserById404JSONResponse) VisitGetUserByIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Response().Header.Set("Content-Type", "application/json")
|
||||
ctx.Status(200)
|
||||
ctx.Status(404)
|
||||
|
||||
return ctx.JSON(&response)
|
||||
}
|
||||
|
||||
type PutUsersUserId404Response struct {
|
||||
}
|
||||
|
||||
func (response PutUsersUserId404Response) VisitPutUsersUserIdResponse(ctx *fiber.Ctx) error {
|
||||
ctx.Status(404)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StrictServerInterface represents all server handlers.
|
||||
type StrictServerInterface interface {
|
||||
// Get all users
|
||||
// (GET /users)
|
||||
GetUsers(ctx context.Context, request GetUsersRequestObject) (GetUsersResponseObject, error)
|
||||
// Create a new user
|
||||
// Create a new user with phone number
|
||||
// (POST /users)
|
||||
PostUsers(ctx context.Context, request PostUsersRequestObject) (PostUsersResponseObject, error)
|
||||
// Delete a user by ID
|
||||
// (DELETE /users/{userId})
|
||||
DeleteUsersUserId(ctx context.Context, request DeleteUsersUserIdRequestObject) (DeleteUsersUserIdResponseObject, error)
|
||||
CreateUser(ctx context.Context, request CreateUserRequestObject) (CreateUserResponseObject, error)
|
||||
// Get a user by ID
|
||||
// (GET /users/{userId})
|
||||
GetUsersUserId(ctx context.Context, request GetUsersUserIdRequestObject) (GetUsersUserIdResponseObject, error)
|
||||
// Update a user by ID
|
||||
// (PUT /users/{userId})
|
||||
PutUsersUserId(ctx context.Context, request PutUsersUserIdRequestObject) (PutUsersUserIdResponseObject, error)
|
||||
GetUserById(ctx context.Context, request GetUserByIdRequestObject) (GetUserByIdResponseObject, error)
|
||||
}
|
||||
|
||||
type StrictHandlerFunc func(ctx *fiber.Ctx, args interface{}) (interface{}, error)
|
||||
@ -297,54 +161,29 @@ type strictHandler struct {
|
||||
middlewares []StrictMiddlewareFunc
|
||||
}
|
||||
|
||||
// GetUsers operation middleware
|
||||
func (sh *strictHandler) GetUsers(ctx *fiber.Ctx) error {
|
||||
var request GetUsersRequestObject
|
||||
// CreateUser operation middleware
|
||||
func (sh *strictHandler) CreateUser(ctx *fiber.Ctx) error {
|
||||
var request CreateUserRequestObject
|
||||
|
||||
handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) {
|
||||
return sh.ssi.GetUsers(ctx.UserContext(), request.(GetUsersRequestObject))
|
||||
}
|
||||
for _, middleware := range sh.middlewares {
|
||||
handler = middleware(handler, "GetUsers")
|
||||
}
|
||||
|
||||
response, err := handler(ctx, request)
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if validResponse, ok := response.(GetUsersResponseObject); ok {
|
||||
if err := validResponse.VisitGetUsersResponse(ctx); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
} else if response != nil {
|
||||
return fmt.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PostUsers operation middleware
|
||||
func (sh *strictHandler) PostUsers(ctx *fiber.Ctx) error {
|
||||
var request PostUsersRequestObject
|
||||
|
||||
var body PostUsersJSONRequestBody
|
||||
var body CreateUserJSONRequestBody
|
||||
if err := ctx.BodyParser(&body); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
request.Body = &body
|
||||
|
||||
handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) {
|
||||
return sh.ssi.PostUsers(ctx.UserContext(), request.(PostUsersRequestObject))
|
||||
return sh.ssi.CreateUser(ctx.UserContext(), request.(CreateUserRequestObject))
|
||||
}
|
||||
for _, middleware := range sh.middlewares {
|
||||
handler = middleware(handler, "PostUsers")
|
||||
handler = middleware(handler, "CreateUser")
|
||||
}
|
||||
|
||||
response, err := handler(ctx, request)
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if validResponse, ok := response.(PostUsersResponseObject); ok {
|
||||
if err := validResponse.VisitPostUsersResponse(ctx); err != nil {
|
||||
} else if validResponse, ok := response.(CreateUserResponseObject); ok {
|
||||
if err := validResponse.VisitCreateUserResponse(ctx); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
} else if response != nil {
|
||||
@ -353,85 +192,25 @@ func (sh *strictHandler) PostUsers(ctx *fiber.Ctx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUsersUserId operation middleware
|
||||
func (sh *strictHandler) DeleteUsersUserId(ctx *fiber.Ctx, userId string) error {
|
||||
var request DeleteUsersUserIdRequestObject
|
||||
// GetUserById operation middleware
|
||||
func (sh *strictHandler) GetUserById(ctx *fiber.Ctx, userId string) error {
|
||||
var request GetUserByIdRequestObject
|
||||
|
||||
request.UserId = userId
|
||||
|
||||
handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) {
|
||||
return sh.ssi.DeleteUsersUserId(ctx.UserContext(), request.(DeleteUsersUserIdRequestObject))
|
||||
return sh.ssi.GetUserById(ctx.UserContext(), request.(GetUserByIdRequestObject))
|
||||
}
|
||||
for _, middleware := range sh.middlewares {
|
||||
handler = middleware(handler, "DeleteUsersUserId")
|
||||
handler = middleware(handler, "GetUserById")
|
||||
}
|
||||
|
||||
response, err := handler(ctx, request)
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if validResponse, ok := response.(DeleteUsersUserIdResponseObject); ok {
|
||||
if err := validResponse.VisitDeleteUsersUserIdResponse(ctx); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
} else if response != nil {
|
||||
return fmt.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsersUserId operation middleware
|
||||
func (sh *strictHandler) GetUsersUserId(ctx *fiber.Ctx, userId string) error {
|
||||
var request GetUsersUserIdRequestObject
|
||||
|
||||
request.UserId = userId
|
||||
|
||||
handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) {
|
||||
return sh.ssi.GetUsersUserId(ctx.UserContext(), request.(GetUsersUserIdRequestObject))
|
||||
}
|
||||
for _, middleware := range sh.middlewares {
|
||||
handler = middleware(handler, "GetUsersUserId")
|
||||
}
|
||||
|
||||
response, err := handler(ctx, request)
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if validResponse, ok := response.(GetUsersUserIdResponseObject); ok {
|
||||
if err := validResponse.VisitGetUsersUserIdResponse(ctx); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
} else if response != nil {
|
||||
return fmt.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PutUsersUserId operation middleware
|
||||
func (sh *strictHandler) PutUsersUserId(ctx *fiber.Ctx, userId string) error {
|
||||
var request PutUsersUserIdRequestObject
|
||||
|
||||
request.UserId = userId
|
||||
|
||||
var body PutUsersUserIdJSONRequestBody
|
||||
if err := ctx.BodyParser(&body); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
request.Body = &body
|
||||
|
||||
handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) {
|
||||
return sh.ssi.PutUsersUserId(ctx.UserContext(), request.(PutUsersUserIdRequestObject))
|
||||
}
|
||||
for _, middleware := range sh.middlewares {
|
||||
handler = middleware(handler, "PutUsersUserId")
|
||||
}
|
||||
|
||||
response, err := handler(ctx, request)
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if validResponse, ok := response.(PutUsersUserIdResponseObject); ok {
|
||||
if err := validResponse.VisitPutUsersUserIdResponse(ctx); err != nil {
|
||||
} else if validResponse, ok := response.(GetUserByIdResponseObject); ok {
|
||||
if err := validResponse.VisitGetUserByIdResponse(ctx); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
} else if response != nil {
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
package handler
|
||||
|
||||
//go:generate go tool oapi-codegen -config ../../../../api/user/cfg.yaml ../../../../api/user/user.yaml
|
||||
//go:generate go tool oapi-codegen -config ../../../../api/user/cfg.yaml ../../../../api/user/api.yaml
|
||||
|
||||
@ -2,46 +2,45 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/service"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/jinzhu/copier"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
service service.UserService
|
||||
}
|
||||
|
||||
func (h UserHandler) CreateUser(ctx context.Context, request CreateUserRequestObject) (CreateUserResponseObject, error) {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (h UserHandler) GetUserById(ctx context.Context, request GetUserByIdRequestObject) (GetUserByIdResponseObject, error) {
|
||||
user, err := h.service.GetUserByUuid(ctx, request.UserId)
|
||||
if err != nil {
|
||||
return GetUserById404JSONResponse{
|
||||
Message: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
var responseUser User
|
||||
err = copier.Copy(&responseUser, user)
|
||||
if err != nil {
|
||||
return GetUserById404JSONResponse{Message: err.Error()}, nil
|
||||
}
|
||||
return GetUserById200JSONResponse{User: responseUser}, nil
|
||||
}
|
||||
|
||||
var _ StrictServerInterface = (*UserHandler)(nil)
|
||||
|
||||
func (u UserHandler) GetUsers(ctx context.Context, request GetUsersRequestObject) (GetUsersResponseObject, error) {
|
||||
var response = make([]User, 0)
|
||||
|
||||
return GetUsers200JSONResponse(response), nil
|
||||
func NewUserHandler(
|
||||
service service.UserService,
|
||||
) *UserHandler {
|
||||
return &UserHandler{service: service}
|
||||
}
|
||||
|
||||
func (u UserHandler) PostUsers(ctx context.Context, request PostUsersRequestObject) (PostUsersResponseObject, error) {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (u UserHandler) DeleteUsersUserId(ctx context.Context, request DeleteUsersUserIdRequestObject) (DeleteUsersUserIdResponseObject, error) {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (u UserHandler) GetUsersUserId(ctx context.Context, request GetUsersUserIdRequestObject) (GetUsersUserIdResponseObject, error) {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (u UserHandler) PutUsersUserId(ctx context.Context, request PutUsersUserIdRequestObject) (PutUsersUserIdResponseObject, error) {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func NewUserHandler() *UserHandler {
|
||||
return &UserHandler{}
|
||||
}
|
||||
|
||||
func RegisterApp(router fiber.Router) {
|
||||
server := NewStrictHandler(NewUserHandler(), nil)
|
||||
func (h UserHandler) RegisterRoutes(router fiber.Router) {
|
||||
server := NewStrictHandler(h, nil)
|
||||
RegisterHandlers(router, server)
|
||||
|
||||
}
|
||||
|
||||
198
internal/api/user/handler/impl_test.go
Normal file
198
internal/api/user/handler/impl_test.go
Normal file
@ -0,0 +1,198 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockUserService implements service.UserService
|
||||
type MockUserService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockUserService) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*domain.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*domain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) GetUserByUuid(ctx context.Context, uuid string) (*domain.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*domain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) CreateUser(ctx context.Context, phoneNumber string) (*domain.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*domain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserService) VerifyUser(ctx context.Context, uuid string) (*domain.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*domain.User), args.Error(1)
|
||||
}
|
||||
|
||||
func TestNewUserHandler(t *testing.T) {
|
||||
mockService := &MockUserService{}
|
||||
handler := NewUserHandler(mockService)
|
||||
|
||||
assert.NotNil(t, handler)
|
||||
assert.Equal(t, mockService, handler.service)
|
||||
assert.Implements(t, (*StrictServerInterface)(nil), handler)
|
||||
}
|
||||
|
||||
func TestUserHandler_GetUserById(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
userId string
|
||||
setupMock func(*MockUserService)
|
||||
expectedStatus int
|
||||
expectError bool
|
||||
expectedMsg string
|
||||
}{
|
||||
{
|
||||
name: "successful user retrieval",
|
||||
userId: "123e4567-e89b-12d3-a456-426614174000",
|
||||
setupMock: func(m *MockUserService) {
|
||||
user := &domain.User{
|
||||
Uuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
PhoneNumber: "+79161234567",
|
||||
}
|
||||
m.On("GetUserByUuid", mock.Anything, "123e4567-e89b-12d3-a456-426614174000").
|
||||
Return(user, nil).Once()
|
||||
},
|
||||
expectedStatus: 200, // Fixed copier bug
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "user not found",
|
||||
userId: "nonexistent-uuid",
|
||||
setupMock: func(m *MockUserService) {
|
||||
m.On("GetUserByUuid", mock.Anything, "nonexistent-uuid").
|
||||
Return(nil, domain.ErrUserNotFound{PhoneNumber: "nonexistent-uuid"}).Once()
|
||||
},
|
||||
expectedStatus: 404,
|
||||
expectError: true,
|
||||
expectedMsg: "User not found with phone number: nonexistent-uuid",
|
||||
},
|
||||
{
|
||||
name: "service error",
|
||||
userId: "error-uuid",
|
||||
setupMock: func(m *MockUserService) {
|
||||
m.On("GetUserByUuid", mock.Anything, "error-uuid").
|
||||
Return(nil, assert.AnError).Once()
|
||||
},
|
||||
expectedStatus: 404,
|
||||
expectError: true,
|
||||
expectedMsg: assert.AnError.Error(),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockService := &MockUserService{}
|
||||
handler := &UserHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
tt.setupMock(mockService)
|
||||
|
||||
request := GetUserByIdRequestObject{
|
||||
UserId: tt.userId,
|
||||
}
|
||||
|
||||
result, err := handler.GetUserById(ctx, request)
|
||||
|
||||
assert.NoError(t, err) // Handler should not return errors, only response objects
|
||||
|
||||
if tt.expectedStatus == 200 {
|
||||
response, ok := result.(GetUserById200JSONResponse)
|
||||
assert.True(t, ok, "Expected 200 response type")
|
||||
_ = response // Just to avoid unused variable error
|
||||
} else {
|
||||
response, ok := result.(GetUserById404JSONResponse)
|
||||
assert.True(t, ok, "Expected 404 response type")
|
||||
assert.Equal(t, tt.expectedMsg, response.Message)
|
||||
_ = response // Use the variable to avoid unused error
|
||||
}
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserHandler_CreateUser(t *testing.T) {
|
||||
mockService := &MockUserService{}
|
||||
handler := &UserHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("create user not implemented", func(t *testing.T) {
|
||||
request := CreateUserRequestObject{}
|
||||
|
||||
// This should panic as per the current implementation
|
||||
assert.Panics(t, func() {
|
||||
_, _ = handler.CreateUser(ctx, request)
|
||||
}, "CreateUser should panic as it's not implemented")
|
||||
})
|
||||
}
|
||||
|
||||
func TestUserHandler_EdgeCases(t *testing.T) {
|
||||
t.Run("empty user ID should be handled gracefully", func(t *testing.T) {
|
||||
mockService := &MockUserService{}
|
||||
handler := &UserHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
mockService.On("GetUserByUuid", mock.Anything, "").
|
||||
Return(nil, domain.ErrUserNotFound{PhoneNumber: ""}).Once()
|
||||
|
||||
request := GetUserByIdRequestObject{
|
||||
UserId: "",
|
||||
}
|
||||
|
||||
result, err := handler.GetUserById(ctx, request)
|
||||
|
||||
assert.NoError(t, err)
|
||||
response, ok := result.(GetUserById404JSONResponse)
|
||||
assert.True(t, ok)
|
||||
assert.Contains(t, response.Message, "User not found")
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
|
||||
t.Run("special characters in user ID", func(t *testing.T) {
|
||||
mockService := &MockUserService{}
|
||||
handler := &UserHandler{service: mockService}
|
||||
ctx := context.Background()
|
||||
|
||||
specialUserId := "user@#$%^&*()"
|
||||
|
||||
mockService.On("GetUserByUuid", mock.Anything, specialUserId).
|
||||
Return(nil, domain.ErrUserNotFound{PhoneNumber: specialUserId}).Once()
|
||||
|
||||
request := GetUserByIdRequestObject{
|
||||
UserId: specialUserId,
|
||||
}
|
||||
|
||||
result, err := handler.GetUserById(ctx, request)
|
||||
|
||||
assert.NoError(t, err)
|
||||
response, ok := result.(GetUserById404JSONResponse)
|
||||
assert.True(t, ok)
|
||||
_ = response // Use the variable to avoid unused error
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
63
internal/api/user/repo/user_repo.go
Normal file
63
internal/api/user/repo/user_repo.go
Normal file
@ -0,0 +1,63 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
db "git.logidex.ru/fakz9/logidex-id/internal/db/generated"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type userRepo struct {
|
||||
db db.DBTX
|
||||
}
|
||||
|
||||
func (u userRepo) VerifyUser(ctx context.Context, requestUuid string) (*db.User, error) {
|
||||
//TODO implement me
|
||||
|
||||
queries := db.New(u.db)
|
||||
uuidParsed, err := uuid.Parse(requestUuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dbUser, err := queries.UpdateUserVerified(ctx, uuidParsed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dbUser, nil
|
||||
}
|
||||
|
||||
func (u userRepo) GetUserByUuid(ctx context.Context, requestUuid string) (*db.User, error) {
|
||||
queries := db.New(u.db)
|
||||
uuidParsed, err := uuid.Parse(requestUuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dbUser, err := queries.GetUserByUUID(ctx, uuidParsed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dbUser, nil
|
||||
}
|
||||
|
||||
func (u userRepo) CreateUser(ctx context.Context, phoneNumber string) (*db.User, error) {
|
||||
queries := db.New(u.db)
|
||||
user, err := queries.CreateUser(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (u userRepo) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*db.User, error) {
|
||||
queries := db.New(u.db)
|
||||
dbUser, err := queries.GetByPhoneNumber(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dbUser, nil
|
||||
}
|
||||
|
||||
func NewUserRepo(db db.DBTX) domain.UserRepository {
|
||||
return &userRepo{db: db}
|
||||
}
|
||||
@ -1,4 +0,0 @@
|
||||
package repository
|
||||
|
||||
type UserRepo interface {
|
||||
}
|
||||
@ -1,13 +1,71 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/repository"
|
||||
"context"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo *repository.UserRepo
|
||||
type UserService interface {
|
||||
GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*domain.User, error)
|
||||
GetUserByUuid(ctx context.Context, uuid string) (*domain.User, error)
|
||||
CreateUser(ctx context.Context, phoneNumber string) (*domain.User, error)
|
||||
VerifyUser(ctx context.Context, uuid string) (*domain.User, error)
|
||||
}
|
||||
type userService struct {
|
||||
repo domain.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo *repository.UserRepo) *UserService {
|
||||
return &UserService{repo: repo}
|
||||
func (u userService) GetUserByUuid(ctx context.Context, uuid string) (*domain.User, error) {
|
||||
dbUser, err := u.repo.GetUserByUuid(ctx, uuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dbUser == nil {
|
||||
return nil, domain.ErrUserNotFound{PhoneNumber: uuid}
|
||||
}
|
||||
return &domain.User{
|
||||
Uuid: dbUser.Uuid.String(),
|
||||
PhoneNumber: dbUser.PhoneNumber,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u userService) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*domain.User, error) {
|
||||
dbUser, err := u.repo.GetUserByPhoneNumber(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dbUser == nil {
|
||||
return nil, domain.ErrUserNotFound{PhoneNumber: phoneNumber}
|
||||
}
|
||||
return &domain.User{
|
||||
Uuid: dbUser.Uuid.String(),
|
||||
PhoneNumber: dbUser.PhoneNumber,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u userService) CreateUser(ctx context.Context, phoneNumber string) (*domain.User, error) {
|
||||
dbUser, err := u.repo.CreateUser(ctx, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.User{
|
||||
Uuid: dbUser.Uuid.String(),
|
||||
PhoneNumber: dbUser.PhoneNumber,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u userService) VerifyUser(ctx context.Context, uuid string) (*domain.User, error) {
|
||||
dbUser, err := u.repo.VerifyUser(ctx, uuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.User{
|
||||
Uuid: dbUser.Uuid.String(),
|
||||
PhoneNumber: dbUser.PhoneNumber,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func NewUserService(repo domain.UserRepository) UserService {
|
||||
return &userService{repo: repo}
|
||||
}
|
||||
|
||||
337
internal/api/user/service/user_service_test.go
Normal file
337
internal/api/user/service/user_service_test.go
Normal file
@ -0,0 +1,337 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
db "git.logidex.ru/fakz9/logidex-id/internal/db/generated"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockUserRepository implements domain.UserRepository
|
||||
type MockUserRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockUserRepository) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*db.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*db.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserRepository) GetUserByUuid(ctx context.Context, uuid string) (*db.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*db.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserRepository) CreateUser(ctx context.Context, phoneNumber string) (*db.User, error) {
|
||||
args := m.Called(ctx, phoneNumber)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*db.User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockUserRepository) VerifyUser(ctx context.Context, uuid string) (*db.User, error) {
|
||||
args := m.Called(ctx, uuid)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*db.User), args.Error(1)
|
||||
}
|
||||
|
||||
func TestNewUserService(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := NewUserService(mockRepo)
|
||||
|
||||
assert.NotNil(t, service)
|
||||
assert.Implements(t, (*UserService)(nil), service)
|
||||
}
|
||||
|
||||
func TestUserService_GetUserByPhoneNumber(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := &userService{repo: mockRepo}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "+79161234567"
|
||||
testUuid := uuid.New()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *domain.User
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "user found",
|
||||
setupMock: func() {
|
||||
dbUser := &db.User{
|
||||
Uuid: testUuid,
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockRepo.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(dbUser, nil).Once()
|
||||
},
|
||||
expectedUser: &domain.User{
|
||||
Uuid: testUuid.String(),
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "user not found",
|
||||
setupMock: func() {
|
||||
mockRepo.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, nil).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
errType: domain.ErrUserNotFound{},
|
||||
},
|
||||
{
|
||||
name: "repository error",
|
||||
setupMock: func() {
|
||||
mockRepo.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mock
|
||||
mockRepo.ExpectedCalls = nil
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.GetUserByPhoneNumber(ctx, phoneNumber)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_GetUserByUuid(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := &userService{repo: mockRepo}
|
||||
ctx := context.Background()
|
||||
testUuid := uuid.New()
|
||||
uuidString := testUuid.String()
|
||||
phoneNumber := "+79161234567"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *domain.User
|
||||
wantErr bool
|
||||
errType interface{}
|
||||
}{
|
||||
{
|
||||
name: "user found",
|
||||
setupMock: func() {
|
||||
dbUser := &db.User{
|
||||
Uuid: testUuid,
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockRepo.On("GetUserByUuid", ctx, uuidString).Return(dbUser, nil).Once()
|
||||
},
|
||||
expectedUser: &domain.User{
|
||||
Uuid: uuidString,
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "user not found",
|
||||
setupMock: func() {
|
||||
mockRepo.On("GetUserByUuid", ctx, uuidString).Return(nil, nil).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
errType: domain.ErrUserNotFound{},
|
||||
},
|
||||
{
|
||||
name: "repository error",
|
||||
setupMock: func() {
|
||||
mockRepo.On("GetUserByUuid", ctx, uuidString).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mock
|
||||
mockRepo.ExpectedCalls = nil
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.GetUserByUuid(ctx, uuidString)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
if tt.errType != nil {
|
||||
assert.IsType(t, tt.errType, err)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_CreateUser(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := &userService{repo: mockRepo}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "+79161234567"
|
||||
testUuid := uuid.New()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *domain.User
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "user created successfully",
|
||||
setupMock: func() {
|
||||
dbUser := &db.User{
|
||||
Uuid: testUuid,
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockRepo.On("CreateUser", ctx, phoneNumber).Return(dbUser, nil).Once()
|
||||
},
|
||||
expectedUser: &domain.User{
|
||||
Uuid: testUuid.String(),
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "repository error",
|
||||
setupMock: func() {
|
||||
mockRepo.On("CreateUser", ctx, phoneNumber).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mock
|
||||
mockRepo.ExpectedCalls = nil
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.CreateUser(ctx, phoneNumber)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_VerifyUser(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := &userService{repo: mockRepo}
|
||||
ctx := context.Background()
|
||||
testUuid := uuid.New()
|
||||
uuidString := testUuid.String()
|
||||
phoneNumber := "+79161234567"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func()
|
||||
expectedUser *domain.User
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "user verified successfully",
|
||||
setupMock: func() {
|
||||
dbUser := &db.User{
|
||||
Uuid: testUuid,
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
mockRepo.On("VerifyUser", ctx, uuidString).Return(dbUser, nil).Once()
|
||||
},
|
||||
expectedUser: &domain.User{
|
||||
Uuid: uuidString,
|
||||
PhoneNumber: phoneNumber,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "repository error",
|
||||
setupMock: func() {
|
||||
mockRepo.On("VerifyUser", ctx, uuidString).Return(nil, assert.AnError).Once()
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mock
|
||||
mockRepo.ExpectedCalls = nil
|
||||
tt.setupMock()
|
||||
|
||||
result, err := service.VerifyUser(ctx, uuidString)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.expectedUser, result)
|
||||
}
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Test edge cases and error scenarios
|
||||
func TestUserService_ErrorMessages(t *testing.T) {
|
||||
mockRepo := &MockUserRepository{}
|
||||
service := &userService{repo: mockRepo}
|
||||
ctx := context.Background()
|
||||
phoneNumber := "+79161234567"
|
||||
|
||||
t.Run("GetUserByPhoneNumber returns proper error message", func(t *testing.T) {
|
||||
mockRepo.On("GetUserByPhoneNumber", ctx, phoneNumber).Return(nil, nil).Once()
|
||||
|
||||
_, err := service.GetUserByPhoneNumber(ctx, phoneNumber)
|
||||
|
||||
assert.Error(t, err)
|
||||
userErr, ok := err.(domain.ErrUserNotFound)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, phoneNumber, userErr.PhoneNumber)
|
||||
assert.Contains(t, err.Error(), phoneNumber)
|
||||
|
||||
mockRepo.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
@ -1,9 +1,10 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/spf13/viper"
|
||||
"log"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@ -20,11 +21,16 @@ type Config struct {
|
||||
Host string
|
||||
Password string
|
||||
}
|
||||
DB struct {
|
||||
Host string
|
||||
Port int
|
||||
User string
|
||||
Password string
|
||||
Dbname string
|
||||
}
|
||||
}
|
||||
|
||||
var Cfg *Config
|
||||
|
||||
func Init() {
|
||||
func NewConfig() Config {
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Println("Error loading .env file")
|
||||
@ -48,5 +54,5 @@ func Init() {
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to decode config into struct, %v", err)
|
||||
}
|
||||
Cfg = &config
|
||||
return config
|
||||
}
|
||||
|
||||
24
internal/db/database.go
Normal file
24
internal/db/database.go
Normal file
@ -0,0 +1,24 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewDatabasePool(cfg config.Config) *pgxpool.Pool {
|
||||
ctx := context.Background()
|
||||
connUrl := "postgresql://" + cfg.DB.User + ":" + cfg.DB.Password + "@" + cfg.DB.Host + ":" + strconv.Itoa(cfg.DB.Port) + "/" + cfg.DB.Dbname
|
||||
|
||||
pool, err := pgxpool.New(ctx, connUrl)
|
||||
if err != nil {
|
||||
panic("Failed to connect to database: " + err.Error())
|
||||
}
|
||||
err = pool.Ping(ctx)
|
||||
if err != nil {
|
||||
panic("Failed to ping database: " + err.Error())
|
||||
}
|
||||
return pool
|
||||
}
|
||||
15
internal/db/fx.go
Normal file
15
internal/db/fx.go
Normal file
@ -0,0 +1,15 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
sqlcdb "git.logidex.ru/fakz9/logidex-id/internal/db/generated"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
var Module = fx.Options(
|
||||
fx.Provide(
|
||||
fx.Annotate(
|
||||
NewDatabasePool,
|
||||
fx.As(new(sqlcdb.DBTX)),
|
||||
),
|
||||
),
|
||||
)
|
||||
32
internal/db/generated/db.go
Normal file
32
internal/db/generated/db.go
Normal file
@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.28.0
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
19
internal/db/generated/models.go
Normal file
19
internal/db/generated/models.go
Normal file
@ -0,0 +1,19 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.28.0
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Uuid uuid.UUID `json:"uuid"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Verified bool `json:"verified"`
|
||||
VerifiedAt *time.Time `json:"verified_at"`
|
||||
}
|
||||
20
internal/db/generated/querier.go
Normal file
20
internal/db/generated/querier.go
Normal file
@ -0,0 +1,20 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.28.0
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
CreateUser(ctx context.Context, phoneNumber string) (User, error)
|
||||
GetByPhoneNumber(ctx context.Context, phoneNumber string) (User, error)
|
||||
GetUserByUUID(ctx context.Context, argUuid uuid.UUID) (User, error)
|
||||
UpdateUserVerified(ctx context.Context, argUuid uuid.UUID) (User, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
92
internal/db/generated/users.sql.go
Normal file
92
internal/db/generated/users.sql.go
Normal file
@ -0,0 +1,92 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.28.0
|
||||
// source: users.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users (phone_number)
|
||||
VALUES ($1)
|
||||
RETURNING uuid, phone_number, created_at, verified, verified_at
|
||||
`
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, phoneNumber string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, createUser, phoneNumber)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.Uuid,
|
||||
&i.PhoneNumber,
|
||||
&i.CreatedAt,
|
||||
&i.Verified,
|
||||
&i.VerifiedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getByPhoneNumber = `-- name: GetByPhoneNumber :one
|
||||
SELECT uuid, phone_number, created_at, verified, verified_at
|
||||
FROM users
|
||||
WHERE phone_number = $1
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetByPhoneNumber(ctx context.Context, phoneNumber string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getByPhoneNumber, phoneNumber)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.Uuid,
|
||||
&i.PhoneNumber,
|
||||
&i.CreatedAt,
|
||||
&i.Verified,
|
||||
&i.VerifiedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByUUID = `-- name: GetUserByUUID :one
|
||||
SELECT uuid, phone_number, created_at, verified, verified_at
|
||||
FROM users
|
||||
WHERE uuid = $1
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByUUID(ctx context.Context, argUuid uuid.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUUID, argUuid)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.Uuid,
|
||||
&i.PhoneNumber,
|
||||
&i.CreatedAt,
|
||||
&i.Verified,
|
||||
&i.VerifiedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateUserVerified = `-- name: UpdateUserVerified :one
|
||||
UPDATE users
|
||||
SET verified = TRUE,
|
||||
verified_at = CURRENT_TIMESTAMP
|
||||
WHERE uuid = $1
|
||||
RETURNING uuid, phone_number, created_at, verified, verified_at
|
||||
`
|
||||
|
||||
func (q *Queries) UpdateUserVerified(ctx context.Context, argUuid uuid.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, updateUserVerified, argUuid)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.Uuid,
|
||||
&i.PhoneNumber,
|
||||
&i.CreatedAt,
|
||||
&i.Verified,
|
||||
&i.VerifiedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
9
internal/db/migrations/001_init.sql
Normal file
9
internal/db/migrations/001_init.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
uuid UUID PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
phone_number VARCHAR(20) NOT NULL CHECK (phone_number ~ '^\+[0-9]{10,15}$'),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
verified BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
verified_at TIMESTAMP NULL
|
||||
|
||||
);
|
||||
23
internal/db/queries/users.sql
Normal file
23
internal/db/queries/users.sql
Normal file
@ -0,0 +1,23 @@
|
||||
-- name: GetByPhoneNumber :one
|
||||
SELECT *
|
||||
FROM users
|
||||
WHERE phone_number = $1
|
||||
LIMIT 1;
|
||||
|
||||
-- name: GetUserByUUID :one
|
||||
SELECT *
|
||||
FROM users
|
||||
WHERE uuid = $1
|
||||
LIMIT 1;
|
||||
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users (phone_number)
|
||||
VALUES ($1)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateUserVerified :one
|
||||
UPDATE users
|
||||
SET verified = TRUE,
|
||||
verified_at = CURRENT_TIMESTAMP
|
||||
WHERE uuid = $1
|
||||
RETURNING *;
|
||||
@ -3,26 +3,15 @@ package hydra_client
|
||||
import (
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
hydraApi "github.com/ory/hydra-client-go"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
client *hydraApi.APIClient
|
||||
initClient sync.Once
|
||||
)
|
||||
|
||||
func InitClient() {
|
||||
func NewHydraClient(appConfig config.Config) *hydraApi.APIClient {
|
||||
cfg := hydraApi.NewConfiguration()
|
||||
cfg.AddDefaultHeader("X-Secret", config.Cfg.Hydra.Password)
|
||||
cfg.AddDefaultHeader("X-Secret", appConfig.Hydra.Password)
|
||||
cfg.Servers = []hydraApi.ServerConfiguration{
|
||||
{
|
||||
URL: config.Cfg.Hydra.Host,
|
||||
URL: appConfig.Hydra.Host,
|
||||
},
|
||||
}
|
||||
client = hydraApi.NewAPIClient(cfg)
|
||||
}
|
||||
|
||||
func GetClient() *hydraApi.APIClient {
|
||||
initClient.Do(InitClient)
|
||||
return client
|
||||
return hydraApi.NewAPIClient(cfg)
|
||||
}
|
||||
|
||||
19
internal/phoneutil/phoneutil.go
Normal file
19
internal/phoneutil/phoneutil.go
Normal file
@ -0,0 +1,19 @@
|
||||
package phoneutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/nyaruka/phonenumbers"
|
||||
)
|
||||
|
||||
func ParseAndFormatPhoneNumber(phoneNumber string) (string, error) {
|
||||
parsedNumber, err := phonenumbers.Parse(phoneNumber, "RU")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := phonenumbers.Format(parsedNumber, phonenumbers.E164)
|
||||
if result == "" {
|
||||
return "", errors.New("failed to format phone number")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
129
internal/phoneutil/phoneutil_test.go
Normal file
129
internal/phoneutil/phoneutil_test.go
Normal file
@ -0,0 +1,129 @@
|
||||
package phoneutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseAndFormatPhoneNumber(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "valid russian phone number with +7",
|
||||
phoneNumber: "+79161234567",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid russian phone number with 8",
|
||||
phoneNumber: "89161234567",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid phone number with spaces",
|
||||
phoneNumber: "+7 916 123 45 67",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid phone number with dashes",
|
||||
phoneNumber: "+7-916-123-45-67",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid phone number with parentheses",
|
||||
phoneNumber: "+7 (916) 123-45-67",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid moscow landline",
|
||||
phoneNumber: "+7 495 123 45 67",
|
||||
want: "+74951234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "russian mobile without country code",
|
||||
phoneNumber: "9161234567",
|
||||
want: "+79161234567",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid phone number - too short",
|
||||
phoneNumber: "1",
|
||||
want: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid phone number - too long",
|
||||
phoneNumber: "+712345678901234567890",
|
||||
want: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "empty phone number",
|
||||
phoneNumber: "",
|
||||
want: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid characters",
|
||||
phoneNumber: "+7abc1234567",
|
||||
want: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "only spaces",
|
||||
phoneNumber: " ",
|
||||
want: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "us phone number should work with ru default",
|
||||
phoneNumber: "+12345678901",
|
||||
want: "+12345678901",
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseAndFormatPhoneNumber(tt.phoneNumber)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err, "ParseAndFormatPhoneNumber() should return error")
|
||||
assert.Empty(t, got, "ParseAndFormatPhoneNumber() should return empty string on error")
|
||||
} else {
|
||||
assert.NoError(t, err, "ParseAndFormatPhoneNumber() should not return error")
|
||||
assert.Equal(t, tt.want, got, "ParseAndFormatPhoneNumber() result mismatch")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAndFormatPhoneNumber_ErrorHandling(t *testing.T) {
|
||||
// Test specific error cases
|
||||
testCases := []struct {
|
||||
name string
|
||||
phoneNumber string
|
||||
}{
|
||||
{"nil input", ""},
|
||||
{"invalid format", "not-a-phone-number"},
|
||||
{"incomplete number", "+7"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
result, err := ParseAndFormatPhoneNumber(tc.phoneNumber)
|
||||
assert.Error(t, err)
|
||||
assert.Empty(t, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1,26 +1,21 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
"github.com/redis/rueidis"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var client rueidis.Client
|
||||
|
||||
func Init() error {
|
||||
func NewRedisClient(cfg config.Config) rueidis.Client {
|
||||
var err error
|
||||
client, err = rueidis.NewClient(rueidis.ClientOption{
|
||||
client, err := rueidis.NewClient(rueidis.ClientOption{
|
||||
// Set the address of your Redis server
|
||||
InitAddress: []string{config.Cfg.Redis.Host + ":" + strconv.Itoa(config.Cfg.Redis.Port)},
|
||||
Password: config.Cfg.Redis.Password,
|
||||
InitAddress: []string{cfg.Redis.Host + ":" + strconv.Itoa(cfg.Redis.Port)},
|
||||
Password: cfg.Redis.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetClient() rueidis.Client {
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
12
internal/server/fx.go
Normal file
12
internal/server/fx.go
Normal file
@ -0,0 +1,12 @@
|
||||
package server
|
||||
|
||||
import "go.uber.org/fx"
|
||||
|
||||
// Module provides the server dependencies and lifecycle management
|
||||
var Module = fx.Options(
|
||||
fx.Provide(
|
||||
NewFiberApp,
|
||||
NewAPIRouter,
|
||||
),
|
||||
fx.Invoke(StartServer),
|
||||
)
|
||||
75
internal/server/server.go
Normal file
75
internal/server/server.go
Normal file
@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
fiberlogger "github.com/gofiber/fiber/v2/middleware/logger"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
// NewFiberApp creates a new Fiber application with common middleware
|
||||
func NewFiberApp(cfg config.Config) *fiber.App {
|
||||
app := fiber.New(fiber.Config{
|
||||
AppName: "Logidex ID API",
|
||||
ServerHeader: "Logidex ID",
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
code := fiber.StatusInternalServerError
|
||||
if e, ok := err.(*fiber.Error); ok {
|
||||
code = e.Code
|
||||
}
|
||||
|
||||
return c.Status(code).JSON(fiber.Map{
|
||||
"error": true,
|
||||
"message": err.Error(),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
// Add middleware
|
||||
app.Use(recover.New())
|
||||
app.Use(fiberlogger.New(fiberlogger.Config{
|
||||
Format: "[${time}] ${status} - ${latency} ${method} ${path}\n",
|
||||
}))
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowOrigins: "*",
|
||||
AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
|
||||
AllowHeaders: "Origin,Content-Type,Accept,Authorization",
|
||||
}))
|
||||
|
||||
// Health check endpoint
|
||||
app.Get("/health", func(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"status": "ok",
|
||||
"service": "logidex-id-api",
|
||||
})
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
// NewAPIRouter creates the main API router group
|
||||
func NewAPIRouter(app *fiber.App) fiber.Router {
|
||||
return app.Group("/api")
|
||||
}
|
||||
|
||||
// StartServer handles the server lifecycle
|
||||
func StartServer(lifecycle fx.Lifecycle, app *fiber.App, cfg config.Config) {
|
||||
lifecycle.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
go func() {
|
||||
addr := ":" + strconv.Itoa(cfg.App.Port)
|
||||
if err := app.Listen(addr); err != nil {
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
return app.Shutdown()
|
||||
},
|
||||
})
|
||||
}
|
||||
48
internal/server/server_test.go
Normal file
48
internal/server/server_test.go
Normal file
@ -0,0 +1,48 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/config"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewFiberApp(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
cfg.App.Port = 8080
|
||||
|
||||
app := NewFiberApp(cfg)
|
||||
|
||||
assert.NotNil(t, app)
|
||||
|
||||
// Test health check endpoint
|
||||
req := httptest.NewRequest("GET", "/health", nil)
|
||||
resp, err := app.Test(req)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestNewAPIRouter(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
cfg.App.Port = 8080
|
||||
|
||||
app := NewFiberApp(cfg)
|
||||
router := NewAPIRouter(app)
|
||||
|
||||
assert.NotNil(t, router)
|
||||
|
||||
// Test that we can add routes to the router
|
||||
router.Get("/test", func(c *fiber.Ctx) error {
|
||||
return c.JSON(map[string]string{"message": "test"})
|
||||
})
|
||||
|
||||
// Test the route works
|
||||
req := httptest.NewRequest("GET", "/api/test", nil)
|
||||
resp, err := app.Test(req)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
}
|
||||
35
sqlc.yaml
Normal file
35
sqlc.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
version: "2"
|
||||
sql:
|
||||
- engine: postgresql
|
||||
schema: "internal/db/migrations"
|
||||
queries: "internal/db/queries"
|
||||
gen:
|
||||
go:
|
||||
package: "db"
|
||||
out: "internal/db/generated"
|
||||
sql_package: "pgx/v5"
|
||||
emit_interface: true
|
||||
emit_json_tags: true
|
||||
emit_pointers_for_null_types: true
|
||||
overrides:
|
||||
# Timestamp
|
||||
- db_type: "pg_catalog.timestamp"
|
||||
nullable: true
|
||||
go_type:
|
||||
import: "time"
|
||||
type: "Time"
|
||||
pointer: true
|
||||
- db_type: "pg_catalog.timestamp"
|
||||
go_type: "time.Time"
|
||||
# UUID
|
||||
- db_type: "uuid"
|
||||
go_type:
|
||||
import: "github.com/google/uuid"
|
||||
type: "UUID"
|
||||
- db_type: "uuid"
|
||||
nullable: true
|
||||
go_type:
|
||||
import: "github.com/google/uuid"
|
||||
type: "UUID"
|
||||
pointer: true
|
||||
|
||||
44
test.env
Normal file
44
test.env
Normal file
@ -0,0 +1,44 @@
|
||||
# Test Environment Configuration
|
||||
# This file contains configuration for running tests
|
||||
|
||||
# Test Database Configuration
|
||||
TEST_DB_HOST=localhost
|
||||
TEST_DB_PORT=5432
|
||||
TEST_DB_NAME=logidex_test
|
||||
TEST_DB_USER=test_user
|
||||
TEST_DB_PASSWORD=test_password
|
||||
TEST_DB_SSL_MODE=disable
|
||||
|
||||
# Test Redis Configuration
|
||||
TEST_REDIS_HOST=localhost
|
||||
TEST_REDIS_PORT=6379
|
||||
TEST_REDIS_PASSWORD=
|
||||
TEST_REDIS_DB=1
|
||||
|
||||
# Test Hydra Configuration
|
||||
TEST_HYDRA_ADMIN_URL=http://localhost:4445
|
||||
TEST_HYDRA_PUBLIC_URL=http://localhost:4444
|
||||
|
||||
# Test Environment Settings
|
||||
TEST_LOG_LEVEL=debug
|
||||
TEST_SERVER_PORT=8080
|
||||
TEST_TIMEOUT=30s
|
||||
|
||||
# Mock Settings
|
||||
ENABLE_MOCKS=true
|
||||
MOCK_OTP_CODE=123456
|
||||
MOCK_SMS_PROVIDER=true
|
||||
|
||||
# Test Feature Flags
|
||||
ENABLE_INTEGRATION_TESTS=false
|
||||
ENABLE_E2E_TESTS=false
|
||||
ENABLE_LOAD_TESTS=false
|
||||
|
||||
# Test Timeouts
|
||||
TEST_DEFAULT_TIMEOUT=30s
|
||||
TEST_INTEGRATION_TIMEOUT=60s
|
||||
TEST_E2E_TIMEOUT=120s
|
||||
|
||||
# Coverage Settings
|
||||
TEST_COVERAGE_THRESHOLD=80
|
||||
GENERATE_COVERAGE_REPORT=true
|
||||
225
test/testutil/test_helpers.go
Normal file
225
test/testutil/test_helpers.go
Normal file
@ -0,0 +1,225 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.logidex.ru/fakz9/logidex-id/internal/api/user/domain"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestContext creates a context with timeout for tests
|
||||
func TestContext(t *testing.T) context.Context {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// CreateTestUser creates a test user with default values
|
||||
func CreateTestUser(t *testing.T) *domain.User {
|
||||
return &domain.User{
|
||||
Uuid: uuid.New().String(),
|
||||
PhoneNumber: "+79161234567",
|
||||
}
|
||||
}
|
||||
|
||||
// CreateTestUserWithPhone creates a test user with specified phone number
|
||||
func CreateTestUserWithPhone(t *testing.T, phoneNumber string) *domain.User {
|
||||
return &domain.User{
|
||||
Uuid: uuid.New().String(),
|
||||
PhoneNumber: phoneNumber,
|
||||
}
|
||||
}
|
||||
|
||||
// AssertValidUUID checks if a string is a valid UUID
|
||||
func AssertValidUUID(t *testing.T, uuidStr string) {
|
||||
_, err := uuid.Parse(uuidStr)
|
||||
assert.NoError(t, err, "Expected valid UUID, got: %s", uuidStr)
|
||||
}
|
||||
|
||||
// AssertValidPhoneNumber checks if a phone number follows expected format
|
||||
func AssertValidPhoneNumber(t *testing.T, phoneNumber string) {
|
||||
assert.NotEmpty(t, phoneNumber)
|
||||
assert.True(t, len(phoneNumber) >= 10, "Phone number should be at least 10 characters")
|
||||
assert.True(t, phoneNumber[0] == '+', "Phone number should start with +")
|
||||
}
|
||||
|
||||
// TimeoutContext creates a context that times out after the specified duration
|
||||
// Note: This function returns a context without a cancel function.
|
||||
// Use TestContext(t) instead for proper cleanup in tests.
|
||||
func TimeoutContext(timeout time.Duration) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), timeout)
|
||||
}
|
||||
|
||||
// ErrorsContain checks if an error contains a specific substring
|
||||
func ErrorsContain(t *testing.T, err error, substring string) {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), substring)
|
||||
}
|
||||
|
||||
// AssertNoError is a helper that fails the test if error is not nil
|
||||
func AssertNoError(t *testing.T, err error, msgAndArgs ...interface{}) {
|
||||
assert.NoError(t, err, msgAndArgs...)
|
||||
}
|
||||
|
||||
// AssertError is a helper that fails the test if error is nil
|
||||
func AssertError(t *testing.T, err error, msgAndArgs ...interface{}) {
|
||||
assert.Error(t, err, msgAndArgs...)
|
||||
}
|
||||
|
||||
// StringPtr returns a pointer to a string value
|
||||
func StringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
// IntPtr returns a pointer to an int value
|
||||
func IntPtr(i int) *int {
|
||||
return &i
|
||||
}
|
||||
|
||||
// BoolPtr returns a pointer to a bool value
|
||||
func BoolPtr(b bool) *bool {
|
||||
return &b
|
||||
}
|
||||
|
||||
// TestPhoneNumbers contains various phone numbers for testing
|
||||
var TestPhoneNumbers = struct {
|
||||
ValidRussian string
|
||||
ValidUS string
|
||||
ValidUK string
|
||||
Invalid string
|
||||
Empty string
|
||||
TooShort string
|
||||
WithSpaces string
|
||||
WithDashes string
|
||||
WithParentheses string
|
||||
}{
|
||||
ValidRussian: "+79161234567",
|
||||
ValidUS: "+12345678901",
|
||||
ValidUK: "+441234567890",
|
||||
Invalid: "not-a-phone",
|
||||
Empty: "",
|
||||
TooShort: "123",
|
||||
WithSpaces: "+7 916 123 45 67",
|
||||
WithDashes: "+7-916-123-45-67",
|
||||
WithParentheses: "+7 (916) 123-45-67",
|
||||
}
|
||||
|
||||
// TestUUIDs contains various UUIDs for testing
|
||||
var TestUUIDs = struct {
|
||||
Valid1 string
|
||||
Valid2 string
|
||||
Invalid string
|
||||
Empty string
|
||||
}{
|
||||
Valid1: "123e4567-e89b-12d3-a456-426614174000",
|
||||
Valid2: "987fcdeb-51a2-43d1-9f12-345678901234",
|
||||
Invalid: "not-a-uuid",
|
||||
Empty: "",
|
||||
}
|
||||
|
||||
// TestErrors contains common test errors
|
||||
var TestErrors = struct {
|
||||
Generic error
|
||||
NotFound error
|
||||
Invalid error
|
||||
Timeout error
|
||||
}{
|
||||
Generic: assert.AnError,
|
||||
NotFound: domain.ErrUserNotFound{PhoneNumber: "+79161234567"},
|
||||
Invalid: assert.AnError,
|
||||
Timeout: context.DeadlineExceeded,
|
||||
}
|
||||
|
||||
// CleanupFunc is a function that cleans up test resources
|
||||
type CleanupFunc func()
|
||||
|
||||
// SetupTestEnvironment sets up a test environment and returns cleanup function
|
||||
func SetupTestEnvironment(t *testing.T) CleanupFunc {
|
||||
// This could set up test databases, Redis connections, etc.
|
||||
// For now, it's a placeholder for future implementation
|
||||
|
||||
return func() {
|
||||
// Cleanup resources
|
||||
}
|
||||
}
|
||||
|
||||
// WaitFor waits for a condition to be true or timeout
|
||||
func WaitFor(t *testing.T, condition func() bool, timeout time.Duration, message string) {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
timeoutChan := time.After(timeout)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if condition() {
|
||||
return
|
||||
}
|
||||
case <-timeoutChan:
|
||||
t.Fatalf("Timeout waiting for condition: %s", message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Eventually runs a function until it succeeds or times out
|
||||
func Eventually(t *testing.T, fn func() error, timeout time.Duration, message string) {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
timeoutChan := time.After(timeout)
|
||||
|
||||
var lastErr error
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if err := fn(); err == nil {
|
||||
return
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
case <-timeoutChan:
|
||||
t.Fatalf("Timeout waiting for function to succeed: %s. Last error: %v", message, lastErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ParallelTest runs a test function in parallel multiple times
|
||||
func ParallelTest(t *testing.T, fn func(*testing.T), count int) {
|
||||
for i := 0; i < count; i++ {
|
||||
i := i // capture loop variable
|
||||
t.Run(fmt.Sprintf("parallel_%d", i), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fn(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkHelper provides utilities for benchmark tests
|
||||
type BenchmarkHelper struct {
|
||||
b *testing.B
|
||||
}
|
||||
|
||||
// NewBenchmarkHelper creates a new benchmark helper
|
||||
func NewBenchmarkHelper(b *testing.B) *BenchmarkHelper {
|
||||
return &BenchmarkHelper{b: b}
|
||||
}
|
||||
|
||||
// ResetTimer resets the benchmark timer
|
||||
func (bh *BenchmarkHelper) ResetTimer() {
|
||||
bh.b.ResetTimer()
|
||||
}
|
||||
|
||||
// StopTimer stops the benchmark timer
|
||||
func (bh *BenchmarkHelper) StopTimer() {
|
||||
bh.b.StopTimer()
|
||||
}
|
||||
|
||||
// StartTimer starts the benchmark timer
|
||||
func (bh *BenchmarkHelper) StartTimer() {
|
||||
bh.b.StartTimer()
|
||||
}
|
||||
18
tips
Normal file
18
tips
Normal file
@ -0,0 +1,18 @@
|
||||
|
||||
|
||||
http://oauth2.logidex.ru/oauth2/auth?client_id=172eb7e2-3b9f-4d4a-907a-d008cc15f08c&response_type=code&scope=openid+offline+offline_access&redirect_uri=http://crm.logidex.ru/auth/callback&state=random123
|
||||
http://crm.logidex.ru/auth/callback?code=ory_ac_a_OklDs30yo44y_VUXM_nqktKvOShDN6ZHnyhQ0Chlc.u-iLZyzy0I6pmTuF5apE-rualitEHPmbZJkPNw1q34s&scope=openid&state=random123
|
||||
|
||||
|
||||
|
||||
hydra create oauth2-client \
|
||||
--endpoint http://127.0.0.1:4445/ \
|
||||
--grant-type authorization_code \
|
||||
--grant-type refresh_token \
|
||||
--response-type code \
|
||||
--scope openid \
|
||||
--scope offline \
|
||||
--scope offline_access \
|
||||
--redirect-uri "https://crm.logidex.ru/auth/callback" \
|
||||
--format json
|
||||
{"client_id":"172eb7e2-3b9f-4d4a-907a-d008cc15f08c","client_name":"","client_secret":"l3t21k~LpUV1ztKYh_pLgmgsD1","client_secret_expires_at":0,"client_uri":"","created_at":"2025-10-26T23:00:45Z","grant_types":["authorization_code","refresh_token"],"jwks":{},"logo_uri":"","metadata":{},"owner":"","policy_uri":"","redirect_uris":["http://crm.logidex.ru/auth/callback"],"registration_access_token":"ory_at_27xocFJj0JJ9HJS95rWZ-9AwXDY32m7CemhVrq1LRtQ.kauzcPMwUzsjsB82p4Kvbh83UKWdKK4Jz_vL3trt1NM","registration_client_uri":"http://oauth2.logidex.ru/oauth2/register/","request_object_signing_alg":"RS256","response_types":["code"],"scope":"openid offline offline_access","skip_consent":false,"skip_logout_consent":false,"subject_type":"public","token_endpoint_auth_method":"client_secret_basic","tos_uri":"","updated_at":"2025-10-26T23:00:45.167057Z","userinfo_signed_response_alg":"none"}
|
||||
Reference in New Issue
Block a user