Skip to content

Commit

Permalink
feat: email unico
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiomsrs committed Jun 29, 2021
1 parent 0309d11 commit e5e6e4a
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package br.com.zupacademy.fabiano.mercadolivre.dto;

import br.com.zupacademy.fabiano.mercadolivre.modelo.Usuario;
import br.com.zupacademy.fabiano.mercadolivre.validator.ValorUnico;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.validation.constraints.*;
Expand All @@ -9,6 +10,7 @@ public class UsuarioRegisterDto {
@NotNull
@NotEmpty
@Email
@ValorUnico(field = "login", instanceClass = Usuario.class)
private String login;
@NotNull
@NotEmpty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class Usuario {
@NotNull
@NotEmpty
@Email
@Column(nullable = false)
@Column(nullable = false, unique = true)
private String login;
@NotNull
@NotEmpty
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package br.com.zupacademy.fabiano.mercadolivre.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = ValorUnicoValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValorUnico {
String message() default "Restricao valor unico";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
Class instanceClass();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package br.com.zupacademy.fabiano.mercadolivre.validator;

import javax.persistence.EntityManager;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ValorUnicoValidator implements ConstraintValidator<ValorUnico, Object> {
private EntityManager em;

private Class<?> object;
private String field;

public ValorUnicoValidator(EntityManager em) {
this.em = em;
}

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return this.em.createQuery("select 1 from "+this.object.getName()+" where "+ field+"=:field")
.setParameter("field",value)
.getResultList()
.isEmpty();
}

@Override
public void initialize(ValorUnico constraintAnnotation) {
this.object = constraintAnnotation.instanceClass();
this.field = constraintAnnotation.field();
ConstraintValidator.super.initialize(constraintAnnotation);
}
}

0 comments on commit e5e6e4a

Please sign in to comment.