15 Commits
Author SHA1 Message Date
phoenix 760a778a27 next_changes (#32)
Reviewed-on: phoenix/textsender-auth#32
2025-12-22 22:42:45 +00:00
phoenix 7597e05243 textsender-models version bump 2025-12-22 17:40:08 -05:00
phoenixandphoenix 636b0280c7 tsk-10: CORS support (#28)
Closes #10

Reviewed-on: phoenix/textsender-auth#28
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-12-21 00:28:08 +00:00
phoenixandphoenix 223b7919f9 tsk-29: Expand LoginResult (#31)
Closes #29

Reviewed-on: phoenix/textsender-auth#31
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-12-16 19:09:18 +00:00
phoenix 66221e504c tsk-10: Got it working 2025-12-13 15:18:06 -05:00
phoenix 093888f7fb tsk-10: Package change 2025-12-13 15:17:55 -05:00
phoenix 225dc0c963 tsk-10: Added cors 2025-12-11 17:29:34 -05:00
phoenix c7b45952fe tsk-10: go mod 2025-12-11 17:29:12 -05:00
phoenix f305e5b2e9 tsk-10: Added cors package 2025-12-11 16:53:30 -05:00
phoenixandphoenix 9f5029dd6e tsk-21: Disable registration (#27)
Closes #21

Reviewed-on: phoenix/textsender-auth#27
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-27 01:01:32 +00:00
phoenixandphoenix d01fae0775 tsk-25: go version bump (#26)
Closes #25

Reviewed-on: phoenix/textsender-auth#26
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-24 21:10:44 +00:00
phoenixandphoenix 371dc38958 tsk-20: Obtain refresh token (#24)
Closes #20

Reviewed-on: phoenix/textsender-auth#24
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-21 20:49:38 +00:00
phoenixandphoenix 0a00282ba7 tsk-19: Service login (#23)
Closes #19

Reviewed-on: phoenix/textsender-auth#23
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-21 18:42:58 +00:00
phoenixandphoenix c340693b24 tsk-18: Create service user (#22)
Closes #18

Reviewed-on: phoenix/textsender-auth#22
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-20 19:11:36 +00:00
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
30 changed files with 2229 additions and 89 deletions
+2
View File
@@ -5,3 +5,5 @@ DB_PASSWORD=password
DB_HOST=auth_db
DB_PORT=5432
DB_SSLMODE=disable
ENABLE_REGISTRATION=true
ALLOWED_ORIGINS="http://textsender.com"
+2
View File
@@ -5,3 +5,5 @@ DB_PASSWORD=yEDjWZCH2vdctjn!
DB_HOST=localhost
DB_PORT=5432
DB_SSLMODE=disable
ENABLE_REGISTRATION=true
ALLOWED_ORIGINS="http://textsender.com"
+27 -23
View File
@@ -14,9 +14,9 @@ jobs:
- uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v6
with:
go-version: '1.25.3' # You can specify a specific version or 'stable'
go-version: '1.25.4' # You can specify a specific version or 'stable'
- name: Build
run: |
@@ -24,7 +24,7 @@ jobs:
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
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender_models_deploy_key
@@ -66,9 +66,9 @@ jobs:
uses: actions/checkout@v5
- name: Setup Go
uses: actions/setup-go@v4
uses: actions/setup-go@v6
with:
go-version: '1.25.3'
go-version: '1.25.4'
- name: Install PostgreSQL client
run: sudo apt update && sudo apt-get install -y postgresql-client
@@ -99,28 +99,32 @@ jobs:
echo "Parent directory"
echo `pwd`
echo "SECRET_KEY=$SECRET_KEY" >> .env
echo "DB_NAME=$DB_NAME" > .env
echo "SECRET_KEY=$SECRET_KEY" > .env
echo "DB_NAME=$DB_NAME" >> .env
echo "DB_USER=$DB_USER" >> .env
echo "DB_PASSWORD=$DB_PASSWORD" >> .env
echo "DB_HOST=$DB_HOST" >> .env
echo "DB_PORT=$DB_PORT" >> .env
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
echo "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 ./...
# - 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
View File
@@ -1,5 +1,5 @@
# Multi-stage Dockerfile for Go application
FROM golang:1.25.3 AS builder
FROM golang:1.25.4 AS builder
WORKDIR /app
@@ -29,6 +29,7 @@ COPY ./internal ./internal
COPY ./Makefile .
COPY ./.env .
COPY ./migrations ./migrations
COPY ./docs ./docs
# Build the application
RUN CGO_ENABLED=0 GOOS=linux make build
+11
View File
@@ -18,3 +18,14 @@ make build
```
./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`.
+38 -4
View File
@@ -12,15 +12,29 @@ import (
"github.com/go-chi/chi/v5"
"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"
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"
"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() {
cfg := config.Load()
if cfg == nil {
@@ -59,12 +73,25 @@ func main() {
}
// Services
userStore := model.NewUserStore(db.Pool)
userHandler := handler.NewUserHandler(userStore)
loginHandler := handler.NewLoginHandler(userStore)
userStore := store.NewUserStore(db.Pool)
serviceStore := store.NewServiceStore(db.Pool)
userHandler := handler.NewUserHandler(cfg, userStore)
loginHandler := handler.NewLoginHandler(cfg, userStore)
serviceHandler := handler.NewServiceHandler(cfg, serviceStore)
refreshHandler := handler.NewRefreshHandler(cfg, userStore, serviceStore)
router := chi.NewRouter()
// 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.Recoverer)
router.Use(middleware.Timeout(60 * time.Second))
@@ -72,6 +99,13 @@ func main() {
router.Method("Post", endpoint.Register, http.HandlerFunc(userHandler.Register))
router.Method("Post", endpoint.Login, http.HandlerFunc(loginHandler.Login))
router.Method("Post", endpoint.CreateServiceUser, http.HandlerFunc(serviceHandler.Register))
router.Method("Post", endpoint.LoginServiceUser, http.HandlerFunc(serviceHandler.Login))
router.Method("Post", endpoint.TokenRefresh, http.HandlerFunc(refreshHandler.Refresh))
router.Method("GET", "/swagger/*", httpSwagger.Handler(
httpSwagger.URL(fmt.Sprintf("http://localhost:%s/swagger/doc.json", config.Port)),
))
// Start server
server := &http.Server{
+17 -10
View File
@@ -15,7 +15,7 @@ import (
"git.kundeng.us/phoenix/textsender-auth/internal/db"
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/model"
"git.kundeng.us/phoenix/textsender-auth/internal/store"
)
var testRouter *mux.Router
@@ -23,27 +23,33 @@ var testRouter *mux.Router
func TestMain(m *testing.M) {
cfg := load()
db, err := db.NewDatabase(cfg.GetDBConnString())
database, err := db.NewDatabase(cfg.GetDBConnString())
if err != nil {
fmt.Println(err.Error())
panic("Failed to initialize database")
}
defer db.Close()
defer database.Close()
ctx := context.Background()
err = db.ResetDatabase(ctx)
err = database.ResetDatabase(ctx)
if err != nil {
fmt.Println(err.Error())
panic("Failed to initialize database")
}
userStore := model.NewUserStore(db.Pool)
userHandler := handler.NewUserHandler(userStore)
loginHandler := handler.NewLoginHandler(userStore)
userStore := store.NewUserStore(database.Pool)
serviceStore := store.NewServiceStore(database.Pool)
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.HandleFunc(endpoint.Register, userHandler.Register).Methods("POST")
testRouter.HandleFunc(endpoint.Login, loginHandler.Login).Methods("POST")
testRouter.HandleFunc(endpoint.CreateServiceUser, serviceHandler.Register).Methods("POST")
testRouter.HandleFunc(endpoint.LoginServiceUser, serviceHandler.Login).Methods("POST")
testRouter.HandleFunc(endpoint.TokenRefresh, refreshHandler.Refresh).Methods("POST")
code := m.Run()
os.Exit(code)
@@ -69,9 +75,10 @@ func load() *config.Config {
dbConnString := unpackedConnString.Parse()
return &config.Config{
DBConnString: dbConnString,
ServerPort: *port,
ResetDB: *resetDb,
DBConnString: dbConnString,
ServerPort: *port,
ResetDB: *resetDb,
EnableRegistration: config.CheckRegistration(),
}
}
+478
View File
@@ -0,0 +1,478 @@
// 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"
}
}
}
}
}
},
"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.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"
}
}
},
"token.Login": {
"type": "object",
"properties": {
"access_token": {
"type": "string"
},
"expires_in": {
"type": "integer"
},
"token_type": {
"type": "string"
}
}
},
"user.ServiceUser": {
"type": "object",
"properties": {
"date_created": {
"type": "string"
},
"id": {
"type": "string"
},
"passphrase": {
"type": "string"
},
"username": {
"type": "string"
}
}
}
},
"securityDefinitions": {
"BearerAuth": {
"description": "JWT Bearer Token",
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "1.0",
Host: "localhost:9080",
BasePath: "/api/v1",
Schemes: []string{},
Title: "textsender-auth",
Description: "Auth API to send text messages",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}
+454
View File
@@ -0,0 +1,454 @@
{
"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"
}
}
}
}
}
},
"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.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"
}
}
},
"token.Login": {
"type": "object",
"properties": {
"access_token": {
"type": "string"
},
"expires_in": {
"type": "integer"
},
"token_type": {
"type": "string"
}
}
},
"user.ServiceUser": {
"type": "object",
"properties": {
"date_created": {
"type": "string"
},
"id": {
"type": "string"
},
"passphrase": {
"type": "string"
},
"username": {
"type": "string"
}
}
}
},
"securityDefinitions": {
"BearerAuth": {
"description": "JWT Bearer Token",
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
}
+289
View File
@@ -0,0 +1,289 @@
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.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
token.Login:
properties:
access_token:
type: string
expires_in:
type: integer
token_type:
type: string
type: object
user.ServiceUser:
properties:
date_created:
type: string
id:
type: string
passphrase:
type: string
username:
type: string
type: object
host: localhost:9080
info:
contact: {}
description: Auth API to send text messages
title: textsender-auth
version: "1.0"
paths:
/login:
post:
consumes:
- application/json
description: Login and be given an access token (requires JWT)
parameters:
- description: Data to obtain a token
in: body
name: request
required: true
schema:
$ref: '#/definitions/handler.LoginAccount'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/handler.LoginResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/handler.LoginResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/handler.LoginResponse'
security:
- BearerAuth: []
summary: Login
tags:
- users
/register:
post:
consumes:
- application/json
description: Create a user that can send texts (requires JWT)
parameters:
- description: Data to add user
in: body
name: request
required: true
schema:
$ref: '#/definitions/handler.RegisterUser'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/handler.RegisterResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/handler.RegisterResponse'
"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
securityDefinitions:
BearerAuth:
description: JWT Bearer Token
in: header
name: Authorization
type: apiKey
swagger: "2.0"
+16 -3
View File
@@ -1,28 +1,41 @@
module git.kundeng.us/phoenix/textsender-auth
go 1.25.3
go 1.25.4
require (
git.kundeng.us/phoenix/textsender-models v0.0.6-main-28b29802b9-556
git.kundeng.us/phoenix/textsender-models v0.0.12
github.com/go-chi/chi/v5 v5.2.3
github.com/go-chi/cors v1.2.2
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/jackc/pgx/v5 v5.7.5
github.com/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
)
+45 -2
View File
@@ -1,13 +1,29 @@
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=
git.kundeng.us/phoenix/textsender-models v0.0.12 h1:ps9H3FS5LyCwQhAiIvg4vYyfLZZ64dex1y9ytb0o9C4=
git.kundeng.us/phoenix/textsender-models v0.0.12/go.mod h1:9iPDQJg1Tc6WMNoW5+f8YKmnosMwlWHJ++hmxNLDEe0=
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-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
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=
@@ -22,28 +38,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=
+51 -8
View File
@@ -5,7 +5,9 @@ import (
"fmt"
"log"
"os"
"path"
"strconv"
"strings"
"github.com/joho/godotenv"
@@ -13,9 +15,11 @@ import (
)
type Config struct {
DBConnString string
ServerPort string
ResetDB bool
DBConnString string
ServerPort string
ResetDB bool
EnableRegistration bool
AllowedOrigins []string
}
type ConnectionInfo struct {
@@ -52,16 +56,35 @@ func Load() *Config {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
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 := UnpackDBConnString()
dbConnString := unpackedConnString.Parse()
allowedOrigins := unpackAllowedOrigin()
return &Config{
DBConnString: dbConnString,
ServerPort: *port,
ResetDB: *resetDb,
if len(allowedOrigins) > 0 {
return &Config{
DBConnString: dbConnString,
ServerPort: *port,
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
}
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 {
return c.DBConnString
}
+3
View File
@@ -3,3 +3,6 @@ package endpoint
// Endpoint for registering a user
const Register = "/api/v1/register"
const Login = "/api/v1/login"
const CreateServiceUser = "/api/v1/service/register"
const LoginServiceUser = "/api/v1/service/login"
const TokenRefresh = "/api/v1/token/refresh"
+18 -5
View File
@@ -4,10 +4,10 @@ import (
"fmt"
"net/http"
"git.kundeng.us/phoenix/textsender-models/pkg/token"
"git.kundeng.us/phoenix/textsender-models/tx0/token"
"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"
)
@@ -22,13 +22,26 @@ type LoginResponse struct {
}
type LoginHandler struct {
UserStore model.UserStore
Config *config.Config
UserStore store.UserStore
}
func NewLoginHandler(userStore model.UserStore) *LoginHandler {
return &LoginHandler{UserStore: userStore}
func NewLoginHandler(cfg *config.Config, userStore store.UserStore) *LoginHandler {
return &LoginHandler{Config: cfg, UserStore: userStore}
}
// Login godoc
// @Summary Login
// @Description Login and be given an access token (requires JWT)
// @Tags users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body LoginAccount true "Data to obtain a token"
// @Success 200 {object} LoginResponse
// @Failure 400 {object} LoginResponse
// @Failure 500 {object} LoginResponse
// @Router /login [post]
func (l *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
var req LoginAccount
if err := ExtractFromRequest(r, &req); err != nil {
+4 -2
View File
@@ -12,12 +12,14 @@ import (
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
)
func TestLogin(t *testing.T) {
mockstore := NewMockUserStore()
handler := NewLoginHandler(mockstore)
cfg := GetConfig()
mockstore := mock.NewMockUserStore()
handler := NewLoginHandler(cfg, mockstore)
testUser := GetTestUser()
unhashedPassword := testUser.Password
+100
View File
@@ -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)
}
+66
View File
@@ -0,0 +1,66 @@
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 := "9328nr29nudx3292m320!"
hashing := utility.HashMash{Password: unhashed}
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)
}
+26 -5
View File
@@ -4,10 +4,11 @@ import (
"fmt"
"net/http"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"git.kundeng.us/phoenix/textsender-models/tx0/user"
"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"
)
@@ -29,13 +30,27 @@ type RegisterResponse struct {
}
type UserHandler struct {
UserStore model.UserStore
Config *config.Config
UserStore store.UserStore
}
func NewUserHandler(userStore model.UserStore) *UserHandler {
return &UserHandler{UserStore: userStore}
func NewUserHandler(cfg *config.Config, userStore store.UserStore) *UserHandler {
return &UserHandler{Config: cfg, UserStore: userStore}
}
// 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 403 {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)
@@ -48,6 +63,12 @@ func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
var statusCode int
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}
fmt.Println("Username:", user.Username)
+4 -2
View File
@@ -10,11 +10,13 @@ import (
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-auth/internal/store/mock"
)
func TestCreateUserWithMock(t *testing.T) {
mockstore := NewMockUserStore()
handler := NewUserHandler(mockstore)
cfg := GetConfig()
mockstore := mock.NewMockUserStore()
handler := NewUserHandler(cfg, mockstore)
testUser := GetTestUser()
jsonValue, _ := json.Marshal(testUser)
+165
View File
@@ -0,0 +1,165 @@
package handler
import (
"net/http"
"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{Password: req.Passphrase}
if hashedPassword, err := hashing.HashPassword(); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
serviceUser := user.ServiceUser{Username: req.Username, Passphrase: hashedPassword}
if err := s.ServiceStore.Create(ctx, &serviceUser); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
statusCode = http.StatusCreated
resp.Message = "Successful"
resp.Data = append(resp.Data, &serviceUser)
}
}
}
}
RespondWithJson(w, statusCode, &resp)
}
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{Password: req.Passphrase}
if !hashing.CheckPasswordHash(req.Passphrase, serviceUser.Passphrase) {
statusCode = http.StatusInternalServerError
resp.Message = "Not valid"
} else {
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 {
statusCode = http.StatusOK
resp.Data = append(resp.Data, myToken)
resp.Message = "Successful"
}
}
}
}
RespondWithJson(w, statusCode, &resp)
}
+72
View File
@@ -0,0 +1,72 @@
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 := "9328nr29nudx3292m320!"
hashing := utility.HashMash{Password: unhashed}
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)
}
+32 -1
View File
@@ -1,9 +1,40 @@
package handler
import (
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"log"
"os"
"path"
"git.kundeng.us/phoenix/textsender-models/tx0/user"
"github.com/joho/godotenv"
"git.kundeng.us/phoenix/textsender-auth/internal/config"
)
func GetTestUser() user.User {
return user.User{Username: "ghost", PhoneNumber: "+1234567890", Password: "dfgdffddfd"}
}
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(),
}
}
+103
View File
@@ -0,0 +1,103 @@
package mock
import (
"context"
"errors"
"fmt"
"sync"
"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
}
@@ -1,4 +1,4 @@
package handler
package mock
import (
"context"
@@ -7,7 +7,7 @@ import (
"github.com/google/uuid"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"git.kundeng.us/phoenix/textsender-models/tx0/user"
)
type MockUserStore struct {
+83
View File
@@ -0,0 +1,83 @@
package store
import (
"context"
"fmt"
"git.kundeng.us/phoenix/textsender-models/tx0/user"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
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
}
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,
)
}
@@ -1,4 +1,4 @@
package model
package store
import (
"context"
@@ -8,10 +8,9 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.kundeng.us/phoenix/textsender-models/pkg/user"
"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)
+2 -2
View File
@@ -8,12 +8,12 @@ type HashMash struct {
Password string
}
func (h HashMash) HashPassword() (string, error) {
func (h *HashMash) HashPassword() (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(h.Password), bcrypt.DefaultCost)
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))
return err == nil
}
+108 -16
View File
@@ -1,47 +1,139 @@
package utility
import (
"fmt"
"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/google/uuid"
"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
SecretKey []byte
hourOffset time.Duration
}
func (t *TokenGenerator) SetSecretKey(secretKey string) {
t.SecretKey = []byte(secretKey)
}
func (t *TokenGenerator) GenerateToken(user user.User) (*token.Login, error) {
issuedAt := time.Now()
expirationTime := time.Now().Add(4 * time.Hour)
claims := t.generateClaims(user, TOKEN_TYPE, issuedAt, expirationTime)
myToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
if tokenString, err := myToken.SignedString(t.SecretKey); err != nil {
return nil, err
func (t *TokenGenerator) SetHourOffset(offset time.Duration) error {
if offset < 48 {
t.hourOffset = offset
return nil
} 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 {
return token.Claims{
UserId: user.Id,
func (t *TokenGenerator) GenerateToken(usr any) (*token.Login, error) {
issuedAt := time.Now()
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()}, 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 != nil {
if clms.UserId != uuid.Nil {
return true, nil
} else {
return false, fmt.Errorf("User Id was not set")
}
} else {
return false, fmt.Errorf("Claims not parsed")
}
} 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 != nil {
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("Claims not parsed")
}
} 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,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: config.App_Name,
ExpiresAt: jwt.NewNumericDate(expiredAt),
IssuedAt: jwt.NewNumericDate(issuedAt),
},
}
}, nil
}
+7
View File
@@ -1,6 +1,7 @@
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
DROP TABLE IF EXISTS users CASCADE;
DROP TABLE IF EXISTS service_users CASCADE;
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
@@ -9,3 +10,9 @@ CREATE TABLE users (
password TEXT NOT NULL
);
CREATE TABLE service_users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
username TEXT NOT NULL,
passphrase TEXT NOT NULL,
created timestamptz DEFAULT now()
);