feat(authentication): Added authentication controller & JWTMiddleware

This commit is contained in:
2026-05-28 17:58:20 +03:30
parent bdb2fcc68f
commit 0b4cb868e7
9 changed files with 603 additions and 64 deletions
+23 -11
View File
@@ -14,6 +14,7 @@ import (
"github.com/go-chi/cors"
"medad.fun/internal/api"
"medad.fun/internal/api/v1/middleware"
"medad.fun/internal/config"
"medad.fun/internal/database"
"medad.fun/internal/frontend"
@@ -26,7 +27,6 @@ func main() {
if err != nil {
log.Fatalln("error loading configuration:", err)
}
log.Printf("Starting medad.fun server version '%s'\n", version.Version)
if cfg.CPUProfilePath != "" {
@@ -45,14 +45,29 @@ func main() {
AllowedOrigins: cfg.CORS.AllowedOrigins,
AllowCredentials: cfg.CORS.AllowCredentials,
})
register := func(method, path string, handler http.HandlerFunc) {
// Each path needs to start with a slash anyway, so this is convenient.
if !strings.HasPrefix(path, "/") {
path = "/" + path
// 1. Create a basic register function for public routes
register := func(method, p string, handler http.HandlerFunc) {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
log.Printf("Registering route: %s %s\n", method, p)
// Wrap with CORS
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(handler).ServeHTTP)
}
log.Printf("Registering route: %s %s\n", method, path)
router.HandleFunc(fmt.Sprintf("%s %s", method, path), corsWrapper(handler).ServeHTTP)
// 2. Create a protected register function for authenticated routes
// This wraps the handler in JWT middleware BEFORE CORS
protectedRegister := func(method, p string, handler http.HandlerFunc) {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
log.Printf("Registering PROTECTED route: %s %s\n", method, p)
// Chain: JWT Middleware -> CORS Wrapper -> Actual Handler
// Note: JWT checks auth first. If valid, it passes to CORS, then handler.
protectedHandler := middleware.JWTMiddleware([]byte(cfg.JWTSecret))(http.HandlerFunc(handler))
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(protectedHandler).ServeHTTP)
}
// Healthcheck for deployments with monitoring if required.
@@ -60,7 +75,7 @@ func main() {
writer.WriteHeader(http.StatusOK)
})
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register)
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register, protectedRegister)
frontendHandler, err := frontend.NewHandler(cfg)
if err != nil {
@@ -76,9 +91,7 @@ func main() {
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
defer os.Exit(0)
log.Printf("Received %s, gracefully shutting down.\n", <-signalChan)
state.ShutdownLobbiesGracefully()
if cfg.CPUProfilePath != "" {
pprof.StopCPUProfile()
@@ -97,7 +110,6 @@ func main() {
if r.URL.Path != "/" && r.URL.Path[len(r.URL.Path)-1] == '/' {
r.URL.Path = r.URL.Path[:len(r.URL.Path)-1]
}
router.ServeHTTP(w, r)
}),
ReadHeaderTimeout: 10 * time.Second,
+10 -3
View File
@@ -7,13 +7,16 @@ require (
github.com/Bios-Marcel/go-petname v0.0.1
github.com/caarlos0/env/v11 v11.3.1
github.com/go-chi/cors v1.2.2
github.com/go-playground/validator/v10 v10.30.2
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/jackc/pgx/v5 v5.9.2
github.com/lxzan/gws v1.8.9
github.com/prometheus/client_golang v1.23.2
github.com/stretchr/testify v1.11.1
github.com/subosito/gotenv v1.6.0
golang.org/x/text v0.33.0
golang.org/x/crypto v0.49.0
golang.org/x/text v0.37.0
)
require (
@@ -21,19 +24,23 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dolthub/maphash v0.1.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.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/klauspost/compress v1.18.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.44.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+22 -6
View File
@@ -14,10 +14,22 @@ 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/dolthub/maphash v0.1.0 h1:bsQ7JsF4FkkWyrP3oCnFJgrCUAFbFf3kOl4L/QxPDyQ=
github.com/dolthub/maphash v0.1.0/go.mod h1:gkg4Ch4CdCDu5h6PMriVLawB7koZ+5ijb9puGMV50a4=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
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-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=
github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=
github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=
github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
@@ -36,6 +48,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lxzan/gws v1.8.9 h1:VU3SGUeWlQrEwfUSfokcZep8mdg/BrUF+y73YYshdBM=
github.com/lxzan/gws v1.8.9/go.mod h1:d9yHaR1eDTBHagQC6KY7ycUOaz5KWeqQtP3xu7aMK8Y=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
@@ -63,12 +77,14 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+13 -43
View File
@@ -1,72 +1,42 @@
package api
import (
"log"
"net/http"
"path"
"strings"
"medad.fun/internal/database"
controller "medad.fun/internal/api/v1"
"medad.fun/internal/metrics"
)
// SetupRoutes registers the /v1/ endpoints with the http package.
func (handler *V1Handler) SetupRoutes(rootPath string, register func(string, string, http.HandlerFunc)) {
func (handler *V1Handler) SetupRoutes(rootPath string, register func(string, string, http.HandlerFunc), protectedRegister func(string, string, http.HandlerFunc)) {
v1 := path.Join(rootPath, "v1")
// Public Metrics
metrics.SetupRoute(func(metricsHandler http.HandlerFunc) {
register("GET", path.Join(v1, "metrics"), metricsHandler)
})
// Public Stats
register("GET", path.Join(v1, "stats"), handler.getStats)
// These exist only for the public API. We version them in order to ensure
// backwards compatibility as far as possible.
// Public Lobby Endpoints
register("GET", path.Join(v1, "lobby"), handler.getLobbies)
register("POST", path.Join(v1, "lobby"), handler.postLobby)
protectedRegister("POST", path.Join(v1, "lobby"), handler.postLobby)
register("PATCH", path.Join(v1, "lobby", "{lobby_id}"), handler.patchLobby)
// We support both path parameter and cookie.
register("PATCH", path.Join(v1, "lobby"), handler.patchLobby)
// The websocket is shared between the public API and the official client
// WebSocket is usually shared, but if you want to secure it, use protectedRegister
register("GET", path.Join(v1, "lobby", "{lobby_id}", "ws"), handler.websocketUpgrade)
// We support both path parameter and cookie.
register("GET", path.Join(v1, "lobby", "ws"), handler.websocketUpgrade)
register("POST", path.Join(v1, "lobby", "{lobby_id}", "player"), handler.postPlayer)
// Protected Player Action
protectedRegister("POST", path.Join(v1, "lobby", "{lobby_id}", "player"), handler.postPlayer)
register("POST", path.Join(v1, "s1mple"), func(w http.ResponseWriter, r *http.Request) {
rows, err := database.Pool.Query(r.Context(), "SELECT id, name FROM my_table")
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
defer rows.Close()
log.Println(rows)
var data []map[string]interface{}
for rows.Next() {
var id int
var name string
if err := rows.Scan(&id, &name); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
data = append(data, map[string]interface{}{
"id": id,
"name": name,
})
}
log.Println(data)
if started, err := marshalToHTTPWriter(data, w); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
})
// Auth Endpoints (Register/Login) are Public
register("POST", path.Join(v1, "auth", "register"), controller.Register)
register("POST", path.Join(v1, "auth", "login"), controller.Login)
}
// remoteAddressToSimpleIP removes unnecessary clutter from the input,
+246
View File
@@ -0,0 +1,246 @@
package controller
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/gofrs/uuid/v5"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"medad.fun/internal/config"
"medad.fun/internal/database"
"medad.fun/internal/database/models"
)
type registerBody struct {
Name string `json:"name" validate:"required"`
Username string `json:"username" validate:"required_without_all=Phone Email,omitempty,unique=user&username,min=4,max=24"`
Email string `json:"email" validate:"required_without_all=Phone Username,omitempty,unique=user&email,email"`
Phone string `json:"phone" validate:"required_without_all=Email Username,omitempty,unique=user&phone,min=11,max=11"`
Password string `json:"password" validate:"required"`
}
type loginBody struct {
Login string `json:"login" validate:"required"`
Password string `json:"password" validate:"required"`
}
func Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var userReq registerBody
if err := json.Unmarshal(body, &userReq); err != nil {
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return
}
userReq.Email = strings.ToLower(userReq.Email)
userReq.Username = strings.ToLower(userReq.Username)
// rows, err := database.Pool.Query(r.Context(), "SELECT id, name FROM my_table")
// if err != nil {
// http.Error(w, "Internal server error", http.StatusInternalServerError)
// return
// }
// defer rows.Close()
// var data []map[string]interface{}
// for rows.Next() {
// var id int
// var name string
// if err := rows.Scan(&id, &name); err != nil {
// http.Error(w, "Internal server error", http.StatusInternalServerError)
// return
// }
// data = append(data, map[string]interface{}{
// "id": id,
// "name": name,
// })
// }
// validate input
validate := validator.New()
validate.RegisterValidation("unique", NewUniqueValidator(database.Pool))
err = validate.Struct(userReq)
if err != nil {
if started, err := marshalToHTTPWriterError(w, err, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
return
}
// // unique validation
// var count int
// if err := database.Pool.QueryRow(r.Context(), `SELECT count(id) FROM "user" WHERE username = $1 OR email = $2 OR phone = $3 LIMIT 1`,
// strings.ToLower(userReq.Username),
// strings.ToLower(userReq.Email),
// userReq.Phone,
// ).Scan(&count); err != nil || count > 0 {
// if started, err := marshalToHTTPWriterError(w, validator.ValidationErrors{validator.FieldError}, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
// if !started {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// }
// return
// }
// return
// }
// register user
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(userReq.Password), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
user := models.UserModel{}
insert_err := database.Pool.QueryRow(r.Context(), `INSERT INTO "user"(id, name, username, email, phone, password) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
uuid.Must(uuid.NewV4()),
userReq.Name,
strings.ToLower(userReq.Username),
strings.ToLower(userReq.Email),
userReq.Phone,
hashedPassword,
).Scan(
&user.ID,
&user.Name,
&user.Username,
&user.Email,
&user.Phone,
&user.Password,
&user.CreatedAt,
&user.UpdatedAt,
)
if insert_err != nil {
log.Print(insert_err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Sign JWT
claims := jwt.MapClaims{
"user_id": user.ID,
"is_admin": false,
"exp": time.Now().Add(time.Hour * 24 * 90).Unix(), // Token expires in 90 days
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString([]byte(config.CachedConfig.JWTSecret))
if err != nil {
log.Fatalf("Error signing token: %v", err)
}
if started, err := marshalToHTTPWriter(w, map[string]any{"token": signedToken, "user": user}, "register|user"); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
func Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var req loginBody
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return
}
// validate input
validate := validator.New()
err = validate.Struct(req)
if err != nil {
if started, err := marshalToHTTPWriterError(w, err, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
return
}
rows, err := database.Pool.Query(r.Context(), `SELECT id, password FROM "user" WHERE username = $1 OR email = $1 OR phone = $1 LIMIT 3`, strings.ToLower(req.Login))
if err != nil {
log.Print(err)
if started, err := marshalToHTTPWriterError(w, nil, "not_found|user", http.StatusNotFound); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
return
}
defer rows.Close()
var token string
for rows.Next() {
var id string
var password string
if err := rows.Scan(&id, &password); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if bcrypt.CompareHashAndPassword([]byte(password), []byte(req.Password)) == nil {
// Sign JWT
claims := jwt.MapClaims{
"user_id": id,
"is_admin": false,
"exp": time.Now().Add(time.Hour * 24 * 90).Unix(), // Token expires in 90 days
}
token_claim := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err = token_claim.SignedString([]byte(config.CachedConfig.JWTSecret))
if err != nil {
log.Fatalf("Error signing token: %v", err)
}
}
}
// no user matched
if token == "" {
if started, err := marshalToHTTPWriterError(w, nil, "not_found|user", http.StatusNotFound); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
return
}
if started, err := marshalToHTTPWriter(w, map[string]any{"token": token}, "login|user"); err != nil {
if !started {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
+172
View File
@@ -0,0 +1,172 @@
package controller
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/golang-jwt/jwt/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type Response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Data any `json:"data,omitempty"`
Errors any `json:"errors,omitempty"`
}
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}
func marshalToHTTPWriter(writer http.ResponseWriter, data any, message string) (bool, error) {
response := Response{Success: true, Message: message, Data: data}
bytes, err := json.Marshal(response)
if err != nil {
return false, err
}
writer.Header().Set("Content-Type", "application/json")
writer.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
_, err = writer.Write(bytes)
return true, err
}
func marshalToHTTPWriterError(writer http.ResponseWriter, errors error, message string, status int) (bool, error) {
fieldErrors := make(map[string][]string)
// Ensure it's a ValidationErrors type
validationErrs, ok := errors.(validator.ValidationErrors)
if ok {
for _, e := range validationErrs {
fieldErrors[e.Field()] = append(fieldErrors[e.Field()], e.Tag())
}
}
response := Response{Success: false, Message: message, Errors: fieldErrors}
bytes, err := json.Marshal(response)
if err != nil {
log.Print(err)
return false, err
}
writer.Header().Set("Content-Type", "application/json")
writer.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
writer.WriteHeader(status)
_, err = writer.Write(bytes)
return true, err
}
type CustomClaims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
jwt.RegisteredClaims
}
func createTokenWithCustomClaims() (string, error) {
claims := CustomClaims{
UserID: 123,
Username: "johndoe",
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(os.Getenv("JWT_SECRET"))
}
func parseCustomToken(signedToken string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(signedToken, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return os.Getenv("JWT_SECRET"), nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*CustomClaims)
if !ok {
return nil, fmt.Errorf("invalid claims type")
}
return claims, nil
}
func NewUniqueValidator(dbPool *pgxpool.Pool) validator.Func {
return func(fl validator.FieldLevel) bool {
// 1. Get the field value
fieldValue := fl.Field().String()
if fieldValue == "" {
return true // If empty, let 'required' handle it
}
// 2. Get the tag value (e.g., "users,email")
tag := fl.Param()
if tag == "" {
return true
}
// 3. Parse the tag: table,column
// We use strings.Split because the format is strict
parts := strings.Split(tag, "&")
if len(parts) != 2 {
log.Printf("Invalid unique tag format for field %s: %s. Expected 'table&column'", fl.FieldName(), tag)
return false
}
tableName := parts[0]
columnName := parts[1]
// Basic validation for SQL injection prevention (optional but recommended)
// Ensure table/column names only contain alphanumeric chars and underscores
if !isValidIdentifier(tableName) || !isValidIdentifier(columnName) {
log.Printf("Invalid table or column name for field %s", fl.FieldName())
return false
}
// 4. Execute the query
query := fmt.Sprintf("SELECT 1 FROM \"%s\" WHERE %s = $1 LIMIT 1", tableName, columnName)
var exists int
err := dbPool.QueryRow(context.Background(), query, fieldValue).Scan(&exists)
if err != nil {
// If the row doesn't exist, err is pgx.ErrNoRows
if err.Error() == "no rows in result set" || err.Error() == "pgx: no rows in result set" {
return true // Unique
}
// Other DB errors
log.Printf("DB error checking uniqueness for %s: %v", fl.FieldName(), err)
return false
}
// If we got here, a row was found
return exists == 0
}
}
// isValidIdentifier checks if a string is a valid SQL identifier (simplified)
func isValidIdentifier(s string) bool {
if len(s) == 0 {
return false
}
for _, r := range s {
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
return false
}
}
return true
}
@@ -0,0 +1,89 @@
package middleware
import (
"context"
"errors"
"log"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
// ContextKey is a custom type for context keys to avoid collisions.
type contextKey string
const (
UserIDKey contextKey = "user_id"
IsAdminKey contextKey = "is_admin"
)
// Claims extends the standard JWT claims to include our custom fields.
type Claims struct {
UserID string `json:"user_id"`
IsAdmin bool `json:"is_admin"` // e.g., "user", "admin"
jwt.RegisteredClaims
}
// JWTMiddleware creates a middleware that validates JWT tokens.
// It expects the token in the "Authorization" header as "Bearer <token>".
func JWTMiddleware(secretKey []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 1. Extract the Authorization header
authHeader := r.Header.Get("Authorization")
// if authHeader == "" {
// http.Error(w, "Missing Authorization header", http.StatusUnauthorized)
// return
// }
// 2. Parse the Bearer token
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
// if tokenString == authHeader {
// http.Error(w, "Invalid Authorization header format", http.StatusUnauthorized)
// return
// }
// 3. Parse and Validate the Token
claims := Claims{}
CheckJWT(&claims, tokenString)
// token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
// // Validate signing method
// if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
// return nil, errors.New("unexpected signing method: " + token.Method.Alg())
// }
// return secretKey, nil
// })
// if err != nil || !token.Valid {
// http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
// return
// }
log.Print(claims.UserID)
// 4. Attach claims to the request context
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
ctx = context.WithValue(ctx, IsAdminKey, claims.IsAdmin)
// 5. Call the next handler in the chain
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequireAuth is a helper to easily apply JWT middleware to a specific handler.
// This is useful if you want to protect specific routes without changing the global register function.
func RequireAuth(secretKey []byte, handler http.HandlerFunc) http.Handler {
return JWTMiddleware(secretKey)(http.HandlerFunc(handler))
}
func CheckJWT(claims *Claims, tokenString string) (*jwt.Token, error) {
return jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
// Validate signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method: " + token.Method.Alg())
}
return "", nil
})
}
+10
View File
@@ -75,6 +75,9 @@ type Config struct {
// Database Related configurations
DatabaseURL string `env:"DATABASE_URL"`
// ENV
JWTSecret string `env:"JWT_SECRET"`
}
var Default = Config{
@@ -117,6 +120,9 @@ var Default = Config{
// Load loads the configuration from the environment. If a .env file is
// available, it will be loaded as well. Values found in the environment
// will overwrite whatever is load from the .env file.
var CachedConfig *Config
func Load() (*Config, error) {
envVars := make(map[string]string)
@@ -176,5 +182,9 @@ func Load() (*Config, error) {
}
config.RootPath = strings.Trim(config.RootPath, "/")
if CachedConfig == nil {
CachedConfig = &config
}
return &config, nil
}
+17
View File
@@ -0,0 +1,17 @@
package models
import (
"github.com/gofrs/uuid/v5"
"github.com/jackc/pgx/v5/pgtype"
)
type UserModel struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Phone string `json:"phone"`
Password string `json:"-"`
CreatedAt pgtype.Timestamp `json:"createdAt"`
UpdatedAt pgtype.Timestamp `json:"updatedAt"`
}