37 Commits
Author SHA1 Message Date
phoenixandphoenix 8a90448854 tsk-15: Add API documentation (#17)
Closes #15

Reviewed-on: phoenix/textsender-auth#17
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-14 17:56:51 +00:00
phoenixandphoenix 6f608b757c tsk-14: Fix startup crash (#16)
Closes #14

Reviewed-on: phoenix/textsender-auth#16
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-14 17:35:57 +00:00
phoenixandphoenix ef39949e77 tsk-8: Added docker support (#13)
Closes #8

Reviewed-on: phoenix/textsender-auth#13
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-05 16:50:14 +00:00
phoenixandphoenix b627c832fa tsk-11: Updating postgresql in workflow (#12)
Closes #11

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