Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e28db7552 | ||
|
|
976a017b4f |
@@ -1,3 +1,4 @@
|
||||
SECRET_KEY=XY0aIEg8qe0svz4IXUSIvxPdbDHIwoda
|
||||
DB_NAME=textsender_auth_db
|
||||
DB_USER=textsender_auth
|
||||
DB_PASSWORD=yEDjWZCH2vdctjn!
|
||||
|
||||
@@ -11,10 +11,10 @@ jobs:
|
||||
runs-on: ubuntu-24.04 # You can change this to macos-latest or windows-latest if needed
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.25.1' # You can specify a specific version or 'stable'
|
||||
|
||||
@@ -25,9 +25,68 @@ jobs:
|
||||
-X main.commit=${{ github.sha }} \
|
||||
-X main.date=$(date +%Y-%m-%dT%H:%M:%S%z)" \
|
||||
-o textsender-auth cmd/api/main.go
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-24.04
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17.5
|
||||
env:
|
||||
POSTGRES_USER: ${{ secrets.DB_TEST_USER }}
|
||||
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||
POSTGRES_DB: ${{ secrets.DB_TEST_NAME }}
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Test
|
||||
run: go test -v ./...
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.25.1'
|
||||
|
||||
- name: Install PostgreSQL client
|
||||
run: sudo apt update && sudo apt-get install -y postgresql-client
|
||||
|
||||
- name: Wait for PostgreSQL to be ready
|
||||
run: |
|
||||
for i in {1..30}; do
|
||||
if pg_isready -h postgres -p 5432; then
|
||||
echo "PostgreSQL is ready"
|
||||
exit 0
|
||||
fi
|
||||
echo "Waiting for PostgreSQL... Attempt $i"
|
||||
sleep 2
|
||||
done
|
||||
echo "PostgreSQL did not start in time"
|
||||
exit 1
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
DB_NAME: ${{ secrets.DB_TEST_NAME }}
|
||||
DB_USER: ${{ secrets.DB_TEST_USER }}
|
||||
DB_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
DB_SSLMODE: disable
|
||||
run: |
|
||||
echo "Parent directory"
|
||||
echo `pwd`
|
||||
|
||||
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
|
||||
|
||||
go test -v ./...
|
||||
|
||||
# - name: Run gofmt (optional)
|
||||
# Uncomment to check code formatting with gofmt
|
||||
|
||||
@@ -46,6 +46,7 @@ func main() {
|
||||
// Services
|
||||
userStore := model.NewUserStore(db.Pool)
|
||||
userHandler := handler.NewUserHandler(userStore)
|
||||
loginHandler := handler.NewLoginHandler(userStore)
|
||||
|
||||
router := chi.NewRouter()
|
||||
|
||||
@@ -55,6 +56,7 @@ func main() {
|
||||
router.Use(mdleware.JSONContentType)
|
||||
|
||||
router.Post(endpoint.Register, userHandler.Register)
|
||||
router.Post(endpoint.Login, loginHandler.Login)
|
||||
|
||||
// Start server
|
||||
server := &http.Server{
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
)
|
||||
|
||||
var testRouter *mux.Router
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
cfg := load()
|
||||
|
||||
db, err := db.NewDatabase(cfg.GetDBConnString())
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
panic("Failed to initialize database")
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
err = db.ResetDatabase(ctx)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
panic("Failed to initialize database")
|
||||
}
|
||||
|
||||
userStore := model.NewUserStore(db.Pool)
|
||||
userHandler := handler.NewUserHandler(userStore)
|
||||
|
||||
testRouter = mux.NewRouter()
|
||||
testRouter.HandleFunc(endpoint.Register, userHandler.Register).Methods("POST")
|
||||
|
||||
code := m.Run()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func load() *config.Config {
|
||||
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||
port := flag.String("port", config.Port, "Server port")
|
||||
flag.Parse()
|
||||
|
||||
cwd, _ := os.Getwd()
|
||||
envPath := path.Join(cwd, ".env")
|
||||
|
||||
err := godotenv.Load(envPath)
|
||||
if err != nil {
|
||||
envPath = path.Join(cwd, "../..", ".env")
|
||||
if err := godotenv.Load(envPath); err != nil {
|
||||
panic("Error loading .env file: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
unpackedConnString := config.UnpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &config.Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
}
|
||||
}
|
||||
|
||||
func resetTestDB(t *testing.T) {
|
||||
t.Helper()
|
||||
_, err := db.Pool.Exec(context.Background(), "DELETE FROM users")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to reset test database: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,24 @@ go 1.25.1
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/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
|
||||
golang.org/x/crypto v0.42.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // 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/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
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/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/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=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -15,13 +20,19 @@ 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/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
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/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
@@ -29,6 +40,8 @@ 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=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/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=
|
||||
|
||||
@@ -41,7 +41,7 @@ func Load() *Config {
|
||||
log.Fatal("Error loading .env file")
|
||||
}
|
||||
|
||||
unpackedConnString := unpackDBConnString()
|
||||
unpackedConnString := UnpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &Config{
|
||||
@@ -51,7 +51,11 @@ func Load() *Config {
|
||||
}
|
||||
}
|
||||
|
||||
func unpackDBConnString() (connInfo ConnectionInfo) {
|
||||
func GetSecretKey() string {
|
||||
return os.Getenv("SECRET_KEY")
|
||||
}
|
||||
|
||||
func UnpackDBConnString() (connInfo ConnectionInfo) {
|
||||
username := os.Getenv("DB_USER")
|
||||
password := os.Getenv("DB_PASSWORD")
|
||||
host := os.Getenv("DB_HOST")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -82,7 +83,13 @@ func (db *Database) ResetDatabase(ctx context.Context) error {
|
||||
|
||||
schemaContent, err := os.ReadFile("migrations/schema.sql")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading schema file: %v", err)
|
||||
log.Println("Default migrations not found. Checking different directory")
|
||||
cwd, _ := os.Getwd()
|
||||
migrationsPath := path.Join(cwd, "../..", "migrations/schema.sql")
|
||||
schemaContent, err = os.ReadFile(migrationsPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading schema file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
statements := strings.Split(string(schemaContent), ";")
|
||||
|
||||
@@ -2,3 +2,4 @@ package endpoint
|
||||
|
||||
// Endpoint for registering a user
|
||||
const Register = "/api/v1/register"
|
||||
const Login = "/api/v1/login"
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/config"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||
)
|
||||
|
||||
type LoginAccount struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []model.Login `json:"data"`
|
||||
}
|
||||
|
||||
type LoginHandler struct {
|
||||
UserStore model.UserStore
|
||||
}
|
||||
|
||||
func NewLoginHandler(userStore model.UserStore) *LoginHandler {
|
||||
return &LoginHandler{UserStore: userStore}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var statusCode int
|
||||
var resp LoginResponse
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
||||
fmt.Printf("Error: %v", err)
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
if !exists {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Failure in user check"
|
||||
} else {
|
||||
if user, err := l.UserStore.GetUserByUsername(ctx, req.Username); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
hashing := utility.HashMash{Password: req.Password}
|
||||
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
||||
var tokGen utility.TokenGenerator
|
||||
secretKey := config.GetSecretKey()
|
||||
tokGen.SetSecretKey(secretKey)
|
||||
if token, 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.Message = "Successful"
|
||||
}
|
||||
} else {
|
||||
statusCode = http.StatusNotFound
|
||||
resp.Message = "User not found"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RespondWithJson(w, statusCode, &resp)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||
)
|
||||
|
||||
func TestLogin(t *testing.T) {
|
||||
mockstore := NewMockUserStore()
|
||||
handler := NewLoginHandler(mockstore)
|
||||
|
||||
testUser := GetTestUser()
|
||||
unhashedPassword := testUser.Password
|
||||
hashing := utility.HashMash{Password: testUser.Password}
|
||||
hashedPassword, err := hashing.HashPassword()
|
||||
assert.NoError(t, err)
|
||||
|
||||
testUser.Password = hashedPassword
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
mockstore.CreateUser(ctx, &testUser)
|
||||
|
||||
loginUser := LoginAccount{Username: testUser.Username, Password: unhashedPassword}
|
||||
jsonValue, _ := json.Marshal(loginUser)
|
||||
|
||||
req, _ := http.NewRequest("POST", endpoint.Login, strings.NewReader(string(jsonValue)))
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.Login(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response LoginResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "An access token should have been returned")
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
)
|
||||
|
||||
type MockUserStore struct {
|
||||
Users map[uuid.UUID]*model.User
|
||||
UsersByUsername map[string]*model.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),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockUserStore) CreateUser(ctx context.Context, user *model.User) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.Error != nil {
|
||||
return m.Error
|
||||
}
|
||||
|
||||
if user.Id == uuid.Nil {
|
||||
user.Id = uuid.New()
|
||||
}
|
||||
|
||||
if _, exists := m.UsersByUsername[user.Username]; exists {
|
||||
return errors.New("User with email already exists")
|
||||
}
|
||||
|
||||
m.Users[user.Id] = user
|
||||
m.UsersByUsername[user.Username] = user
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*model.User, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.Error != nil {
|
||||
return nil, m.Error
|
||||
}
|
||||
|
||||
if m.Error != nil {
|
||||
return nil, m.Error
|
||||
}
|
||||
|
||||
user, exists := m.Users[id]
|
||||
if !exists {
|
||||
return nil, errors.New("User not found")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (m *MockUserStore) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.Error != nil {
|
||||
return nil, m.Error
|
||||
}
|
||||
|
||||
user, exists := m.UsersByUsername[username]
|
||||
if !exists {
|
||||
return nil, errors.New("User not found")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (m *MockUserStore) GetAllUsers(ctx context.Context) ([]*model.User, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.Error != nil {
|
||||
return nil, m.Error
|
||||
}
|
||||
|
||||
users := make([]*model.User, 0, len(m.Users))
|
||||
for _, user := range m.Users {
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (m *MockUserStore) UserExists(ctx context.Context, username string) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.Error != nil {
|
||||
return false, m.Error
|
||||
}
|
||||
|
||||
_, exists := m.UsersByUsername[username]
|
||||
if !exists {
|
||||
return exists, errors.New("User not found")
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package handler
|
||||
|
||||
import "net/http"
|
||||
import "encoding/json"
|
||||
import "fmt"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||
@@ -42,7 +40,8 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := extractUserFromReq(r)
|
||||
var req RegisterUser
|
||||
err := ExtractFromRequest(r, &req)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -50,6 +49,8 @@ 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{}
|
||||
|
||||
@@ -69,7 +70,7 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Failure in creating User"
|
||||
} else {
|
||||
hashing := utility.HashMash{user.Password}
|
||||
hashing := utility.HashMash{Password: user.Password}
|
||||
hashedPassword, err := hashing.HashPassword()
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
@@ -88,21 +89,5 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
respondWithJson(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
func extractUserFromReq(r *http.Request) (user model.User, myError error) {
|
||||
var usr RegisterUser
|
||||
err := json.NewDecoder(r.Body).Decode(&usr)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
return model.User{PhoneNumber: usr.PhoneNumber, Username: usr.Username, Password: usr.Password}, nil
|
||||
}
|
||||
|
||||
func respondWithJson(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||
w.Header().Set("Content-type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
RespondWithJson(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/db"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/handler/endpoint"
|
||||
)
|
||||
|
||||
func TestCreateUserWithMock(t *testing.T) {
|
||||
mockstore := NewMockUserStore()
|
||||
handler := NewUserHandler(mockstore)
|
||||
|
||||
testUser := GetTestUser()
|
||||
jsonValue, _ := json.Marshal(testUser)
|
||||
|
||||
req, _ := http.NewRequest("POST", endpoint.Register, strings.NewReader(string(jsonValue)))
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.Register(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response RegisterResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||
}
|
||||
|
||||
func resetTestDB(t *testing.T) {
|
||||
t.Helper()
|
||||
_, err := db.Pool.Exec(context.Background(), "DELETE FROM users")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to reset test database: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func RespondWithJson(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||
w.Header().Set("Content-type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
)
|
||||
|
||||
func GetTestUser() model.User {
|
||||
return model.User{Username: "ghost", PhoneNumber: "+1234567890", Password: "dfgdffddfd"}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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"`
|
||||
}
|
||||
@@ -21,7 +21,7 @@ type UserStore interface {
|
||||
GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*User, error)
|
||||
GetAllUsers(ctx context.Context) ([]*User, error)
|
||||
UserExists(ctx context.Context, email string) (bool, error)
|
||||
UserExists(ctx context.Context, username string) (bool, error)
|
||||
}
|
||||
|
||||
type PGUserStore struct {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package utility
|
||||
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package utility
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
)
|
||||
|
||||
type TokenGenerator struct {
|
||||
SecretKey []byte
|
||||
}
|
||||
|
||||
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")
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
if tokenString, err := token.SignedString(t.SecretKey); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return &model.Login{AccessToken: tokenString}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TokenGenerator) generateClaims(user model.User, role string) model.Claims {
|
||||
return model.Claims{
|
||||
UserId: user.Id.String(),
|
||||
Role: role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: "textsender-auth",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user