Added skeleton code for register endpoint (#2)
Reviewed-on: phoenix/textsender-auth#2 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DBConnString string
|
||||
ServerPort string
|
||||
ResetDB bool
|
||||
}
|
||||
|
||||
type ConnectionInfo struct {
|
||||
Username string
|
||||
Password string
|
||||
Database string
|
||||
Host string
|
||||
Port int
|
||||
SslMode string
|
||||
}
|
||||
|
||||
const Port = "9080"
|
||||
|
||||
func (ci ConnectionInfo) Parse() string {
|
||||
return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", ci.Username, ci.Password, ci.Host, ci.Port, ci.Database, ci.SslMode)
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||
port := flag.String("port", Port, "Server port")
|
||||
flag.Parse()
|
||||
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Fatal("Error loading .env file")
|
||||
}
|
||||
|
||||
unpackedConnString := unpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
}
|
||||
}
|
||||
|
||||
func unpackDBConnString() (connInfo ConnectionInfo) {
|
||||
username := os.Getenv("DB_USER")
|
||||
password := os.Getenv("DB_PASSWORD")
|
||||
host := os.Getenv("DB_HOST")
|
||||
port := os.Getenv("DB_PORT")
|
||||
database := os.Getenv("DB_NAME")
|
||||
sslMode := os.Getenv("DB_SSLMODE")
|
||||
|
||||
if username != "" {
|
||||
connInfo.Username = username
|
||||
} else {
|
||||
connInfo.Username = "user"
|
||||
}
|
||||
|
||||
if password != "" {
|
||||
connInfo.Password = password
|
||||
} else {
|
||||
connInfo.Password = "password"
|
||||
}
|
||||
|
||||
if host != "" {
|
||||
connInfo.Host = host
|
||||
} else {
|
||||
connInfo.Host = "localhost"
|
||||
}
|
||||
|
||||
if port != "" {
|
||||
num, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
connInfo.Port = num
|
||||
} else {
|
||||
connInfo.Port = 5432
|
||||
}
|
||||
|
||||
if database != "" {
|
||||
connInfo.Database = database
|
||||
} else {
|
||||
connInfo.Database = "textsender_auth_db"
|
||||
}
|
||||
|
||||
if sslMode != "" {
|
||||
connInfo.SslMode = sslMode
|
||||
} else {
|
||||
connInfo.SslMode = "disable"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Config) GetDBConnString() string {
|
||||
return c.DBConnString
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// db/connection.go
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var Pool *pgxpool.Pool
|
||||
|
||||
type Database struct {
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewDatabase(connString string) (*Database, error) {
|
||||
ctx := context.Background()
|
||||
// Parse the connection string and create pool configuration
|
||||
config, err := pgxpool.ParseConfig(connString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to parse DSN: %v", err)
|
||||
}
|
||||
|
||||
// Configure connection pool settings
|
||||
config.MaxConns = 25
|
||||
config.MinConns = 5
|
||||
config.MaxConnLifetime = time.Hour
|
||||
config.MaxConnIdleTime = 30 * time.Minute
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
|
||||
// Configure connection timeouts
|
||||
config.ConnConfig.ConnectTimeout = 10 * time.Second
|
||||
config.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
|
||||
// Create the connection pool
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to create connection pool: %v", err)
|
||||
}
|
||||
|
||||
// Test the connection with a short timeout
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("unable to ping database: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Successfully connected to database")
|
||||
return &Database{Pool: pool}, nil
|
||||
}
|
||||
|
||||
func (db *Database) Close() {
|
||||
if db.Pool != nil {
|
||||
db.Pool.Close()
|
||||
log.Println("Database connection pool closed")
|
||||
}
|
||||
}
|
||||
|
||||
// HealthCheck verifies the database connection is still alive
|
||||
func (db *Database) HealthCheck(ctx context.Context) error {
|
||||
return db.Pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// GetPoolStats returns connection pool statistics
|
||||
func (db *Database) GetPoolStats() string {
|
||||
stats := db.Pool.Stat()
|
||||
return fmt.Sprintf("TotalConns: %d, IdleConns: %d, AcquiredConns: %d",
|
||||
stats.TotalConns(), stats.IdleConns(), stats.AcquiredConns())
|
||||
}
|
||||
|
||||
func (db *Database) ResetDatabase(ctx context.Context) error {
|
||||
tx, err := db.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Transaction unable to begin: %v", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
schemaContent, err := os.ReadFile("migrations/schema.sql")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading schema file: %v", err)
|
||||
}
|
||||
|
||||
statements := strings.Split(string(schemaContent), ";")
|
||||
|
||||
for _, stmt := range statements {
|
||||
stmt = strings.TrimSpace(stmt)
|
||||
if stmt == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(stmt, "--") {
|
||||
continue
|
||||
}
|
||||
|
||||
_, err := tx.Exec(ctx, stmt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error executing SQL statement: %v\nStatement: %s", err, stmt)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("unable to commit transaction: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Database schema applied successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package endpoint
|
||||
|
||||
// Endpoint for registering a user
|
||||
const Register = "/api/v1/register"
|
||||
@@ -0,0 +1,108 @@
|
||||
package handler
|
||||
|
||||
import "net/http"
|
||||
import "encoding/json"
|
||||
import "fmt"
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/model"
|
||||
"git.kundeng.us/phoenix/textsender-auth/internal/utility"
|
||||
)
|
||||
|
||||
type RegisterUser struct {
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type RegisterResponseItem struct {
|
||||
Id uuid.UUID `json:"id"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
type RegisterResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []RegisterResponseItem `json:"data"`
|
||||
}
|
||||
|
||||
type UserHandler struct {
|
||||
UserStore model.UserStore
|
||||
}
|
||||
|
||||
func NewUserHandler(userStore model.UserStore) *UserHandler {
|
||||
return &UserHandler{UserStore: userStore}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := extractUserFromReq(r)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
var statusCode int
|
||||
resp := RegisterResponse{}
|
||||
|
||||
fmt.Println("Username:", user.Username)
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
exists, err := h.UserStore.UserExists(ctx, user.Username)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %v", err)
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
}
|
||||
|
||||
if exists {
|
||||
// User already exists
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Failure in creating User"
|
||||
} else {
|
||||
hashing := utility.HashMash{user.Password}
|
||||
hashedPassword, err := hashing.HashPassword()
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
user.Password = hashedPassword
|
||||
err := h.UserStore.CreateUser(ctx, &user)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
resp.Message = "Successful"
|
||||
statusCode = http.StatusOK
|
||||
resp.Data = append(resp.Data, RegisterResponseItem{Id: user.Id, PhoneNumber: user.PhoneNumber, Username: user.Username})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
respondWithJson(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
func JSONContentType(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package model
|
||||
@@ -0,0 +1,120 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id uuid.UUID `json:"id"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserStore interface {
|
||||
CreateUser(ctx context.Context, user *User) error
|
||||
GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*User, error)
|
||||
GetAllUsers(ctx context.Context) ([]*User, error)
|
||||
UserExists(ctx context.Context, email string) (bool, error)
|
||||
}
|
||||
|
||||
type PGUserStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserStore(db *pgxpool.Pool) *PGUserStore {
|
||||
return &PGUserStore{db: db}
|
||||
}
|
||||
|
||||
func (s *PGUserStore) CreateUser(ctx context.Context, user *User) error {
|
||||
query := `
|
||||
INSERT INTO users (phone_number, username, password)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, phone_number, username
|
||||
`
|
||||
|
||||
return s.db.QueryRow(ctx, query, user.PhoneNumber, user.Username, user.Password).Scan(
|
||||
&user.Id, &user.PhoneNumber, &user.Username,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *PGUserStore) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
query := `SELECT id, username, password, phone_number FROM users WHERE id = $1`
|
||||
|
||||
var user User
|
||||
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||
)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting user by ID: %w", err)
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PGUserStore) GetUserByUsername(ctx context.Context, username string) (*User, error) {
|
||||
query := `SELECT id, username, password, phone_number FROM users WHERE username = $1`
|
||||
|
||||
var user User
|
||||
err := s.db.QueryRow(ctx, query, username).Scan(
|
||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||
)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting user by ID: %w", err)
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PGUserStore) GetAllUsers(ctx context.Context) ([]*User, error) {
|
||||
query := `SELECT id, username, password, phone_number FROM users`
|
||||
|
||||
rows, err := s.db.Query(ctx, query)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("querying all users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*User
|
||||
for rows.Next() {
|
||||
var user User
|
||||
if err := rows.Scan(
|
||||
&user.Id, &user.Username, &user.Password, &user.PhoneNumber,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scanning user row: %w", err)
|
||||
}
|
||||
users = append(users, &user)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterating user rows: %w", err)
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (s *PGUserStore) UserExists(ctx context.Context, username string) (bool, error) {
|
||||
query := `SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)`
|
||||
|
||||
var exists bool
|
||||
err := s.db.QueryRow(ctx, query, username).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("checking if user exists: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package utility
|
||||
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type HashMash struct {
|
||||
Password string
|
||||
}
|
||||
|
||||
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 {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (h *HashMash) SetPassword(password string) {
|
||||
h.Password = password
|
||||
}
|
||||
Reference in New Issue
Block a user