Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f556d729a5 | ||
|
|
e06a54947f | ||
|
|
689762c72a | ||
|
|
de171b790d | ||
|
|
d34cad033d | ||
|
|
760a778a27 | ||
|
|
7597e05243
|
||
|
|
636b0280c7 | ||
|
|
223b7919f9 | ||
|
|
66221e504c
|
||
|
|
093888f7fb
|
||
|
|
225dc0c963
|
||
|
|
c7b45952fe
|
||
|
|
f305e5b2e9
|
||
|
|
9f5029dd6e | ||
|
|
d01fae0775 | ||
|
|
371dc38958 | ||
|
|
0a00282ba7 | ||
|
|
c340693b24 | ||
|
|
8a90448854 |
@@ -5,3 +5,5 @@ DB_PASSWORD=password
|
|||||||
DB_HOST=auth_db
|
DB_HOST=auth_db
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
DB_SSLMODE=disable
|
DB_SSLMODE=disable
|
||||||
|
ENABLE_REGISTRATION=true
|
||||||
|
ALLOWED_ORIGINS="http://textsender.com"
|
||||||
|
|||||||
@@ -5,3 +5,5 @@ DB_PASSWORD=yEDjWZCH2vdctjn!
|
|||||||
DB_HOST=localhost
|
DB_HOST=localhost
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
DB_SSLMODE=disable
|
DB_SSLMODE=disable
|
||||||
|
ENABLE_REGISTRATION=true
|
||||||
|
ALLOWED_ORIGINS="http://textsender.com"
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ jobs:
|
|||||||
- uses: actions/checkout@v5
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: '1.25.3' # You can specify a specific version or 'stable'
|
go-version: '1.26.1' # You can specify a specific version or 'stable'
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: |
|
run: |
|
||||||
@@ -24,7 +24,7 @@ jobs:
|
|||||||
mkdir -p ~/.ssh
|
mkdir -p ~/.ssh
|
||||||
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
chmod 600 ~/.ssh/textsender_models_deploy_key
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
ssh-keyscan ${{ vars.MY_HOST }} >> ~/.ssh/known_hosts
|
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
eval $(ssh-agent -s)
|
eval $(ssh-agent -s)
|
||||||
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:18.0
|
image: postgres:18.3-alpine
|
||||||
env:
|
env:
|
||||||
POSTGRES_USER: ${{ secrets.DB_TEST_USER }}
|
POSTGRES_USER: ${{ secrets.DB_TEST_USER }}
|
||||||
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||||
@@ -66,9 +66,9 @@ jobs:
|
|||||||
uses: actions/checkout@v5
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: '1.25.3'
|
go-version: '1.26.1'
|
||||||
|
|
||||||
- name: Install PostgreSQL client
|
- name: Install PostgreSQL client
|
||||||
run: sudo apt update && sudo apt-get install -y postgresql-client
|
run: sudo apt update && sudo apt-get install -y postgresql-client
|
||||||
@@ -99,28 +99,32 @@ jobs:
|
|||||||
echo "Parent directory"
|
echo "Parent directory"
|
||||||
echo `pwd`
|
echo `pwd`
|
||||||
|
|
||||||
echo "SECRET_KEY=$SECRET_KEY" >> .env
|
echo "SECRET_KEY=$SECRET_KEY" > .env
|
||||||
echo "DB_NAME=$DB_NAME" > .env
|
echo "DB_NAME=$DB_NAME" >> .env
|
||||||
echo "DB_USER=$DB_USER" >> .env
|
echo "DB_USER=$DB_USER" >> .env
|
||||||
echo "DB_PASSWORD=$DB_PASSWORD" >> .env
|
echo "DB_PASSWORD=$DB_PASSWORD" >> .env
|
||||||
echo "DB_HOST=$DB_HOST" >> .env
|
echo "DB_HOST=$DB_HOST" >> .env
|
||||||
echo "DB_PORT=$DB_PORT" >> .env
|
echo "DB_PORT=$DB_PORT" >> .env
|
||||||
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
|
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
|
||||||
|
echo "ENABLE_REGISTRATION=true" >> .env
|
||||||
|
echo "ALLOWED_ORIGINS=http://localhost:9080" >> .env
|
||||||
|
|
||||||
|
echo "Initializing config"
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
|
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
eval $(ssh-agent -s)
|
||||||
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
|
|
||||||
|
go env -w GOPRIVATE='${{ secrets.GIT_HOST_ROOT }}'
|
||||||
|
|
||||||
|
echo "Creating local .gitconfig"
|
||||||
|
touch ~/.gitconfig
|
||||||
|
cat > ~/.gitconfig << "EOF"
|
||||||
|
[url "ssh://git@${{ secrets.GIT_HOST_ROOT }}"]
|
||||||
|
insteadOf = https://${{ secrets.GIT_HOST_ROOT }}
|
||||||
|
EOF
|
||||||
|
|
||||||
go test -v ./...
|
go test -v ./...
|
||||||
|
|
||||||
# - name: Run gofmt (optional)
|
|
||||||
# Uncomment to check code formatting with gofmt
|
|
||||||
# run: |
|
|
||||||
# if [ -n "$(gofmt -l.)" ]; then
|
|
||||||
# echo "Go code is not formatted. Please run 'gofmt -w.' to fix it."
|
|
||||||
# exit 1
|
|
||||||
# fi
|
|
||||||
|
|
||||||
# - name: Run golint (optional)
|
|
||||||
# Uncomment to check code style with golint
|
|
||||||
# run: |
|
|
||||||
# if [ -n "$(golint./...)" ]; then
|
|
||||||
# echo "Go code has style issues. Please run 'golint./...' to see them."
|
|
||||||
# exit 1
|
|
||||||
# fi
|
|
||||||
|
|||||||
+2
-1
@@ -1,5 +1,5 @@
|
|||||||
# Multi-stage Dockerfile for Go application
|
# Multi-stage Dockerfile for Go application
|
||||||
FROM golang:1.25.3 AS builder
|
FROM golang:1.26.1 AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -29,6 +29,7 @@ COPY ./internal ./internal
|
|||||||
COPY ./Makefile .
|
COPY ./Makefile .
|
||||||
COPY ./.env .
|
COPY ./.env .
|
||||||
COPY ./migrations ./migrations
|
COPY ./migrations ./migrations
|
||||||
|
COPY ./docs ./docs
|
||||||
|
|
||||||
# Build the application
|
# Build the application
|
||||||
RUN CGO_ENABLED=0 GOOS=linux make build
|
RUN CGO_ENABLED=0 GOOS=linux make build
|
||||||
|
|||||||
@@ -18,3 +18,13 @@ make build
|
|||||||
```
|
```
|
||||||
./textsender-auth -reset-db
|
./textsender-auth -reset-db
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Generate API documentation
|
||||||
|
```
|
||||||
|
go install github.com/swaggo/swag/cmd/swag@latest
|
||||||
|
|
||||||
|
swag init --generalInfo main.go --dir ./cmd/api,./internal/handler --output docs/ --parseDependency --parseInternal
|
||||||
|
```
|
||||||
|
|
||||||
|
The API documentation can be viewed from `http://localhost:9080/swagger/index.html`.
|
||||||
|
|||||||
+41
-4
@@ -12,15 +12,30 @@ import (
|
|||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
"github.com/go-chi/cors"
|
||||||
|
"github.com/swaggo/http-swagger/v2"
|
||||||
|
|
||||||
|
_ "git.kundeng.us/phoenix/textsender-auth/docs"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
database "git.kundeng.us/phoenix/textsender-auth/internal/db"
|
database "git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
mdleware "git.kundeng.us/phoenix/textsender-auth/internal/middleware"
|
mdleware "git.kundeng.us/phoenix/textsender-auth/internal/middleware"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
"git.kundeng.us/phoenix/textsender-auth/internal/services"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// @title textsender-auth
|
||||||
|
// @version 1.0
|
||||||
|
// @description Auth API to send text messages
|
||||||
|
|
||||||
|
// @host localhost:9080
|
||||||
|
// @BasePath /api/v1
|
||||||
|
|
||||||
|
// @securityDefinitions.apikey BearerAuth
|
||||||
|
// @in header
|
||||||
|
// @name Authorization
|
||||||
|
// @description JWT Bearer Token
|
||||||
func main() {
|
func main() {
|
||||||
cfg := config.Load()
|
cfg := config.Load()
|
||||||
if cfg == nil {
|
if cfg == nil {
|
||||||
@@ -59,12 +74,26 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Services
|
// Services
|
||||||
userStore := model.NewUserStore(db.Pool)
|
userStore := store.NewUserStore(db.Pool)
|
||||||
userHandler := handler.NewUserHandler(userStore)
|
serviceStore := store.NewServiceStore(db.Pool)
|
||||||
loginHandler := handler.NewLoginHandler(userStore)
|
|
||||||
|
userHandler := handler.NewUserHandler(cfg, userStore)
|
||||||
|
loginHandler := handler.NewLoginHandler(cfg, userStore)
|
||||||
|
serviceHandler := handler.NewServiceHandler(cfg, serviceStore)
|
||||||
|
refreshHandler := handler.NewRefreshHandler(cfg, userStore, serviceStore)
|
||||||
|
|
||||||
router := chi.NewRouter()
|
router := chi.NewRouter()
|
||||||
|
jwtService := services.NewJWTService(config.GetSecretKey())
|
||||||
|
|
||||||
|
// Configure CORS
|
||||||
|
router.Use(cors.Handler(cors.Options{
|
||||||
|
AllowedOrigins: cfg.AllowedOrigins,
|
||||||
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||||
|
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||||
|
ExposedHeaders: []string{"Link", "X-Total-Count"},
|
||||||
|
AllowCredentials: true,
|
||||||
|
MaxAge: 300, // 5 minutes
|
||||||
|
}))
|
||||||
router.Use(middleware.Logger)
|
router.Use(middleware.Logger)
|
||||||
router.Use(middleware.Recoverer)
|
router.Use(middleware.Recoverer)
|
||||||
router.Use(middleware.Timeout(60 * time.Second))
|
router.Use(middleware.Timeout(60 * time.Second))
|
||||||
@@ -72,6 +101,14 @@ func main() {
|
|||||||
|
|
||||||
router.Method("Post", endpoint.Register, http.HandlerFunc(userHandler.Register))
|
router.Method("Post", endpoint.Register, http.HandlerFunc(userHandler.Register))
|
||||||
router.Method("Post", endpoint.Login, http.HandlerFunc(loginHandler.Login))
|
router.Method("Post", endpoint.Login, http.HandlerFunc(loginHandler.Login))
|
||||||
|
router.Method("Post", endpoint.CreateServiceUser, http.HandlerFunc(serviceHandler.Register))
|
||||||
|
router.Method("Post", endpoint.LoginServiceUser, http.HandlerFunc(serviceHandler.Login))
|
||||||
|
router.Method("Post", endpoint.TokenRefresh, http.HandlerFunc(refreshHandler.Refresh))
|
||||||
|
router.Method("PATCH", endpoint.UpdatePassword, mdleware.AuthMiddleware(jwtService)(http.HandlerFunc(loginHandler.UpdatePassword)))
|
||||||
|
|
||||||
|
router.Method("GET", "/swagger/*", httpSwagger.Handler(
|
||||||
|
httpSwagger.URL(fmt.Sprintf("http://localhost:%s/swagger/doc.json", config.Port)),
|
||||||
|
))
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
|
|||||||
+24
-12
@@ -4,46 +4,57 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
mdleware "git.kundeng.us/phoenix/textsender-auth/internal/middleware"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/services"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
var testRouter *mux.Router
|
var testRouter *chi.Mux
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
cfg := load()
|
cfg := load()
|
||||||
|
|
||||||
db, err := db.NewDatabase(cfg.GetDBConnString())
|
database, err := db.NewDatabase(cfg.GetDBConnString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err.Error())
|
fmt.Println(err.Error())
|
||||||
panic("Failed to initialize database")
|
panic("Failed to initialize database")
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer database.Close()
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err = db.ResetDatabase(ctx)
|
err = database.ResetDatabase(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err.Error())
|
fmt.Println(err.Error())
|
||||||
panic("Failed to initialize database")
|
panic("Failed to initialize database")
|
||||||
}
|
}
|
||||||
|
|
||||||
userStore := model.NewUserStore(db.Pool)
|
userStore := store.NewUserStore(database.Pool)
|
||||||
userHandler := handler.NewUserHandler(userStore)
|
serviceStore := store.NewServiceStore(database.Pool)
|
||||||
loginHandler := handler.NewLoginHandler(userStore)
|
userHandler := handler.NewUserHandler(cfg, userStore)
|
||||||
|
loginHandler := handler.NewLoginHandler(cfg, userStore)
|
||||||
|
serviceHandler := handler.NewServiceHandler(cfg, serviceStore)
|
||||||
|
refreshHandler := handler.NewRefreshHandler(cfg, userStore, serviceStore)
|
||||||
|
|
||||||
testRouter = mux.NewRouter()
|
testRouter = chi.NewRouter()
|
||||||
testRouter.HandleFunc(endpoint.Register, userHandler.Register).Methods("POST")
|
jwtService := services.NewJWTService(config.GetSecretKey())
|
||||||
testRouter.HandleFunc(endpoint.Login, loginHandler.Login).Methods("POST")
|
testRouter.Method("POST", endpoint.Register, http.HandlerFunc(userHandler.Register))
|
||||||
|
testRouter.Method("POST", endpoint.Login, http.HandlerFunc(loginHandler.Login))
|
||||||
|
testRouter.Method("POST", endpoint.CreateServiceUser, http.HandlerFunc(serviceHandler.Register))
|
||||||
|
testRouter.Method("POST", endpoint.LoginServiceUser, http.HandlerFunc(serviceHandler.Login))
|
||||||
|
testRouter.Method("POST", endpoint.TokenRefresh, http.HandlerFunc(refreshHandler.Refresh))
|
||||||
|
testRouter.Method("PATCH", endpoint.UpdatePassword, mdleware.AuthMiddleware(jwtService)(http.HandlerFunc(loginHandler.UpdatePassword)))
|
||||||
|
|
||||||
code := m.Run()
|
code := m.Run()
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
@@ -72,6 +83,7 @@ func load() *config.Config {
|
|||||||
DBConnString: dbConnString,
|
DBConnString: dbConnString,
|
||||||
ServerPort: *port,
|
ServerPort: *port,
|
||||||
ResetDB: *resetDb,
|
ResetDB: *resetDb,
|
||||||
|
EnableRegistration: config.CheckRegistration(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ services:
|
|||||||
|
|
||||||
# PostgreSQL Database Service
|
# PostgreSQL Database Service
|
||||||
auth_db:
|
auth_db:
|
||||||
image: postgres:18.0-alpine # Use an official Postgres image (Alpine variant is smaller)
|
image: postgres:18.3-alpine # Use an official Postgres image (Alpine variant is smaller)
|
||||||
container_name: textsender_auth_db # Optional: Give the container a specific name
|
container_name: textsender_auth_db # Optional: Give the container a specific name
|
||||||
environment:
|
environment:
|
||||||
# These MUST match the user, password, and database name in the DATABASE_URL above
|
# These MUST match the user, password, and database name in the DATABASE_URL above
|
||||||
|
|||||||
+684
@@ -0,0 +1,684 @@
|
|||||||
|
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||||
|
package docs
|
||||||
|
|
||||||
|
import "github.com/swaggo/swag"
|
||||||
|
|
||||||
|
const docTemplate = `{
|
||||||
|
"schemes": {{ marshal .Schemes }},
|
||||||
|
"swagger": "2.0",
|
||||||
|
"info": {
|
||||||
|
"description": "{{escape .Description}}",
|
||||||
|
"title": "{{.Title}}",
|
||||||
|
"contact": {},
|
||||||
|
"version": "{{.Version}}"
|
||||||
|
},
|
||||||
|
"host": "{{.Host}}",
|
||||||
|
"basePath": "{{.BasePath}}",
|
||||||
|
"paths": {
|
||||||
|
"/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginAccount"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Register user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterUser"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Servce login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Service login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a service token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a service user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Register service user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/token/refresh": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Refresh token endpoint (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"refresh"
|
||||||
|
],
|
||||||
|
"summary": "Obtain a refresh token",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to refresh token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/user/name/update": {
|
||||||
|
"patch": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Update the first or last name of a user (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Update name of user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to update name of user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/user/password/update": {
|
||||||
|
"patch": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Update the password of a regular account (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Update Password",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Needed data to update password",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"definitions": {
|
||||||
|
"git_kundeng_us_phoenix_textsender-models_tx0_user.User": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"first_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_login": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginAccount": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RefreshRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RefreshResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponseItem"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponseItem": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/user.ServiceUser"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceLoginRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceLoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdateNameRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"first_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdateNameResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdatePasswordRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"confirmed_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"current_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"updated_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdatePasswordResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"token.Login": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"expires_in": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"issued_at": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"token_type": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user.ServiceUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_login": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"description": "TODO: Remove the omitempty tags at a later point",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"securityDefinitions": {
|
||||||
|
"BearerAuth": {
|
||||||
|
"description": "JWT Bearer Token",
|
||||||
|
"type": "apiKey",
|
||||||
|
"name": "Authorization",
|
||||||
|
"in": "header"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`
|
||||||
|
|
||||||
|
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||||
|
var SwaggerInfo = &swag.Spec{
|
||||||
|
Version: "1.0",
|
||||||
|
Host: "localhost:9080",
|
||||||
|
BasePath: "/api/v1",
|
||||||
|
Schemes: []string{},
|
||||||
|
Title: "textsender-auth",
|
||||||
|
Description: "Auth API to send text messages",
|
||||||
|
InfoInstanceName: "swagger",
|
||||||
|
SwaggerTemplate: docTemplate,
|
||||||
|
LeftDelim: "{{",
|
||||||
|
RightDelim: "}}",
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||||
|
}
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
{
|
||||||
|
"swagger": "2.0",
|
||||||
|
"info": {
|
||||||
|
"description": "Auth API to send text messages",
|
||||||
|
"title": "textsender-auth",
|
||||||
|
"contact": {},
|
||||||
|
"version": "1.0"
|
||||||
|
},
|
||||||
|
"host": "localhost:9080",
|
||||||
|
"basePath": "/api/v1",
|
||||||
|
"paths": {
|
||||||
|
"/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginAccount"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.LoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Register user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterUser"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/login": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Servce login and be given an access token (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Service login",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to obtain a service token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceLoginResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/service/register": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Create a service user that can send texts (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"service users"
|
||||||
|
],
|
||||||
|
"summary": "Register service user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to add user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.ServiceCreationResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/token/refresh": {
|
||||||
|
"post": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Refresh token endpoint (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"refresh"
|
||||||
|
],
|
||||||
|
"summary": "Obtain a refresh token",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to refresh token",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.RefreshResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/user/name/update": {
|
||||||
|
"patch": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Update the first or last name of a user (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Update name of user",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Data to update name of user",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdateNameResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/user/password/update": {
|
||||||
|
"patch": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"BearerAuth": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Update the password of a regular account (requires JWT)",
|
||||||
|
"consumes": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"application/json"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"users"
|
||||||
|
],
|
||||||
|
"summary": "Update Password",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"description": "Needed data to update password",
|
||||||
|
"name": "request",
|
||||||
|
"in": "body",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordRequest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "Bad Request",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal Server Error",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/handler.UpdatePasswordResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"definitions": {
|
||||||
|
"git_kundeng_us_phoenix_textsender-models_tx0_user.User": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"first_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_login": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginAccount": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.LoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RefreshRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RefreshResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/handler.RegisterResponseItem"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterResponseItem": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.RegisterUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"phone_number": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceCreationResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/user.ServiceUser"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceLoginRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.ServiceLoginResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/token.Login"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdateNameRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"first_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdateNameResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdatePasswordRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"confirmed_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"current_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"updated_password": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handler.UpdatePasswordResponse": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"token.Login": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"access_token": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"expires_in": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"issued_at": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"token_type": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user.ServiceUser": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"created": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"last_login": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"passphrase": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"description": "TODO: Remove the omitempty tags at a later point",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"securityDefinitions": {
|
||||||
|
"BearerAuth": {
|
||||||
|
"description": "JWT Bearer Token",
|
||||||
|
"type": "apiKey",
|
||||||
|
"name": "Authorization",
|
||||||
|
"in": "header"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
basePath: /api/v1
|
||||||
|
definitions:
|
||||||
|
git_kundeng_us_phoenix_textsender-models_tx0_user.User:
|
||||||
|
properties:
|
||||||
|
created:
|
||||||
|
type: string
|
||||||
|
first_name:
|
||||||
|
type: string
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
last_login:
|
||||||
|
type: string
|
||||||
|
last_name:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
phone_number:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.LoginAccount:
|
||||||
|
properties:
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.LoginResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/token.Login'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RefreshRequest:
|
||||||
|
properties:
|
||||||
|
access_token:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RefreshResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/token.Login'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponseItem'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterResponseItem:
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
phone_number:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.RegisterUser:
|
||||||
|
properties:
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
phone_number:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceCreationRequest:
|
||||||
|
properties:
|
||||||
|
passphrase:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceCreationResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/user.ServiceUser'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceLoginRequest:
|
||||||
|
properties:
|
||||||
|
passphrase:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.ServiceLoginResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/token.Login'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.UpdateNameRequest:
|
||||||
|
properties:
|
||||||
|
first_name:
|
||||||
|
type: string
|
||||||
|
last_name:
|
||||||
|
type: string
|
||||||
|
user_id:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.UpdateNameResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.UpdatePasswordRequest:
|
||||||
|
properties:
|
||||||
|
confirmed_password:
|
||||||
|
type: string
|
||||||
|
current_password:
|
||||||
|
type: string
|
||||||
|
updated_password:
|
||||||
|
type: string
|
||||||
|
user_id:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
handler.UpdatePasswordResponse:
|
||||||
|
properties:
|
||||||
|
data:
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/git_kundeng_us_phoenix_textsender-models_tx0_user.User'
|
||||||
|
type: array
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
token.Login:
|
||||||
|
properties:
|
||||||
|
access_token:
|
||||||
|
type: string
|
||||||
|
expires_in:
|
||||||
|
type: integer
|
||||||
|
issued_at:
|
||||||
|
type: integer
|
||||||
|
token_type:
|
||||||
|
type: string
|
||||||
|
user_id:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
user.ServiceUser:
|
||||||
|
properties:
|
||||||
|
created:
|
||||||
|
type: string
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
last_login:
|
||||||
|
type: string
|
||||||
|
passphrase:
|
||||||
|
type: string
|
||||||
|
username:
|
||||||
|
description: 'TODO: Remove the omitempty tags at a later point'
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
|
host: localhost:9080
|
||||||
|
info:
|
||||||
|
contact: {}
|
||||||
|
description: Auth API to send text messages
|
||||||
|
title: textsender-auth
|
||||||
|
version: "1.0"
|
||||||
|
paths:
|
||||||
|
/login:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Login and be given an access token (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to obtain a token
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginAccount'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.LoginResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Login
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
/register:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Create a user that can send texts (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to add user
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterUser'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
"403":
|
||||||
|
description: Forbidden
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RegisterResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Register user
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
/service/login:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Servce login and be given an access token (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to obtain a service token
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceLoginRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceLoginResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceLoginResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Service login
|
||||||
|
tags:
|
||||||
|
- service users
|
||||||
|
/service/register:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Create a service user that can send texts (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to add user
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
"403":
|
||||||
|
description: Forbidden
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.ServiceCreationResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Register service user
|
||||||
|
tags:
|
||||||
|
- service users
|
||||||
|
/token/refresh:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Refresh token endpoint (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to refresh token
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RefreshRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RefreshResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RefreshResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.RefreshResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Obtain a refresh token
|
||||||
|
tags:
|
||||||
|
- refresh
|
||||||
|
/user/name/update:
|
||||||
|
patch:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Update the first or last name of a user (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Data to update name of user
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdateNameRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdateNameResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdateNameResponse'
|
||||||
|
"403":
|
||||||
|
description: Forbidden
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdateNameResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdateNameResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Update name of user
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
/user/password/update:
|
||||||
|
patch:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Update the password of a regular account (requires JWT)
|
||||||
|
parameters:
|
||||||
|
- description: Needed data to update password
|
||||||
|
in: body
|
||||||
|
name: request
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdatePasswordRequest'
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdatePasswordResponse'
|
||||||
|
"400":
|
||||||
|
description: Bad Request
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdatePasswordResponse'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/handler.UpdatePasswordResponse'
|
||||||
|
security:
|
||||||
|
- BearerAuth: []
|
||||||
|
summary: Update Password
|
||||||
|
tags:
|
||||||
|
- users
|
||||||
|
securityDefinitions:
|
||||||
|
BearerAuth:
|
||||||
|
description: JWT Bearer Token
|
||||||
|
in: header
|
||||||
|
name: Authorization
|
||||||
|
type: apiKey
|
||||||
|
swagger: "2.0"
|
||||||
@@ -1,28 +1,45 @@
|
|||||||
module git.kundeng.us/phoenix/textsender-auth
|
module git.kundeng.us/phoenix/textsender-auth
|
||||||
|
|
||||||
go 1.25.3
|
go 1.26.1
|
||||||
|
|
||||||
require (
|
require (
|
||||||
git.kundeng.us/phoenix/textsender-models v0.0.6-main-28b29802b9-556
|
git.kundeng.us/phoenix/textsender-models v0.2.0
|
||||||
github.com/go-chi/chi/v5 v5.2.3
|
github.com/go-chi/chi/v5 v5.2.5
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
github.com/go-chi/cors v1.2.2
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/gorilla/mux v1.8.1
|
github.com/jackc/pgx/v5 v5.9.1
|
||||||
github.com/jackc/pgx/v5 v5.7.5
|
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
golang.org/x/crypto v0.42.0
|
github.com/swaggo/http-swagger/v2 v2.0.2
|
||||||
|
github.com/swaggo/swag v1.16.6
|
||||||
|
golang.org/x/crypto v0.49.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/go-openapi/jsonpointer v0.22.5 // indirect
|
||||||
|
github.com/go-openapi/jsonreference v0.21.5 // indirect
|
||||||
|
github.com/go-openapi/spec v0.22.4 // indirect
|
||||||
|
github.com/go-openapi/swag/conv v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/jsonutils v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/loading v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/stringutils v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/typeutils v0.25.5 // indirect
|
||||||
|
github.com/go-openapi/swag/yamlutils v0.25.5 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
github.com/kr/text v0.2.0 // indirect
|
github.com/kr/text v0.2.0 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
golang.org/x/sync v0.17.0 // indirect
|
github.com/swaggo/files/v2 v2.0.2 // indirect
|
||||||
golang.org/x/text v0.29.0 // indirect
|
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||||
|
golang.org/x/mod v0.34.0 // indirect
|
||||||
|
golang.org/x/sync v0.20.0 // indirect
|
||||||
|
golang.org/x/text v0.35.0 // indirect
|
||||||
|
golang.org/x/tools v0.43.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,23 +1,54 @@
|
|||||||
git.kundeng.us/phoenix/textsender-models v0.0.6-main-28b29802b9-556 h1:2NI8cXaxt2rsXrhy/rDhgoOzvjLQwbhwr4nv2g35Ah8=
|
git.kundeng.us/phoenix/textsender-models v0.2.0 h1:smz8Fs8VOs1Ya23txbOM0YPRidZIsM0yE9unHF0D/nQ=
|
||||||
git.kundeng.us/phoenix/textsender-models v0.0.6-main-28b29802b9-556/go.mod h1:lx5MCnOgGgsdpwzrfi9uph5xmkeb6H8AuexUNGss2no=
|
git.kundeng.us/phoenix/textsender-models v0.2.0/go.mod h1:3CkqA/HFKPhpMYxkKn5uVbZEzEbG3sofLZE8pZ1BHO4=
|
||||||
|
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||||
|
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
||||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||||
|
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
|
||||||
|
github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0=
|
||||||
|
github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE=
|
||||||
|
github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw=
|
||||||
|
github.com/go-openapi/spec v0.22.4 h1:4pxGjipMKu0FzFiu/DPwN3CTBRlVM2yLf/YTWorYfDQ=
|
||||||
|
github.com/go-openapi/spec v0.22.4/go.mod h1:WQ6Ai0VPWMZgMT4XySjlRIE6GP1bGQOtEThn3gcWLtQ=
|
||||||
|
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
|
||||||
|
github.com/go-openapi/swag/conv v0.25.5 h1:wAXBYEXJjoKwE5+vc9YHhpQOFj2JYBMF2DUi+tGu97g=
|
||||||
|
github.com/go-openapi/swag/conv v0.25.5/go.mod h1:CuJ1eWvh1c4ORKx7unQnFGyvBbNlRKbnRyAvDvzWA4k=
|
||||||
|
github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo=
|
||||||
|
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
|
||||||
|
github.com/go-openapi/swag/jsonutils v0.25.5 h1:XUZF8awQr75MXeC+/iaw5usY/iM7nXPDwdG3Jbl9vYo=
|
||||||
|
github.com/go-openapi/swag/jsonutils v0.25.5/go.mod h1:48FXUaz8YsDAA9s5AnaUvAmry1UcLcNVWUjY42XkrN4=
|
||||||
|
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5 h1:SX6sE4FrGb4sEnnxbFL/25yZBb5Hcg1inLeErd86Y1U=
|
||||||
|
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5/go.mod h1:/2KvOTrKWjVA5Xli3DZWdMCZDzz3uV/T7bXwrKWPquo=
|
||||||
|
github.com/go-openapi/swag/loading v0.25.5 h1:odQ/umlIZ1ZVRteI6ckSrvP6e2w9UTF5qgNdemJHjuU=
|
||||||
|
github.com/go-openapi/swag/loading v0.25.5/go.mod h1:I8A8RaaQ4DApxhPSWLNYWh9NvmX2YKMoB9nwvv6oW6g=
|
||||||
|
github.com/go-openapi/swag/stringutils v0.25.5 h1:NVkoDOA8YBgtAR/zvCx5rhJKtZF3IzXcDdwOsYzrB6M=
|
||||||
|
github.com/go-openapi/swag/stringutils v0.25.5/go.mod h1:PKK8EZdu4QJq8iezt17HM8RXnLAzY7gW0O1KKarrZII=
|
||||||
|
github.com/go-openapi/swag/typeutils v0.25.5 h1:EFJ+PCga2HfHGdo8s8VJXEVbeXRCYwzzr9u4rJk7L7E=
|
||||||
|
github.com/go-openapi/swag/typeutils v0.25.5/go.mod h1:itmFmScAYE1bSD8C4rS0W+0InZUBrB2xSPbWt6DLGuc=
|
||||||
|
github.com/go-openapi/swag/yamlutils v0.25.5 h1:kASCIS+oIeoc55j28T4o8KwlV2S4ZLPT6G0iq2SSbVQ=
|
||||||
|
github.com/go-openapi/swag/yamlutils v0.25.5/go.mod h1:Gek1/SjjfbYvM+Iq4QGwa/2lEXde9n2j4a3wI3pNuOQ=
|
||||||
|
github.com/go-openapi/testify/enable/yaml/v2 v2.4.0 h1:7SgOMTvJkM8yWrQlU8Jm18VeDPuAvB/xWrdxFJkoFag=
|
||||||
|
github.com/go-openapi/testify/enable/yaml/v2 v2.4.0/go.mod h1:14iV8jyyQlinc9StD7w1xVPW3CO3q1Gj04Jy//Kw4VM=
|
||||||
|
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
|
||||||
|
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
|
||||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
github.com/jackc/pgx/v5 v5.7.5 h1:JHGfMnQY+IEtGM63d+NGMjoRpysB2JBwDr5fsngwmJs=
|
github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc=
|
||||||
github.com/jackc/pgx/v5 v5.7.5/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
@@ -35,12 +66,24 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
|||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
github.com/swaggo/files/v2 v2.0.2 h1:Bq4tgS/yxLB/3nwOMcul5oLEUKa877Ykgz3CJMVbQKU=
|
||||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
github.com/swaggo/files/v2 v2.0.2/go.mod h1:TVqetIzZsO9OhHX1Am9sRf9LdrFZqoK49N37KON/jr0=
|
||||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
github.com/swaggo/http-swagger/v2 v2.0.2 h1:FKCdLsl+sFCx60KFsyM0rDarwiUSZ8DqbfSyIKC9OBg=
|
||||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeAHmgIyooa4xm3AQ=
|
||||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||||
|
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||||
|
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
|
||||||
|
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
|
||||||
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||||
|
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||||
|
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
|
||||||
|
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
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/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
@@ -16,6 +18,8 @@ type Config struct {
|
|||||||
DBConnString string
|
DBConnString string
|
||||||
ServerPort string
|
ServerPort string
|
||||||
ResetDB bool
|
ResetDB bool
|
||||||
|
EnableRegistration bool
|
||||||
|
AllowedOrigins []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionInfo struct {
|
type ConnectionInfo struct {
|
||||||
@@ -52,16 +56,35 @@ func Load() *Config {
|
|||||||
|
|
||||||
err := godotenv.Load()
|
err := godotenv.Load()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
envPath := path.Join(cwd, "../..", ".env")
|
||||||
|
if err = godotenv.Load(envPath); err != nil {
|
||||||
|
prevPath := path.Join(envPath, "../..", ".env")
|
||||||
|
if err = godotenv.Load(prevPath); err != nil {
|
||||||
log.Fatal("Error loading .env file")
|
log.Fatal("Error loading .env file")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
unpackedConnString := UnpackDBConnString()
|
unpackedConnString := UnpackDBConnString()
|
||||||
dbConnString := unpackedConnString.Parse()
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
allowedOrigins := unpackAllowedOrigin()
|
||||||
|
|
||||||
|
if len(allowedOrigins) > 0 {
|
||||||
return &Config{
|
return &Config{
|
||||||
DBConnString: dbConnString,
|
DBConnString: dbConnString,
|
||||||
ServerPort: *port,
|
ServerPort: *port,
|
||||||
ResetDB: *resetDb,
|
ResetDB: *resetDb,
|
||||||
|
EnableRegistration: CheckRegistration(),
|
||||||
|
AllowedOrigins: allowedOrigins,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &Config{
|
||||||
|
DBConnString: dbConnString,
|
||||||
|
ServerPort: *port,
|
||||||
|
ResetDB: *resetDb,
|
||||||
|
EnableRegistration: CheckRegistration(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +143,26 @@ func UnpackDBConnString() (connInfo ConnectionInfo) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func unpackAllowedOrigin() []string {
|
||||||
|
allowedOriginsRaw := os.Getenv("ALLOWED_ORIGINS")
|
||||||
|
allowedOriginsSplit := strings.Split(allowedOriginsRaw, ",")
|
||||||
|
return allowedOriginsSplit
|
||||||
|
}
|
||||||
|
|
||||||
|
func CheckRegistration() bool {
|
||||||
|
if flagValue := os.Getenv("ENABLE_REGISTRATION"); flagValue != "" {
|
||||||
|
if val := strings.ToUpper(flagValue); val == "TRUE" {
|
||||||
|
return true
|
||||||
|
} else if val == "FALSE" {
|
||||||
|
return false
|
||||||
|
} else {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Config) GetDBConnString() string {
|
func (c *Config) GetDBConnString() string {
|
||||||
return c.DBConnString
|
return c.DBConnString
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
package endpoint
|
package endpoint
|
||||||
|
|
||||||
// Endpoint for registering a user
|
const (
|
||||||
const Register = "/api/v1/register"
|
// Endpoint for registering a user
|
||||||
const Login = "/api/v1/login"
|
Register = "/api/v1/register"
|
||||||
|
Login = "/api/v1/login"
|
||||||
|
UpdatePassword = "/api/v1/user/password/update"
|
||||||
|
UpdateName = "/api/v1/user/name/update"
|
||||||
|
|
||||||
|
CreateServiceUser = "/api/v1/service/register"
|
||||||
|
LoginServiceUser = "/api/v1/service/login"
|
||||||
|
|
||||||
|
TokenRefresh = "/api/v1/token/refresh"
|
||||||
|
)
|
||||||
|
|||||||
+125
-14
@@ -1,16 +1,28 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/token"
|
"git.kundeng.us/phoenix/textsender-models/tx0/token"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type LoginHandler struct {
|
||||||
|
Config *config.Config
|
||||||
|
UserStore store.UserStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoginHandler(cfg *config.Config, userStore store.UserStore) *LoginHandler {
|
||||||
|
return &LoginHandler{Config: cfg, UserStore: userStore}
|
||||||
|
}
|
||||||
|
|
||||||
type LoginAccount struct {
|
type LoginAccount struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
@@ -21,14 +33,18 @@ type LoginResponse struct {
|
|||||||
Data []token.Login `json:"data"`
|
Data []token.Login `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginHandler struct {
|
// Login godoc
|
||||||
UserStore model.UserStore
|
// @Summary Login
|
||||||
}
|
// @Description Login and be given an access token (requires JWT)
|
||||||
|
// @Tags users
|
||||||
func NewLoginHandler(userStore model.UserStore) *LoginHandler {
|
// @Accept json
|
||||||
return &LoginHandler{UserStore: userStore}
|
// @Produce json
|
||||||
}
|
// @Security BearerAuth
|
||||||
|
// @Param request body LoginAccount true "Data to obtain a token"
|
||||||
|
// @Success 200 {object} LoginResponse
|
||||||
|
// @Failure 400 {object} LoginResponse
|
||||||
|
// @Failure 500 {object} LoginResponse
|
||||||
|
// @Router /login [post]
|
||||||
func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||||
var req LoginAccount
|
var req LoginAccount
|
||||||
if err := ExtractFromRequest(r, &req); err != nil {
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
@@ -42,7 +58,7 @@ func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
||||||
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
||||||
fmt.Printf("Error: %v", err)
|
log.Println("Error:", err)
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
} else {
|
} else {
|
||||||
@@ -54,20 +70,32 @@ func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
} else {
|
} else {
|
||||||
hashing := utility.HashMash{Password: req.Password}
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(req.Password); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
||||||
|
lastLogin := time.Now()
|
||||||
var tokGen utility.TokenGenerator
|
var tokGen utility.TokenGenerator
|
||||||
secretKey := config.GetSecretKey()
|
secretKey := config.GetSecretKey()
|
||||||
tokGen.SetSecretKey(secretKey)
|
tokGen.SetSecretKey(secretKey)
|
||||||
if myToken, err := tokGen.GenerateToken(*user); err != nil {
|
if myToken, err := tokGen.GenerateToken(*user); err != nil {
|
||||||
fmt.Println(err.Error())
|
log.Println(err.Error())
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = "Error generating token"
|
resp.Message = "Error generating token"
|
||||||
} else {
|
} else {
|
||||||
|
log.Println("Updating user's last login")
|
||||||
|
if rowsAffected, err := l.UserStore.UpdateLastLogin(ctx, user.Id, lastLogin); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
log.Println("Rows updated:", rowsAffected)
|
||||||
statusCode = http.StatusOK
|
statusCode = http.StatusOK
|
||||||
resp.Data = append(resp.Data, *myToken)
|
resp.Data = append(resp.Data, *myToken)
|
||||||
resp.Message = "Successful"
|
resp.Message = "Successful"
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
statusCode = http.StatusNotFound
|
statusCode = http.StatusNotFound
|
||||||
resp.Message = "User not found"
|
resp.Message = "User not found"
|
||||||
@@ -75,6 +103,89 @@ func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdatePasswordRequest struct {
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
CurrentPassword string `json:"current_password"`
|
||||||
|
UpdatedPassword string `json:"updated_password"`
|
||||||
|
ConfirmedPassword string `json:"confirmed_password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdatePasswordResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []user.User `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePassword godoc
|
||||||
|
// @Summary Update Password
|
||||||
|
// @Description Update the password of a regular account (requires JWT)
|
||||||
|
// @Tags users
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body UpdatePasswordRequest true "Needed data to update password"
|
||||||
|
// @Success 200 {object} UpdatePasswordResponse
|
||||||
|
// @Failure 400 {object} UpdatePasswordResponse
|
||||||
|
// @Failure 500 {object} UpdatePasswordResponse
|
||||||
|
// @Router /user/password/update [patch]
|
||||||
|
func (l *LoginHandler) UpdatePassword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req UpdatePasswordRequest
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp UpdatePasswordResponse
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if usr, err := l.UserStore.GetUserByID(ctx, req.UserId); err != nil {
|
||||||
|
log.Println("Error:", err)
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(req.CurrentPassword); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if hashing.CheckPasswordHash(req.CurrentPassword, usr.Password) {
|
||||||
|
if req.UpdatedPassword == req.ConfirmedPassword {
|
||||||
|
// Hash password
|
||||||
|
err := hashing.SetPassword(req.UpdatedPassword)
|
||||||
|
hashedPassword, err := hashing.HashPassword()
|
||||||
|
if err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
// Update user password
|
||||||
|
usr.Password = hashedPassword
|
||||||
|
// Save user in DB
|
||||||
|
if rowsAffected, err := l.UserStore.UpdatePassword(ctx, usr.Id, usr.Password); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
log.Println("Rows affected:", rowsAffected)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *usr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Passwords do not match"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "User not found"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
RespondWithJson(w, statusCode, &resp)
|
RespondWithJson(w, statusCode, &resp)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,27 +12,21 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestLogin(t *testing.T) {
|
func TestLogin(t *testing.T) {
|
||||||
mockstore := NewMockUserStore()
|
cfg := GetConfig()
|
||||||
handler := NewLoginHandler(mockstore)
|
mockstore := mock.NewMockUserStore()
|
||||||
|
handler := NewLoginHandler(cfg, mockstore)
|
||||||
testUser := GetTestUser()
|
|
||||||
unhashedPassword := testUser.Password
|
|
||||||
hashing := utility.HashMash{Password: testUser.Password}
|
|
||||||
hashedPassword, err := hashing.HashPassword()
|
|
||||||
assert.NoError(t, err)
|
|
||||||
|
|
||||||
testUser.Password = hashedPassword
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
mockstore.CreateUser(ctx, &testUser)
|
testUser, unhashedPassword, err := createUser(ctx, mockstore)
|
||||||
|
assert.NoError(t, err, "Error Creating user")
|
||||||
|
|
||||||
loginUser := LoginAccount{Username: testUser.Username, Password: unhashedPassword}
|
loginUser := LoginAccount{Username: testUser.Username, Password: *unhashedPassword}
|
||||||
jsonValue, _ := json.Marshal(loginUser)
|
jsonValue, _ := json.Marshal(loginUser)
|
||||||
|
|
||||||
req, _ := http.NewRequest("POST", endpoint.Login, strings.NewReader(string(jsonValue)))
|
req, _ := http.NewRequest("POST", endpoint.Login, strings.NewReader(string(jsonValue)))
|
||||||
@@ -48,3 +42,29 @@ func TestLogin(t *testing.T) {
|
|||||||
|
|
||||||
assert.NotEmpty(t, response.Data, "An access token should have been returned")
|
assert.NotEmpty(t, response.Data, "An access token should have been returned")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUpdatePassword(t *testing.T) {
|
||||||
|
cfg := GetConfig()
|
||||||
|
mockstore := mock.NewMockUserStore()
|
||||||
|
handler := NewLoginHandler(cfg, mockstore)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
testUser, unhashedPassword, err := createUser(ctx, mockstore)
|
||||||
|
assert.NoError(t, err, "Error Creating user")
|
||||||
|
assert.NotNil(t, testUser, "User should not be nil")
|
||||||
|
|
||||||
|
updatedPassword := "TakeATrip2yonder!"
|
||||||
|
newPassword := UpdatePasswordRequest{UserId: testUser.Id, CurrentPassword: *unhashedPassword, UpdatedPassword: updatedPassword, ConfirmedPassword: updatedPassword}
|
||||||
|
jsonValue, _ := json.Marshal(newPassword)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("PATCH", endpoint.UpdatePassword, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.UpdatePassword(rr, req)
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response UpdatePasswordResponse
|
||||||
|
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/token"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RefreshHandler struct {
|
||||||
|
Config *config.Config
|
||||||
|
UserStore store.UserStore
|
||||||
|
ServiceStore store.ServiceStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRefreshHandler(cfg *config.Config, userStore store.UserStore, serviceStore store.ServiceStore) *RefreshHandler {
|
||||||
|
return &RefreshHandler{Config: cfg, UserStore: userStore, ServiceStore: serviceStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RefreshRequest struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RefreshResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []*token.Login `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh godoc
|
||||||
|
// @Summary Obtain a refresh token
|
||||||
|
// @Description Refresh token endpoint (requires JWT)
|
||||||
|
// @Tags refresh
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body RefreshRequest true "Data to refresh token"
|
||||||
|
// @Success 200 {object} RefreshResponse
|
||||||
|
// @Failure 400 {object} RefreshResponse
|
||||||
|
// @Failure 500 {object} RefreshResponse
|
||||||
|
// @Router /token/refresh [post]
|
||||||
|
func (rh *RefreshHandler) Refresh(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req RefreshRequest
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp RefreshResponse
|
||||||
|
|
||||||
|
secretKey := config.GetSecretKey()
|
||||||
|
tokGen := utility.TokenGenerator{}
|
||||||
|
tokGen.SetSecretKey(secretKey)
|
||||||
|
tokGen.SetHourOffset(12)
|
||||||
|
if verified, err := tokGen.VerifyToken(req.AccessToken); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if verified {
|
||||||
|
if id, err := tokGen.ExtractIdFromToken(req.AccessToken); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
if usr, err := rh.UserStore.GetUserByID(ctx, id); err != nil || usr == nil {
|
||||||
|
if serviceUsr, err := rh.ServiceStore.GetWithId(ctx, id); err != nil || serviceUsr == nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if myToken, err := tokGen.GenerateToken(serviceUsr); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, myToken)
|
||||||
|
resp.Message = "Successful"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if myToken, err := tokGen.GenerateToken(usr); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, myToken)
|
||||||
|
resp.Message = "Successful"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Unverified"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRefreshTokenWithMock(t *testing.T) {
|
||||||
|
var serviceUser user.ServiceUser
|
||||||
|
var hashedPassword string
|
||||||
|
var err error
|
||||||
|
unhashed := "A9328nr29nudx3292m320!"
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(unhashed); err != nil {
|
||||||
|
assert.NoError(t, err, "Error setting password")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hashedPassword, err = hashing.HashPassword(); err != nil {
|
||||||
|
assert.NoError(t, err, "Error hashing password: %v", err)
|
||||||
|
} else {
|
||||||
|
serviceUser.Passphrase = hashedPassword
|
||||||
|
}
|
||||||
|
serviceUser.Username = "swoon"
|
||||||
|
ctx := t.Context()
|
||||||
|
mockStore := mock.NewMockServiceUserStore()
|
||||||
|
userStore := mock.NewMockUserStore()
|
||||||
|
|
||||||
|
if err := mockStore.Create(ctx, &serviceUser); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating service user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := GetConfig()
|
||||||
|
handler := NewServiceHandler(cfg, mockStore)
|
||||||
|
testService := ServiceLoginRequest{Username: serviceUser.Username, Passphrase: unhashed}
|
||||||
|
jsonValue, err := json.Marshal(testService)
|
||||||
|
assert.NoError(t, err, "Error marshaling request")
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.LoginServiceUser, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.Login(rr, req)
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response ServiceLoginResponse
|
||||||
|
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
accessToken := response.Data[0].AccessToken
|
||||||
|
|
||||||
|
testReq := RefreshRequest{AccessToken: accessToken}
|
||||||
|
jsonValue, err = json.Marshal(testReq)
|
||||||
|
assert.NoError(t, err, "Error marshaling request")
|
||||||
|
|
||||||
|
newHandler := NewRefreshHandler(cfg, userStore, mockStore)
|
||||||
|
req, _ = http.NewRequest("POST", endpoint.TokenRefresh, strings.NewReader(string(jsonValue)))
|
||||||
|
rr = httptest.NewRecorder()
|
||||||
|
|
||||||
|
newHandler.Refresh(rr, req)
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
}
|
||||||
+111
-11
@@ -2,15 +2,26 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type UserHandler struct {
|
||||||
|
Config *config.Config
|
||||||
|
UserStore store.UserStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserHandler(cfg *config.Config, userStore store.UserStore) *UserHandler {
|
||||||
|
return &UserHandler{Config: cfg, UserStore: userStore}
|
||||||
|
}
|
||||||
|
|
||||||
type RegisterUser struct {
|
type RegisterUser struct {
|
||||||
PhoneNumber string `json:"phone_number"`
|
PhoneNumber string `json:"phone_number"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
@@ -28,14 +39,19 @@ type RegisterResponse struct {
|
|||||||
Data []RegisterResponseItem `json:"data"`
|
Data []RegisterResponseItem `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserHandler struct {
|
// Register godoc
|
||||||
UserStore model.UserStore
|
// @Summary Register user
|
||||||
}
|
// @Description Create a user that can send texts (requires JWT)
|
||||||
|
// @Tags users
|
||||||
func NewUserHandler(userStore model.UserStore) *UserHandler {
|
// @Accept json
|
||||||
return &UserHandler{UserStore: userStore}
|
// @Produce json
|
||||||
}
|
// @Security BearerAuth
|
||||||
|
// @Param request body RegisterUser true "Data to add user"
|
||||||
|
// @Success 200 {object} RegisterResponse
|
||||||
|
// @Failure 400 {object} RegisterResponse
|
||||||
|
// @Failure 403 {object} RegisterResponse
|
||||||
|
// @Failure 500 {object} RegisterResponse
|
||||||
|
// @Router /register [post]
|
||||||
func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||||
var req RegisterUser
|
var req RegisterUser
|
||||||
err := ExtractFromRequest(r, &req)
|
err := ExtractFromRequest(r, &req)
|
||||||
@@ -48,6 +64,12 @@ func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var statusCode int
|
var statusCode int
|
||||||
var resp RegisterResponse
|
var resp RegisterResponse
|
||||||
|
if !u.Config.EnableRegistration {
|
||||||
|
statusCode = http.StatusForbidden
|
||||||
|
resp.Message = "Registration disabled"
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
return
|
||||||
|
}
|
||||||
user := user.User{Username: req.Username, Password: req.Password, PhoneNumber: req.PhoneNumber}
|
user := user.User{Username: req.Username, Password: req.Password, PhoneNumber: req.PhoneNumber}
|
||||||
|
|
||||||
fmt.Println("Username:", user.Username)
|
fmt.Println("Username:", user.Username)
|
||||||
@@ -64,7 +86,11 @@ func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
statusCode = http.StatusBadRequest
|
statusCode = http.StatusBadRequest
|
||||||
resp.Message = "Failure in creating User"
|
resp.Message = "Failure in creating User"
|
||||||
} else {
|
} else {
|
||||||
hashing := utility.HashMash{Password: user.Password}
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(req.Password); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
if hashedPassword, err := hashing.HashPassword(); err != nil {
|
if hashedPassword, err := hashing.HashPassword(); err != nil {
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
@@ -81,8 +107,82 @@ func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
RespondWithJson(w, statusCode, &resp)
|
RespondWithJson(w, statusCode, &resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UpdateNameRequest struct {
|
||||||
|
Firstname *string `json:"first_name,omitempty"`
|
||||||
|
Lastname *string `json:"last_name,omitempty"`
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateNameResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []*user.User `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateName godoc
|
||||||
|
// @Summary Update name of user
|
||||||
|
// @Description Update the first or last name of a user (requires JWT)
|
||||||
|
// @Tags users
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body UpdateNameRequest true "Data to update name of user"
|
||||||
|
// @Success 200 {object} UpdateNameResponse
|
||||||
|
// @Failure 400 {object} UpdateNameResponse
|
||||||
|
// @Failure 403 {object} UpdateNameResponse
|
||||||
|
// @Failure 500 {object} UpdateNameResponse
|
||||||
|
// @Router /user/name/update [patch]
|
||||||
|
func (u *UserHandler) UpdateName(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req UpdateNameRequest
|
||||||
|
err := ExtractFromRequest(r, &req)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp UpdateNameResponse
|
||||||
|
updateFirstname := req.Firstname != nil && len(*req.Firstname) > 0
|
||||||
|
updateLastname := req.Lastname != nil && len(*req.Lastname) > 0
|
||||||
|
|
||||||
|
if req.UserId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "User Id not provided"
|
||||||
|
} else if !updateFirstname && !updateLastname {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "No name provided"
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
if usr, err := u.UserStore.GetUserByID(ctx, req.UserId); err != nil {
|
||||||
|
log.Println("Error:", err)
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if usr == nil {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "User not found"
|
||||||
|
} else {
|
||||||
|
// Add query to update names
|
||||||
|
if rowsAffected, err := u.UserStore.UpdateName(ctx, req.Firstname, req.Lastname, usr); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
log.Println("Rows updated:", rowsAffected)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, usr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,11 +10,13 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCreateUserWithMock(t *testing.T) {
|
func TestCreateUserWithMock(t *testing.T) {
|
||||||
mockstore := NewMockUserStore()
|
cfg := GetConfig()
|
||||||
handler := NewUserHandler(mockstore)
|
mockstore := mock.NewMockUserStore()
|
||||||
|
handler := NewUserHandler(cfg, mockstore)
|
||||||
|
|
||||||
testUser := GetTestUser()
|
testUser := GetTestUser()
|
||||||
jsonValue, _ := json.Marshal(testUser)
|
jsonValue, _ := json.Marshal(testUser)
|
||||||
@@ -32,3 +34,32 @@ func TestCreateUserWithMock(t *testing.T) {
|
|||||||
|
|
||||||
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUpdateNameOfUser(t *testing.T) {
|
||||||
|
ctx := t.Context()
|
||||||
|
cfg := GetConfig()
|
||||||
|
userStore := mock.NewMockUserStore()
|
||||||
|
|
||||||
|
usr := GetTestUser()
|
||||||
|
if err := userStore.CreateUser(ctx, &usr); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating user")
|
||||||
|
}
|
||||||
|
|
||||||
|
testNameChange := UpdateNameRequest{}
|
||||||
|
testNameChange.Firstname = &[]string{"Bob"}[0]
|
||||||
|
testNameChange.Lastname = &[]string{"De-Buildor"}[0]
|
||||||
|
testNameChange.UserId = usr.Id
|
||||||
|
jsonValue, _ := json.Marshal(testNameChange)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("PATCH", endpoint.UpdateName, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler := NewUserHandler(cfg, userStore)
|
||||||
|
handler.UpdateName(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response UpdateNameResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/token"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServiceHandler struct {
|
||||||
|
Config *config.Config
|
||||||
|
ServiceStore store.ServiceStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServiceHandler(cfg *config.Config, serviceStore store.ServiceStore) *ServiceHandler {
|
||||||
|
return &ServiceHandler{Config: cfg, ServiceStore: serviceStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceCreationRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Passphrase string `json:"passphrase"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceCreationResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []*user.ServiceUser `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register godoc
|
||||||
|
// @Summary Register service user
|
||||||
|
// @Description Create a service user that can send texts (requires JWT)
|
||||||
|
// @Tags service users
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body ServiceCreationRequest true "Data to add user"
|
||||||
|
// @Success 200 {object} ServiceCreationResponse
|
||||||
|
// @Failure 400 {object} ServiceCreationResponse
|
||||||
|
// @Failure 403 {object} ServiceCreationResponse
|
||||||
|
// @Failure 500 {object} ServiceCreationResponse
|
||||||
|
// @Router /service/register [post]
|
||||||
|
func (s *ServiceHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req ServiceCreationRequest
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp ServiceCreationResponse
|
||||||
|
if !s.Config.EnableRegistration {
|
||||||
|
statusCode = http.StatusForbidden
|
||||||
|
resp.Message = "Registration disabled"
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
if exists, err := s.ServiceStore.CheckWithUsername(ctx, req.Username); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if exists {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Service user already exists"
|
||||||
|
} else {
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(req.Passphrase); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if hashedPassword, err := hashing.HashPassword(); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
serviceUser := user.ServiceUser{Username: req.Username, Passphrase: hashedPassword}
|
||||||
|
if err := s.ServiceStore.Create(ctx, &serviceUser); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusCreated
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, &serviceUser)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceLoginRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Passphrase string `json:"passphrase"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceLoginResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []*token.Login `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login godoc
|
||||||
|
// @Summary Service login
|
||||||
|
// @Description Servce login and be given an access token (requires JWT)
|
||||||
|
// @Tags service users
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param request body ServiceLoginRequest true "Data to obtain a service token"
|
||||||
|
// @Success 200 {object} ServiceLoginResponse
|
||||||
|
// @Failure 500 {object} ServiceLoginResponse
|
||||||
|
// @Router /service/login [post]
|
||||||
|
func (s *ServiceHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req ServiceLoginRequest
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp ServiceLoginResponse
|
||||||
|
|
||||||
|
if len(req.Username) == 0 || len(req.Passphrase) == 0 {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid request"
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if serviceUser, err := s.ServiceStore.GetWithUsername(ctx, req.Username); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if serviceUser == nil {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "Not found"
|
||||||
|
} else {
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(req.Passphrase); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if !hashing.CheckPasswordHash(req.Passphrase, serviceUser.Passphrase) {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = "Not valid"
|
||||||
|
} else {
|
||||||
|
lastLogin := time.Now()
|
||||||
|
var tokGen utility.TokenGenerator
|
||||||
|
tokGen.SetHourOffset(8)
|
||||||
|
secretKey := config.GetSecretKey()
|
||||||
|
tokGen.SetSecretKey(secretKey)
|
||||||
|
|
||||||
|
if myToken, err := tokGen.GenerateToken(*serviceUser); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
log.Println("Updating service user's last login")
|
||||||
|
if rowsAffected, err := s.ServiceStore.UpdateLastLogin(ctx, serviceUser.Id, lastLogin); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
log.Println("Rows updated:", rowsAffected)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, myToken)
|
||||||
|
resp.Message = "Successful"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJson(w, statusCode, &resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateServiceUserWithMock(t *testing.T) {
|
||||||
|
cfg := GetConfig()
|
||||||
|
mockStore := mock.NewMockServiceUserStore()
|
||||||
|
handler := NewServiceHandler(cfg, mockStore)
|
||||||
|
|
||||||
|
testService := ServiceCreationRequest{Username: "swoon", Passphrase: "Ewrewr329n12y3x2!2"}
|
||||||
|
jsonValue, err := json.Marshal(testService)
|
||||||
|
assert.NoError(t, err, "Error marshaling request")
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.CreateServiceUser, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.Register(rr, req)
|
||||||
|
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||||
|
|
||||||
|
var response ServiceCreationResponse
|
||||||
|
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginServiceUserWithMock(t *testing.T) {
|
||||||
|
var serviceUser user.ServiceUser
|
||||||
|
var hashedPassword string
|
||||||
|
var err error
|
||||||
|
unhashed := "A9328nr29nudx3292m320!"
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(unhashed); err != nil {
|
||||||
|
assert.NoError(t, err, "Error setting password")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hashedPassword, err = hashing.HashPassword(); err != nil {
|
||||||
|
assert.NoError(t, err, "Error hashing password: %v", err)
|
||||||
|
} else {
|
||||||
|
serviceUser.Passphrase = hashedPassword
|
||||||
|
}
|
||||||
|
serviceUser.Username = "swoon"
|
||||||
|
ctx := t.Context()
|
||||||
|
mockStore := mock.NewMockServiceUserStore()
|
||||||
|
|
||||||
|
if err := mockStore.Create(ctx, &serviceUser); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating service user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := GetConfig()
|
||||||
|
handler := NewServiceHandler(cfg, mockStore)
|
||||||
|
testService := ServiceLoginRequest{Username: serviceUser.Username, Passphrase: unhashed}
|
||||||
|
jsonValue, err := json.Marshal(testService)
|
||||||
|
assert.NoError(t, err, "Error marshaling request")
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.LoginServiceUser, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.Login(rr, req)
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response ServiceLoginResponse
|
||||||
|
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
@@ -1,9 +1,63 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetTestUser() user.User {
|
func GetTestUser() user.User {
|
||||||
return user.User{Username: "ghost", PhoneNumber: "+1234567890", Password: "dfgdffddfd"}
|
return user.User{Username: "ghost", PhoneNumber: "+1234567890", Password: "Dfgdffd343dfd!"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetConfig() *config.Config {
|
||||||
|
err := godotenv.Load()
|
||||||
|
if err != nil {
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
envPath := path.Join(cwd, "../..", ".env")
|
||||||
|
if err = godotenv.Load(envPath); err != nil {
|
||||||
|
prevPath := path.Join(envPath, "../..", ".env")
|
||||||
|
if err = godotenv.Load(prevPath); err != nil {
|
||||||
|
log.Fatal("Error loading .env file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unpackedConnString := config.UnpackDBConnString()
|
||||||
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
|
||||||
|
return &config.Config{
|
||||||
|
DBConnString: dbConnString,
|
||||||
|
ServerPort: config.Port,
|
||||||
|
ResetDB: false,
|
||||||
|
EnableRegistration: config.CheckRegistration(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUser(ctx context.Context, userStore *mock.MockUserStore) (*user.User, *string, error) {
|
||||||
|
testUser := GetTestUser()
|
||||||
|
unhashedPassword := testUser.Password
|
||||||
|
hashing := utility.HashMash{}
|
||||||
|
if err := hashing.SetPassword(testUser.Password); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("Error setting password: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedPassword, err := hashing.HashPassword()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
testUser.Password = hashedPassword
|
||||||
|
userStore.CreateUser(ctx, &testUser)
|
||||||
|
|
||||||
|
return &testUser, &unhashedPassword, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-auth/internal/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type contextKey string
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserContextKey contextKey = "user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AuthMiddleware(authService *services.JWTService) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
authHeader := r.Header.Get("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
http.Error(w, "Authorization header required", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract token from "Bearer <token>"
|
||||||
|
parts := strings.Split(authHeader, " ")
|
||||||
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||||
|
http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token := parts[1]
|
||||||
|
|
||||||
|
// Validate token with auth service
|
||||||
|
user, err := authService.ValidateToken(token)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add user to context
|
||||||
|
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
package model
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
type UserStore interface {
|
|
||||||
CreateUser(ctx context.Context, user *user.User) error
|
|
||||||
GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error)
|
|
||||||
GetUserByUsername(ctx context.Context, username string) (*user.User, error)
|
|
||||||
GetAllUsers(ctx context.Context) ([]*user.User, error)
|
|
||||||
UserExists(ctx context.Context, username string) (bool, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type PGUserStore struct {
|
|
||||||
db *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUserStore(db *pgxpool.Pool) *PGUserStore {
|
|
||||||
return &PGUserStore{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PGUserStore) CreateUser(ctx context.Context, user *user.User) error {
|
|
||||||
query := `
|
|
||||||
INSERT INTO users (phone_number, username, password)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, phone_number, username
|
|
||||||
`
|
|
||||||
|
|
||||||
return s.db.QueryRow(ctx, query, user.PhoneNumber, user.Username, user.Password).Scan(
|
|
||||||
&user.Id, &user.PhoneNumber, &user.Username,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error) {
|
|
||||||
query := `SELECT id, username, password, phone_number FROM users WHERE id = $1`
|
|
||||||
|
|
||||||
var user user.User
|
|
||||||
err := s.db.QueryRow(ctx, query, id).Scan(
|
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err == pgx.ErrNoRows {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("getting user by ID: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &user, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*user.User, error) {
|
|
||||||
query := `SELECT id, username, password, phone_number FROM users WHERE username = $1`
|
|
||||||
|
|
||||||
var user user.User
|
|
||||||
err := s.db.QueryRow(ctx, query, username).Scan(
|
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err == pgx.ErrNoRows {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("getting user by ID: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &user, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*user.User, error) {
|
|
||||||
query := `SELECT id, username, password, phone_number FROM users`
|
|
||||||
|
|
||||||
rows, err := s.db.Query(ctx, query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("querying all users: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var users []*user.User
|
|
||||||
for rows.Next() {
|
|
||||||
var user user.User
|
|
||||||
if err := rows.Scan(
|
|
||||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
|
||||||
); err != nil {
|
|
||||||
return nil, fmt.Errorf("scanning user row: %w", err)
|
|
||||||
}
|
|
||||||
users = append(users, &user)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, fmt.Errorf("iterating user rows: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return users, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PGUserStore) UserExists(ctx context.Context, username string) (bool, error) {
|
|
||||||
query := `SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)`
|
|
||||||
|
|
||||||
var exists bool
|
|
||||||
err := s.db.QueryRow(ctx, query, username).Scan(&exists)
|
|
||||||
if err != nil {
|
|
||||||
return false, fmt.Errorf("checking if user exists: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return exists, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
txtmodels_token "git.kundeng.us/phoenix/textsender-models/tx0/token"
|
||||||
|
txtmodels_user "git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JWTService struct {
|
||||||
|
secretKey []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewJWTService(secretKey string) *JWTService {
|
||||||
|
return &JWTService{
|
||||||
|
secretKey: []byte(secretKey),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *JWTService) ValidateToken(tokenString string) (*txtmodels_user.User, error) {
|
||||||
|
// TODO: Include more user information in the claims to populate user
|
||||||
|
claims := &txtmodels_token.Claims{}
|
||||||
|
|
||||||
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||||
|
// Validate the signing method
|
||||||
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, jwt.ErrSignatureInvalid
|
||||||
|
}
|
||||||
|
return s.secretKey, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !token.Valid {
|
||||||
|
return nil, jwt.ErrSignatureInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check token expiration
|
||||||
|
if time.Now().After(claims.ExpiresAt.Time) {
|
||||||
|
return nil, jwt.ErrTokenExpired
|
||||||
|
}
|
||||||
|
|
||||||
|
return &txtmodels_user.User{
|
||||||
|
Id: claims.UserId,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package mock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MockServiceUserStore struct {
|
||||||
|
ServiceUsers map[uuid.UUID]*user.ServiceUser
|
||||||
|
ServiceUsersByUsername map[string]*user.ServiceUser
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockServiceUserStore() *MockServiceUserStore {
|
||||||
|
return &MockServiceUserStore{
|
||||||
|
ServiceUsers: make(map[uuid.UUID]*user.ServiceUser),
|
||||||
|
ServiceUsersByUsername: make(map[string]*user.ServiceUser),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockServiceUserStore) Create(ctx context.Context, user *user.ServiceUser) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Id == uuid.Nil {
|
||||||
|
user.Id = uuid.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exists := m.ServiceUsersByUsername[user.Username]; exists {
|
||||||
|
return errors.New("service User with username already exists")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.ServiceUsers[user.Id] = user
|
||||||
|
m.ServiceUsersByUsername[user.Username] = user
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockServiceUserStore) CheckWithUsername(ctx context.Context, username string) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return false, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
var exists bool
|
||||||
|
|
||||||
|
for _, serviceUser := range m.ServiceUsers {
|
||||||
|
if serviceUser.Username == username {
|
||||||
|
exists = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
return exists, nil
|
||||||
|
} else {
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockServiceUserStore) GetWithUsername(ctx context.Context, username string) (*user.ServiceUser, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceUser := m.ServiceUsersByUsername[username]
|
||||||
|
if serviceUser != nil {
|
||||||
|
return serviceUser, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("User not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockServiceUserStore) GetWithId(ctx context.Context, id uuid.UUID) (*user.ServiceUser, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, serviceUser := range m.ServiceUsers {
|
||||||
|
if serviceUser.Id == id {
|
||||||
|
return serviceUser, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockServiceUserStore) UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return 0, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceUser, exists := m.ServiceUsers[id]
|
||||||
|
if !exists {
|
||||||
|
return 0, errors.New("Service user not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceUser.LastLogin = &lastLogin
|
||||||
|
|
||||||
|
m.ServiceUsers[id] = serviceUser
|
||||||
|
m.ServiceUsersByUsername[serviceUser.Username] = serviceUser
|
||||||
|
|
||||||
|
return 1, nil
|
||||||
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
package handler
|
package mock
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MockUserStore struct {
|
type MockUserStore struct {
|
||||||
@@ -37,9 +39,11 @@ func (m *MockUserStore) CreateUser(ctx context.Context, user *user.User) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, exists := m.UsersByUsername[user.Username]; exists {
|
if _, exists := m.UsersByUsername[user.Username]; exists {
|
||||||
return errors.New("User with email already exists")
|
return errors.New("User with username already exists")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
user.Created = time.Now()
|
||||||
|
|
||||||
m.Users[user.Id] = user
|
m.Users[user.Id] = user
|
||||||
m.UsersByUsername[user.Username] = user
|
m.UsersByUsername[user.Username] = user
|
||||||
return nil
|
return nil
|
||||||
@@ -112,3 +116,77 @@ func (m *MockUserStore) UserExists(ctx context.Context, username string) (bool,
|
|||||||
return exists, nil
|
return exists, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) UpdatePassword(ctx context.Context, id uuid.UUID, password string) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return 0, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
user, exists := m.Users[id]
|
||||||
|
if !exists {
|
||||||
|
return 0, errors.New("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
user.Password = password
|
||||||
|
|
||||||
|
m.Users[id] = user
|
||||||
|
m.UsersByUsername[user.Username] = user
|
||||||
|
|
||||||
|
return 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return 0, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
user, exists := m.Users[id]
|
||||||
|
if !exists {
|
||||||
|
return 0, errors.New("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
user.LastLogin = &lastLogin
|
||||||
|
|
||||||
|
m.Users[id] = user
|
||||||
|
m.UsersByUsername[user.Username] = user
|
||||||
|
|
||||||
|
return 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockUserStore) UpdateName(ctx context.Context, firstname *string, lastname *string, usr *user.User) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return 0, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstname == nil && lastname == nil {
|
||||||
|
return 0, fmt.Errorf("Names not provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
user, exists := m.Users[usr.Id]
|
||||||
|
if !exists {
|
||||||
|
return 0, errors.New("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstname != nil && lastname != nil {
|
||||||
|
user.Firstname = firstname
|
||||||
|
user.Lastname = lastname
|
||||||
|
} else if firstname != nil {
|
||||||
|
user.Firstname = firstname
|
||||||
|
} else {
|
||||||
|
user.Lastname = lastname
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Users[usr.Id] = user
|
||||||
|
m.UsersByUsername[user.Username] = user
|
||||||
|
|
||||||
|
return 1, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TODO: Rename this to ServiceUserStore
|
||||||
|
type ServiceStore interface {
|
||||||
|
CheckWithUsername(ctx context.Context, username string) (bool, error)
|
||||||
|
GetWithUsername(ctx context.Context, username string) (*user.ServiceUser, error)
|
||||||
|
GetWithId(ctx context.Context, id uuid.UUID) (*user.ServiceUser, error)
|
||||||
|
Create(ctx context.Context, serviceUser *user.ServiceUser) error
|
||||||
|
UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGServiceStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServiceStore(db *pgxpool.Pool) *PGServiceStore {
|
||||||
|
return &PGServiceStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGServiceStore) CheckWithUsername(ctx context.Context, username string) (bool, error) {
|
||||||
|
var exists bool
|
||||||
|
query := `SELECT EXISTS(SELECT 1 FROM service_users WHERE Username = $1)`
|
||||||
|
|
||||||
|
if err := s.db.QueryRow(ctx, query, username).Scan(&exists); err != nil {
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return exists, nil
|
||||||
|
} else {
|
||||||
|
return exists, fmt.Errorf("Error querying row: %v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGServiceStore) GetWithUsername(ctx context.Context, username string) (*user.ServiceUser, error) {
|
||||||
|
var serviceUser user.ServiceUser
|
||||||
|
query := `SELECT id, username, passphrase, created FROM service_users WHERE username = $1`
|
||||||
|
|
||||||
|
if err := s.db.QueryRow(ctx, query, username).Scan(&serviceUser.Id, &serviceUser.Username, &serviceUser.Passphrase, &serviceUser.Created); err != nil {
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Error querying row: %v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &serviceUser, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGServiceStore) GetWithId(ctx context.Context, id uuid.UUID) (*user.ServiceUser, error) {
|
||||||
|
var serviceUser user.ServiceUser
|
||||||
|
query := `SELECT id, username, passphrase, created FROM service_users WHERE id = $1`
|
||||||
|
|
||||||
|
if err := s.db.QueryRow(ctx, query, id).Scan(&serviceUser.Id, &serviceUser.Username, &serviceUser.Passphrase, &serviceUser.Created); err != nil {
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Error querying row: %v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &serviceUser, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGServiceStore) Create(ctx context.Context, serviceUser *user.ServiceUser) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO service_users (username, passphrase)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
RETURNING id, created
|
||||||
|
`
|
||||||
|
|
||||||
|
return s.db.QueryRow(ctx, query, serviceUser.Username, serviceUser.Passphrase).Scan(
|
||||||
|
&serviceUser.Id, &serviceUser.Created,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGServiceStore) UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error) {
|
||||||
|
query := `UPDATE service_users SET last_login = $1 WHERE id = $2`
|
||||||
|
if affected, err := s.db.Exec(ctx, query, lastLogin, id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserStore interface {
|
||||||
|
CreateUser(ctx context.Context, user *user.User) error
|
||||||
|
GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error)
|
||||||
|
GetUserByUsername(ctx context.Context, username string) (*user.User, error)
|
||||||
|
GetAllUsers(ctx context.Context) ([]*user.User, error)
|
||||||
|
UserExists(ctx context.Context, username string) (bool, error)
|
||||||
|
UpdatePassword(ctx context.Context, id uuid.UUID, password string) (int64, error)
|
||||||
|
UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error)
|
||||||
|
UpdateName(ctx context.Context, firstname *string, lastname *string, usr *user.User) (int64, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGUserStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserStore(db *pgxpool.Pool) *PGUserStore {
|
||||||
|
return &PGUserStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) CreateUser(ctx context.Context, user *user.User) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO users (phone_number, username, password)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
RETURNING id, phone_number, username, created
|
||||||
|
`
|
||||||
|
|
||||||
|
return s.db.QueryRow(ctx, query, user.PhoneNumber, user.Username, user.Password).Scan(
|
||||||
|
&user.Id, &user.PhoneNumber, &user.Username, &user.Created,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*user.User, error) {
|
||||||
|
query := `SELECT id, username, password, phone_number, created FROM users WHERE id = $1`
|
||||||
|
|
||||||
|
var user user.User
|
||||||
|
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||||
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber, &user.Created,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting user by ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*user.User, error) {
|
||||||
|
query := `SELECT id, username, password, phone_number, created FROM users WHERE username = $1`
|
||||||
|
|
||||||
|
var user user.User
|
||||||
|
err := s.db.QueryRow(ctx, query, username).Scan(
|
||||||
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber, &user.Created,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting user by ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*user.User, error) {
|
||||||
|
query := `SELECT id, username, password, phone_number, created FROM users`
|
||||||
|
|
||||||
|
rows, err := s.db.Query(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("querying all users: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var users []*user.User
|
||||||
|
for rows.Next() {
|
||||||
|
var user user.User
|
||||||
|
if err := rows.Scan(
|
||||||
|
&user.Id, &user.Username, &user.Password, &user.PhoneNumber, &user.Created,
|
||||||
|
); err != nil {
|
||||||
|
return nil, fmt.Errorf("scanning user row: %w", err)
|
||||||
|
}
|
||||||
|
users = append(users, &user)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterating user rows: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return users, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) UserExists(ctx context.Context, username string) (bool, error) {
|
||||||
|
query := `SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)`
|
||||||
|
|
||||||
|
var exists bool
|
||||||
|
err := s.db.QueryRow(ctx, query, username).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("checking if user exists: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) UpdatePassword(ctx context.Context, id uuid.UUID, password string) (int64, error) {
|
||||||
|
query := `UPDATE users SET password = $1 WHERE id = $2`
|
||||||
|
if affected, err := s.db.Exec(ctx, query, password, id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) UpdateLastLogin(ctx context.Context, id uuid.UUID, lastLogin time.Time) (int64, error) {
|
||||||
|
query := `UPDATE users SET last_login = $1 WHERE id = $2`
|
||||||
|
if affected, err := s.db.Exec(ctx, query, lastLogin, id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGUserStore) UpdateName(ctx context.Context, firstname *string, lastname *string, usr *user.User) (int64, error) {
|
||||||
|
var query string
|
||||||
|
|
||||||
|
if firstname == nil && lastname == nil {
|
||||||
|
return 0, fmt.Errorf("Provided names are empty")
|
||||||
|
} else {
|
||||||
|
tableName := "users"
|
||||||
|
if firstname != nil && lastname != nil {
|
||||||
|
query = fmt.Sprintf("UPDATE %s SET first_name = $1, last_name = $2 WHERE id = $3", tableName)
|
||||||
|
if affected, err := s.db.Exec(ctx, query, firstname, lastname, usr.Id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
usr.Firstname = firstname
|
||||||
|
usr.Lastname = lastname
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
} else if firstname != nil {
|
||||||
|
query = fmt.Sprintf("UPDATE %s SET first_name = $1 WHERE id = $2", tableName)
|
||||||
|
if affected, err := s.db.Exec(ctx, query, firstname, usr.Id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
usr.Firstname = firstname
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
query = fmt.Sprintf("UPDATE %s SET last_name = $1 WHERE id = $2", tableName)
|
||||||
|
if affected, err := s.db.Exec(ctx, query, lastname, usr.Id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
usr.Lastname = lastname
|
||||||
|
return affected.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,62 @@
|
|||||||
package utility
|
package utility
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
type HashMash struct {
|
type HashMash struct {
|
||||||
Password string
|
password string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h HashMash) HashPassword() (string, error) {
|
func (h *HashMash) HashPassword() (string, error) {
|
||||||
bytes, err := bcrypt.GenerateFromPassword([]byte(h.Password), bcrypt.DefaultCost)
|
bytes, err := bcrypt.GenerateFromPassword([]byte(h.password), bcrypt.DefaultCost)
|
||||||
return string(bytes), err
|
return string(bytes), err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h HashMash) CheckPasswordHash(password string, hash string) bool {
|
func (h *HashMash) CheckPasswordHash(password string, hash string) bool {
|
||||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HashMash) SetPassword(password string) {
|
func (h *HashMash) SetPassword(password string) error {
|
||||||
h.Password = password
|
if len(password) < 8 {
|
||||||
|
return fmt.Errorf("Password length is not enought")
|
||||||
|
} else if len(password) > 32 {
|
||||||
|
return fmt.Errorf("Password length is too long")
|
||||||
|
} else {
|
||||||
|
specialCharacters := "!@#$%^&*?"
|
||||||
|
numbers := "0123456789"
|
||||||
|
if strings.ContainsAny(password, specialCharacters) && strings.ContainsAny(password, numbers) {
|
||||||
|
var hasAtleastOneUpper, hasAtleastOneLower bool
|
||||||
|
|
||||||
|
for _, c := range password {
|
||||||
|
if unicode.IsUpper(c) {
|
||||||
|
hasAtleastOneUpper = true
|
||||||
|
} else if unicode.IsLower(c) {
|
||||||
|
hasAtleastOneLower = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasAtleastOneLower && hasAtleastOneUpper {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasAtleastOneUpper && hasAtleastOneLower {
|
||||||
|
h.password = password
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
if !hasAtleastOneUpper {
|
||||||
|
return fmt.Errorf("Password requires at least one upper case letter")
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("Password requires at least one lower case letter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("Password should contain special characters and numbers")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+98
-15
@@ -1,13 +1,15 @@
|
|||||||
package utility
|
package utility
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/token"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/tx0/user"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/token"
|
|
||||||
"git.kundeng.us/phoenix/textsender-models/pkg/user"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const ROLE_TYPE = "regular"
|
const ROLE_TYPE = "regular"
|
||||||
@@ -15,33 +17,114 @@ const TOKEN_TYPE = "Bearer"
|
|||||||
|
|
||||||
type TokenGenerator struct {
|
type TokenGenerator struct {
|
||||||
SecretKey []byte
|
SecretKey []byte
|
||||||
|
hourOffset time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TokenGenerator) SetSecretKey(secretKey string) {
|
func (t *TokenGenerator) SetSecretKey(secretKey string) {
|
||||||
t.SecretKey = []byte(secretKey)
|
t.SecretKey = []byte(secretKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TokenGenerator) GenerateToken(user user.User) (*token.Login, error) {
|
func (t *TokenGenerator) SetHourOffset(offset time.Duration) error {
|
||||||
issuedAt := time.Now()
|
if offset < 48 {
|
||||||
expirationTime := time.Now().Add(4 * time.Hour)
|
t.hourOffset = offset
|
||||||
claims := t.generateClaims(user, TOKEN_TYPE, issuedAt, expirationTime)
|
return nil
|
||||||
|
|
||||||
myToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
if tokenString, err := myToken.SignedString(t.SecretKey); err != nil {
|
|
||||||
return nil, err
|
|
||||||
} else {
|
} else {
|
||||||
return &token.Login{AccessToken: tokenString, TokenType: TOKEN_TYPE, ExpiresIn: expirationTime.Unix()}, nil
|
return fmt.Errorf("No change")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TokenGenerator) generateClaims(user user.User, role string, issuedAt time.Time, expiredAt time.Time) token.Claims {
|
func (t *TokenGenerator) GenerateToken(usr any) (*token.Login, error) {
|
||||||
return token.Claims{
|
issuedAt := time.Now()
|
||||||
UserId: user.Id,
|
if t.hourOffset == 0 {
|
||||||
|
t.hourOffset = 4
|
||||||
|
}
|
||||||
|
expirationTime := time.Now().Add(t.hourOffset * time.Hour)
|
||||||
|
|
||||||
|
if claims, err := t.generateClaims(usr, TOKEN_TYPE, issuedAt, expirationTime); err != nil {
|
||||||
|
return nil, fmt.Errorf("Error generating claims: %v", err)
|
||||||
|
} else {
|
||||||
|
myToken := jwt.NewWithClaims(jwt.SigningMethodHS256, *claims)
|
||||||
|
if tokenString, err := myToken.SignedString(t.SecretKey); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return &token.Login{UserId: claims.UserId, AccessToken: tokenString, TokenType: TOKEN_TYPE, ExpiresIn: expirationTime.Unix(), IssuedAt: issuedAt.Unix()}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) VerifyToken(accessToken string) (bool, error) {
|
||||||
|
clms := &token.Claims{}
|
||||||
|
|
||||||
|
if tken, err := t.parseTokenWithClaims(accessToken, clms); err != nil {
|
||||||
|
return false, nil
|
||||||
|
} else {
|
||||||
|
if tken.Valid {
|
||||||
|
if clms.UserId != uuid.Nil {
|
||||||
|
return true, nil
|
||||||
|
} else {
|
||||||
|
return false, fmt.Errorf("User Id was not set")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false, fmt.Errorf("Invalid access token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) ExtractIdFromToken(accessToken string) (uuid.UUID, error) {
|
||||||
|
clms := &token.Claims{}
|
||||||
|
|
||||||
|
if tken, err := t.parseTokenWithClaims(accessToken, clms); err != nil {
|
||||||
|
return uuid.Nil, nil
|
||||||
|
} else {
|
||||||
|
if tken.Valid {
|
||||||
|
if clms.UserId != uuid.Nil {
|
||||||
|
return clms.UserId, nil
|
||||||
|
} else {
|
||||||
|
return uuid.Nil, fmt.Errorf("User Id was not set")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return uuid.Nil, fmt.Errorf("Invalid access token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) parseTokenWithClaims(accessToken string, claims *token.Claims) (*jwt.Token, error) {
|
||||||
|
tken, err := jwt.ParseWithClaims(accessToken, claims, func(tken *jwt.Token) (any, error) {
|
||||||
|
if _, ok := tken.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, fmt.Errorf("unexpected signing method: %v", tken.Header["alg"])
|
||||||
|
}
|
||||||
|
return t.SecretKey, nil
|
||||||
|
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return tken, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TokenGenerator) generateClaims(usr any, role string, issuedAt time.Time, expiredAt time.Time) (*token.Claims, error) {
|
||||||
|
var id uuid.UUID
|
||||||
|
switch val := usr.(type) {
|
||||||
|
case user.User:
|
||||||
|
id = val.Id
|
||||||
|
case *user.User:
|
||||||
|
id = val.Id
|
||||||
|
case user.ServiceUser:
|
||||||
|
id = val.Id
|
||||||
|
case *user.ServiceUser:
|
||||||
|
id = val.Id
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Invalid type")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &token.Claims{
|
||||||
|
UserId: id,
|
||||||
Role: role,
|
Role: role,
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
Issuer: config.App_Name,
|
Issuer: config.App_Name,
|
||||||
ExpiresAt: jwt.NewNumericDate(expiredAt),
|
ExpiresAt: jwt.NewNumericDate(expiredAt),
|
||||||
IssuedAt: jwt.NewNumericDate(issuedAt),
|
IssuedAt: jwt.NewNumericDate(issuedAt),
|
||||||
},
|
},
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-1
@@ -1,11 +1,23 @@
|
|||||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||||
|
|
||||||
DROP TABLE IF EXISTS users CASCADE;
|
DROP TABLE IF EXISTS users CASCADE;
|
||||||
|
DROP TABLE IF EXISTS service_users CASCADE;
|
||||||
|
|
||||||
CREATE TABLE users (
|
CREATE TABLE users (
|
||||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
first_name TEXT NULL,
|
||||||
|
last_name TEXT NULL,
|
||||||
phone_number TEXT NOT NULL,
|
phone_number TEXT NOT NULL,
|
||||||
username TEXT NOT NULL,
|
username TEXT NOT NULL,
|
||||||
password TEXT NOT NULL
|
password TEXT NOT NULL,
|
||||||
|
created timestamptz DEFAULT now(),
|
||||||
|
last_login timestamptz NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE service_users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
passphrase TEXT NOT NULL,
|
||||||
|
created timestamptz DEFAULT now(),
|
||||||
|
last_login timestamptz NULL
|
||||||
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user