11package ru .javawebinar .topjava .web .user ;
22
33
4+ import org .springframework .lang .Nullable ;
45import org .springframework .stereotype .Component ;
6+ import org .springframework .util .Assert ;
57import org .springframework .util .StringUtils ;
68import org .springframework .validation .Errors ;
79import ru .javawebinar .topjava .HasIdAndEmail ;
810import ru .javawebinar .topjava .model .User ;
911import ru .javawebinar .topjava .repository .UserRepository ;
1012import ru .javawebinar .topjava .web .ExceptionInfoHandler ;
13+ import ru .javawebinar .topjava .web .SecurityUtil ;
1114
15+ import javax .servlet .http .HttpServletRequest ;
1216
1317@ Component
1418public class UniqueMailValidator implements org .springframework .validation .Validator {
1519
1620 private final UserRepository repository ;
21+ private final HttpServletRequest request ;
1722
18- public UniqueMailValidator (UserRepository repository ) {
23+ public UniqueMailValidator (UserRepository repository , @ Nullable HttpServletRequest request ) {
1924 this .repository = repository ;
25+ this .request = request ;
2026 }
2127
2228 @ Override
@@ -29,7 +35,18 @@ public void validate(Object target, Errors errors) {
2935 HasIdAndEmail user = ((HasIdAndEmail ) target );
3036 if (StringUtils .hasText (user .getEmail ())) {
3137 User dbUser = repository .getByEmail (user .getEmail ().toLowerCase ());
32- if (dbUser != null && !dbUser .getId ().equals (user .getId ())) {
38+ if (dbUser != null ) {
39+ Assert .notNull (request , "HttpServletRequest missed" );
40+ if (request .getMethod ().equals ("PUT" ) || (request .getMethod ().equals ("POST" ) && user .getId () != null )) { // update for REST(PUT) and UI(POST)
41+ int dbId = dbUser .id ();
42+ // it is ok, if update ourselves
43+ if (user .getId () != null && dbId == user .id ()) return ;
44+
45+ // workaround for update with user.id=null in request body
46+ // ValidationUtil.assureIdConsistent (id setter) called after this validation
47+ String requestURI = request .getRequestURI ();
48+ if (requestURI .endsWith ("/" + dbId ) || (dbId == SecurityUtil .get ().getId () && requestURI .contains ("/profile" ))) return ;
49+ }
3350 errors .rejectValue ("email" , ExceptionInfoHandler .EXCEPTION_DUPLICATE_EMAIL );
3451 }
3552 }
0 commit comments