173 lines
4.6 KiB
Go
173 lines
4.6 KiB
Go
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
|
|
}
|