87 error handling + ajax + rest

This commit is contained in:
Artem.Arefev 2019-05-17 04:34:03 +04:00
parent b9748905d1
commit 6a62e61caf
8 changed files with 61 additions and 31 deletions

View File

@ -20,6 +20,7 @@ import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.service.UserService;
import java.util.Set;
@ -112,4 +113,9 @@ public class AdviceController {
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) {
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
}
@ExceptionHandler(UserSendingMailException.class)
public ResponseExtended<String> handleUserSendingMailException(Throwable e ) {
return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage());
}
}

View File

@ -6,14 +6,15 @@ public enum ErrorConstants {
VALIDATION_ERROR(2, "Validation error"),
USER_ID_EXISTS(100, "New user can't have id"),
USER_ACTIVATION_ERROR(101, "Invalid activation key"),
USER_EMAIL_EXISTS(102, "User with same email already exists"),
USER_LOGIN_EXISTS(103, "User with same login already exists"),
USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"),
USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"),
USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "Пароли введены неверно"),
USER_NOT_FOUND(105, "User is not found"),
USER_NOT_ACTIVATED(106, "User is not activated"),
USER_RESET_ERROR(107, "Invalid reset key"),
USER_UNDEAD_ERROR(108, "Can't edit/delete that user"),
FILE_UPLOAD_ERROR(110, "File upload error");
FILE_UPLOAD_ERROR(110, "File upload error"),
USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка");
private int code;
private String message;

View File

@ -3,6 +3,7 @@ package ru.ulstu.user.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -166,4 +167,9 @@ public class UserController extends OdinController<UserListDto, UserDto> {
User user = userSessionService.getUserBySessionId(sessionId);
userService.changeUserPassword(user, payload);
}
@PostMapping("/invite")
public void inviteUser(@RequestParam("email") String email) {
userService.inviteUser(email);
}
}

View File

@ -49,10 +49,4 @@ public class UserMvcController extends OdinController<UserListDto, UserDto> {
User user = userSessionService.getUserBySessionId(sessionId);
modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
}
@PostMapping("/invite")
public String inviteUser(@RequestParam(value = "email") String email, ModelMap modelMap) {
userService.inviteUser(email);
return "redirect:/";
}
}

View File

@ -40,7 +40,7 @@ public class MailService {
}
@Async
public void sendEmail(String to, String subject, String content) throws MessagingException {
public void sendEmail(String to, String subject, String content) throws MessagingException, MailException {
log.debug("Send email to '{}' with subject '{}'", to, subject);
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name());
@ -111,7 +111,7 @@ public class MailService {
sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET);
}
public void sendInviteMail(Map<String, Object> variables, String email) throws MessagingException {
public void sendInviteMail(Map<String, Object> variables, String email) throws MessagingException, MailException {
sendEmailFromTemplate(variables, "userInviteEmail", Constants.MAIL_INVITE, email);
}

View File

@ -5,6 +5,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.mail.MailException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -336,8 +337,8 @@ public class UserService implements UserDetailsService {
Map<String, Object> variables = ImmutableMap.of("password", password, "email", email);
try {
mailService.sendInviteMail(variables, email);
} catch (MessagingException e) {
throw new UserSendingMailException(INVITE_USER_EXCEPTION);
} catch (MessagingException | MailException e) {
throw new UserSendingMailException(email);
}
}
}

View File

@ -30,4 +30,28 @@ function changePassword() {
alert(errorData.responseJSON.error.message)
}
})
}
function inviteUser() {
email = document.getElementById("email").value;
re = /\S+@\S+\.\S+/;
if (!re.test(email)) {
alert("Некорректный почтовый ящик")
return;
}
$.ajax({
url:"/api/1.0/users/invite?email=" + email,
contentType: "application/json; charset=utf-8",
method: "POST",
success: function() {
document.getElementById("closeModalInvite").click();
alert("Пользователь был успешно приглашен");
},
error: function(errorData) {
alert(errorData.responseJSON.error.message)
}
})
}

View File

@ -2,29 +2,27 @@
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="headerfiles">
<meta charset="UTF-8"/>
<script src="js/users.js"></script>
</head>
<body>
<div id="inviteModal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
<form id="invite-form" method="post" action="/users/invite">
<div class="modal-header">
<h5 class="modal-title" id="label">Пригласить пользователя</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<input class="form-control" id="email" type="text"
placeholder="email" name="email"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Пригласить</button>
</div>
</form>
<div class="modal-header">
<h5 class="modal-title" id="label">Пригласить пользователя</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<input class="form-control" id="email" type="text"
placeholder="Email" name="email"/>
</div>
<div class="modal-footer">
<button id="closeModalInvite" type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть
</button>
<button type="button" onclick="inviteUser()" class="btn btn-primary">Отправить приглашение</button>
</div>
</div>
</div>
</div>