Skip to content

Commit

Permalink
feat(validation): signin/signup request validation
Browse files Browse the repository at this point in the history
  • Loading branch information
lukewhrit committed Nov 19, 2024
1 parent 7757bc2 commit c62343c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
1 change: 1 addition & 0 deletions internal/server/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func (s *Server) SignUp(w http.ResponseWriter, r *http.Request) {
Username: "luke",
Password: "password",
}

// Do validation
// Make sure password is secure, make sure username does not exist

Expand Down
25 changes: 20 additions & 5 deletions internal/util/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,26 @@ import (
"github.com/rs/zerolog/log"
)

func ValidateBody(maxSize int, body CreateRequest) error {
return validation.ValidateStruct(&body,
validation.Field(&body.Content, validation.Required,
validation.Length(2, maxSize)),
)
func ValidateBody[T CreateRequest | SigninRequest | SignupRequest](maxSize int, body T) error {
switch v := any(body).(type) {
case CreateRequest:
return validation.ValidateStruct(&v,
validation.Field(&v.Content, validation.Required, validation.Length(2, maxSize)),
)
case SigninRequest:
return validation.ValidateStruct(&v,
validation.Field(&v.Username, validation.Required),
validation.Field(&v.Password, validation.Required, validation.Length(16, 128)),
)
case SignupRequest:
return validation.ValidateStruct(&v,
validation.Field(&v.Username, validation.Required),
validation.Field(&v.Password, validation.Required, validation.Length(16, 128)),
)
default:
return validation.Errors{"body": validation.NewError("validation_error", "unsupported request type")}

Check warning on line 49 in internal/util/helpers.go

View check run for this annotation

Codecov / codecov/patch

internal/util/helpers.go#L38-L49

Added lines #L38 - L49 were not covered by tests
}

}

// HandleBody figures out whether a incoming request is in JSON or multipart/form-data and decodes it appropriately
Expand Down

0 comments on commit c62343c

Please sign in to comment.