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
+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"`
}