Validate email local part when creating users
- Check length (1-64 characters) - Allow only valid email characters (RFC 5321) - Return ValidationError with descriptive message
This commit is contained in:
parent
36258bf53c
commit
f9ddfa869e
1 changed files with 28 additions and 0 deletions
|
|
@ -3,7 +3,9 @@ package handlers
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/imc-vibe/backend/internal/db"
|
"github.com/imc-vibe/backend/internal/db"
|
||||||
|
|
@ -129,6 +131,12 @@ func (h *UserHandler) Create(c *gin.Context) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate email local part (before @)
|
||||||
|
if err := validateEmailLocalPart(req.Email); err != nil {
|
||||||
|
Error(c, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
existing, _ := h.db.GetUserByEmail(req.Email)
|
existing, _ := h.db.GetUserByEmail(req.Email)
|
||||||
if existing != nil {
|
if existing != nil {
|
||||||
Error(c, http.StatusConflict, "user already exists")
|
Error(c, http.StatusConflict, "user already exists")
|
||||||
|
|
@ -254,3 +262,23 @@ func (h *UserHandler) ListAll(c *gin.Context) {
|
||||||
|
|
||||||
Success(c, users)
|
Success(c, users)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var emailLocalPartRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\-/=?^_`{|}~-]+$")
|
||||||
|
|
||||||
|
func validateEmailLocalPart(email string) error {
|
||||||
|
parts := strings.Split(email, "@")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return &ValidationError{Message: "invalid email format"}
|
||||||
|
}
|
||||||
|
|
||||||
|
localPart := parts[0]
|
||||||
|
if len(localPart) < 1 || len(localPart) > 64 {
|
||||||
|
return &ValidationError{Message: "username must be between 1 and 64 characters"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !emailLocalPartRegex.MatchString(localPart) {
|
||||||
|
return &ValidationError{Message: "username can only contain letters, numbers, and common special characters"}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue