Merge branch '72-link-to-timetable' into 'dev'

Resolve "Ссылка на расписание пользователя"

Closes #72

See merge request romanov73/ng-tracker!31
This commit is contained in:
Anton Romanov 2019-03-13 07:16:32 +00:00
commit ae58a5b6e4
8 changed files with 498 additions and 420 deletions

View File

@ -58,7 +58,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.anyRequest() .anyRequest()
.permitAll(); .permitAll();
http.anonymous() http.anonymous()
.principal("developer") .principal("admin")
.authorities(UserRoleConstants.ADMIN); .authorities(UserRoleConstants.ADMIN);
} else { } else {
log.debug("Security enabled"); log.debug("Security enabled");

View File

@ -1,100 +1,116 @@
package ru.ulstu.core.controller; package ru.ulstu.core.controller;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError; import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.ModelAttribute;
import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.model.ErrorConstants; import ru.ulstu.core.model.ErrorConstants;
import ru.ulstu.core.model.response.Response; import ru.ulstu.core.model.response.Response;
import ru.ulstu.core.model.response.ResponseExtended; import ru.ulstu.core.model.response.ResponseExtended;
import ru.ulstu.user.error.UserActivationError; import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException; import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException; import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException; import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException; import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.model.User;
import java.util.Set; import ru.ulstu.user.service.UserService;
import java.util.stream.Collectors;
import java.util.Set;
@RestController import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController { @ControllerAdvice
private final Logger log = LoggerFactory.getLogger(AdviceController.class); public class AdviceController {
private final static String USER_NAME_TEMPLATE = "%s %s %s";
private Response<Void> handleException(ErrorConstants error) { private final Logger log = LoggerFactory.getLogger(AdviceController.class);
log.warn(error.toString()); private final UserService userService;
return new Response<>(error);
} public AdviceController(UserService userService) {
this.userService = userService;
private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) { }
log.warn(error.toString());
return new ResponseExtended<>(error, errorData); @ModelAttribute("currentUser")
} public String getCurrentUser() {
User user = userService.getCurrentUser();
@ExceptionHandler(EntityIdIsNullException.class) return String.format(USER_NAME_TEMPLATE,
public Response<Void> handleEntityIdIsNullException(Throwable e) { user.getLastName(),
return handleException(ErrorConstants.ID_IS_NULL); user.getFirstName().substring(0, 1),
} user.getPatronymic().substring(0, 1));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { private Response<Void> handleException(ErrorConstants error) {
final Set<String> errors = e.getBindingResult().getAllErrors().stream() log.warn(error.toString());
.filter(error -> error instanceof FieldError) return new Response<>(error);
.map(error -> ((FieldError) error).getField()) }
.collect(Collectors.toSet());
return handleException(ErrorConstants.VALIDATION_ERROR, errors); private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) {
} log.warn(error.toString());
return new ResponseExtended<>(error, errorData);
@ExceptionHandler(UserIdExistsException.class) }
public Response<Void> handleUserIdExistsException(Throwable e) {
return handleException(ErrorConstants.USER_ID_EXISTS); @ExceptionHandler(EntityIdIsNullException.class)
} public Response<Void> handleEntityIdIsNullException(Throwable e) {
return handleException(ErrorConstants.ID_IS_NULL);
@ExceptionHandler(UserActivationError.class) }
public ResponseExtended<String> handleUserActivationError(Throwable e) {
return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage()); @ExceptionHandler(MethodArgumentNotValidException.class)
} public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
final Set<String> errors = e.getBindingResult().getAllErrors().stream()
@ExceptionHandler(UserLoginExistsException.class) .filter(error -> error instanceof FieldError)
public ResponseExtended<String> handleUserLoginExistsException(Throwable e) { .map(error -> ((FieldError) error).getField())
return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage()); .collect(Collectors.toSet());
} return handleException(ErrorConstants.VALIDATION_ERROR, errors);
}
@ExceptionHandler(UserEmailExistsException.class)
public ResponseExtended<String> handleUserEmailExistsException(Throwable e) { @ExceptionHandler(UserIdExistsException.class)
return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage()); public Response<Void> handleUserIdExistsException(Throwable e) {
} return handleException(ErrorConstants.USER_ID_EXISTS);
}
@ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) { @ExceptionHandler(UserActivationError.class)
return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH); public ResponseExtended<String> handleUserActivationError(Throwable e) {
} return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseExtended<String> handleUserNotFoundException(Throwable e) { @ExceptionHandler(UserLoginExistsException.class)
return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage()); public ResponseExtended<String> handleUserLoginExistsException(Throwable e) {
} return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
}
@ExceptionHandler(UserNotActivatedException.class)
public Response<Void> handleUserNotActivatedException(Throwable e) { @ExceptionHandler(UserEmailExistsException.class)
return handleException(ErrorConstants.USER_NOT_ACTIVATED); public ResponseExtended<String> handleUserEmailExistsException(Throwable e) {
} return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
}
@ExceptionHandler(UserResetKeyError.class)
public ResponseExtended<String> handleUserResetKeyError(Throwable e) { @ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage()); public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
} return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
}
@ExceptionHandler(UserIsUndeadException.class)
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) { @ExceptionHandler(UserNotFoundException.class)
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage()); public ResponseExtended<String> handleUserNotFoundException(Throwable e) {
} return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
} }
@ExceptionHandler(UserNotActivatedException.class)
public Response<Void> handleUserNotActivatedException(Throwable e) {
return handleException(ErrorConstants.USER_NOT_ACTIVATED);
}
@ExceptionHandler(UserResetKeyError.class)
public ResponseExtended<String> handleUserResetKeyError(Throwable e) {
return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
}
@ExceptionHandler(UserIsUndeadException.class)
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) {
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
}
}

View File

@ -0,0 +1,21 @@
package ru.ulstu.index.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.core.controller.AdviceController;
import ru.ulstu.user.service.UserService;
@Controller()
@RequestMapping(value = "/index")
public class IndexController extends AdviceController {
public IndexController(UserService userService) {
super(userService);
}
@GetMapping
public void currentUser(ModelMap modelMap) {
//нужен здесь для добавления параметров на стартовой странице
}
}

View File

@ -45,6 +45,10 @@ public class User extends BaseEntity {
@Column(name = "last_name", length = 50, nullable = false) @Column(name = "last_name", length = 50, nullable = false)
private String lastName; private String lastName;
@Size(max = 50)
@Column(name = "patronymic", length = 50)
private String patronymic;
@NotNull @NotNull
@Email @Email
@Size(min = 5, max = 100) @Size(min = 5, max = 100)
@ -174,4 +178,12 @@ public class User extends BaseEntity {
this.roles.clear(); this.roles.clear();
this.roles.addAll(roles); this.roles.addAll(roles);
} }
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
} }

View File

@ -1,318 +1,327 @@
package ru.ulstu.user.service; package ru.ulstu.user.service;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.jpa.OffsetablePageRequest; import ru.ulstu.core.jpa.OffsetablePageRequest;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.response.PageableItems; import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.user.error.UserActivationError; import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException; import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException; import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException; import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException; import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserResetPasswordDto;
import ru.ulstu.user.model.UserRole; import ru.ulstu.user.model.UserRole;
import ru.ulstu.user.model.UserRoleConstants; import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.model.UserRoleDto; import ru.ulstu.user.model.UserRoleDto;
import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRepository;
import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.repository.UserRoleRepository;
import ru.ulstu.user.util.UserUtils; import ru.ulstu.user.util.UserUtils;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@Transactional @Transactional
public class UserService implements UserDetailsService { public class UserService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(UserService.class); private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository; private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final UserRoleRepository userRoleRepository; private final UserRoleRepository userRoleRepository;
private final UserMapper userMapper; private final UserMapper userMapper;
private final MailService mailService; private final MailService mailService;
private final ApplicationProperties applicationProperties; private final ApplicationProperties applicationProperties;
public UserService(UserRepository userRepository, public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder, PasswordEncoder passwordEncoder,
UserRoleRepository userRoleRepository, UserRoleRepository userRoleRepository,
UserMapper userMapper, UserMapper userMapper,
MailService mailService, MailService mailService,
ApplicationProperties applicationProperties) { ApplicationProperties applicationProperties) {
this.userRepository = userRepository; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.userRoleRepository = userRoleRepository; this.userRoleRepository = userRoleRepository;
this.userMapper = userMapper; this.userMapper = userMapper;
this.mailService = mailService; this.mailService = mailService;
this.applicationProperties = applicationProperties; this.applicationProperties = applicationProperties;
} }
private User getUserByEmail(String email) { private User getUserByEmail(String email) {
return userRepository.findOneByEmailIgnoreCase(email); return userRepository.findOneByEmailIgnoreCase(email);
} }
private User getUserByActivationKey(String activationKey) { private User getUserByActivationKey(String activationKey) {
return userRepository.findOneByActivationKey(activationKey); return userRepository.findOneByActivationKey(activationKey);
} }
public User getUserByLogin(String login) { public User getUserByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login); return userRepository.findOneByLoginIgnoreCase(login);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public UserDto getUserWithRolesById(Integer userId) { public UserDto getUserWithRolesById(Integer userId) {
final User userEntity = userRepository.findOneWithRolesById(userId); final User userEntity = userRepository.findOneWithRolesById(userId);
if (userEntity == null) { if (userEntity == null) {
throw new UserNotFoundException(userId.toString()); throw new UserNotFoundException(userId.toString());
} }
return userMapper.userEntityToUserDto(userEntity); return userMapper.userEntityToUserDto(userEntity);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public PageableItems<UserListDto> getAllUsers(int offset, int count) { public PageableItems<UserListDto> getAllUsers(int offset, int count) {
final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
} }
// TODO: read only active users // TODO: read only active users
public List<User> findAll() { public List<User> findAll() {
return userRepository.findAll(); return userRepository.findAll();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public PageableItems<UserRoleDto> getUserRoles() { public PageableItems<UserRoleDto> getUserRoles() {
final List<UserRoleDto> roles = userRoleRepository.findAll().stream() final List<UserRoleDto> roles = userRoleRepository.findAll().stream()
.map(UserRoleDto::new) .map(UserRoleDto::new)
.sorted(Comparator.comparing(UserRoleDto::getViewValue)) .sorted(Comparator.comparing(UserRoleDto::getViewValue))
.collect(Collectors.toList()); .collect(Collectors.toList());
return new PageableItems<>(roles.size(), roles); return new PageableItems<>(roles.size(), roles);
} }
public UserDto createUser(UserDto userDto) { public UserDto createUser(UserDto userDto) {
if (userDto.getId() != null) { if (userDto.getId() != null) {
throw new UserIdExistsException(); throw new UserIdExistsException();
} }
if (getUserByLogin(userDto.getLogin()) != null) { if (getUserByLogin(userDto.getLogin()) != null) {
throw new UserLoginExistsException(userDto.getLogin()); throw new UserLoginExistsException(userDto.getLogin());
} }
if (getUserByEmail(userDto.getEmail()) != null) { if (getUserByEmail(userDto.getEmail()) != null) {
throw new UserEmailExistsException(userDto.getEmail()); throw new UserEmailExistsException(userDto.getEmail());
} }
if (!userDto.isPasswordsValid()) { if (!userDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
User user = userMapper.userDtoToUserEntity(userDto); User user = userMapper.userDtoToUserEntity(userDto);
user.setActivated(false); user.setActivated(false);
user.setActivationKey(UserUtils.generateActivationKey()); user.setActivationKey(UserUtils.generateActivationKey());
user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
user.setPassword(passwordEncoder.encode(userDto.getPassword())); user.setPassword(passwordEncoder.encode(userDto.getPassword()));
user = userRepository.save(user); user = userRepository.save(user);
mailService.sendActivationEmail(user); mailService.sendActivationEmail(user);
log.debug("Created Information for User: {}", user.getLogin()); log.debug("Created Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user); return userMapper.userEntityToUserDto(user);
} }
public UserDto activateUser(String activationKey) { public UserDto activateUser(String activationKey) {
final User user = getUserByActivationKey(activationKey); final User user = getUserByActivationKey(activationKey);
if (user == null) { if (user == null) {
throw new UserActivationError(activationKey); throw new UserActivationError(activationKey);
} }
user.setActivated(true); user.setActivated(true);
user.setActivationKey(null); user.setActivationKey(null);
user.setActivationDate(null); user.setActivationDate(null);
log.debug("Activated user: {}", user.getLogin()); log.debug("Activated user: {}", user.getLogin());
return userMapper.userEntityToUserDto(userRepository.save(user)); return userMapper.userEntityToUserDto(userRepository.save(user));
} }
public UserDto updateUser(UserDto userDto) { public UserDto updateUser(UserDto userDto) {
if (userDto.getId() == null) { if (userDto.getId() == null) {
throw new EntityIdIsNullException(); throw new EntityIdIsNullException();
} }
if (!Objects.equals( if (!Objects.equals(
Optional.ofNullable(getUserByEmail(userDto.getEmail())) Optional.ofNullable(getUserByEmail(userDto.getEmail()))
.map(BaseEntity::getId).orElse(userDto.getId()), .map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) { userDto.getId())) {
throw new UserEmailExistsException(userDto.getEmail()); throw new UserEmailExistsException(userDto.getEmail());
} }
if (!Objects.equals( if (!Objects.equals(
Optional.ofNullable(getUserByLogin(userDto.getLogin())) Optional.ofNullable(getUserByLogin(userDto.getLogin()))
.map(BaseEntity::getId).orElse(userDto.getId()), .map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) { userDto.getId())) {
throw new UserLoginExistsException(userDto.getLogin()); throw new UserLoginExistsException(userDto.getLogin());
} }
User user = userRepository.findOne(userDto.getId()); User user = userRepository.findOne(userDto.getId());
if (user == null) { if (user == null) {
throw new UserNotFoundException(userDto.getId().toString()); throw new UserNotFoundException(userDto.getId().toString());
} }
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
userDto.setLogin(applicationProperties.getUndeadUserLogin()); userDto.setLogin(applicationProperties.getUndeadUserLogin());
userDto.setActivated(true); userDto.setActivated(true);
userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
} }
user.setLogin(userDto.getLogin()); user.setLogin(userDto.getLogin());
user.setFirstName(userDto.getFirstName()); user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName()); user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail()); user.setEmail(userDto.getEmail());
if (userDto.isActivated() != user.getActivated()) { if (userDto.isActivated() != user.getActivated()) {
if (userDto.isActivated()) { if (userDto.isActivated()) {
user.setActivationKey(null); user.setActivationKey(null);
user.setActivationDate(null); user.setActivationDate(null);
} else { } else {
user.setActivationKey(UserUtils.generateActivationKey()); user.setActivationKey(UserUtils.generateActivationKey());
user.setActivationDate(new Date()); user.setActivationDate(new Date());
} }
} }
user.setActivated(userDto.isActivated()); user.setActivated(userDto.isActivated());
final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles()); final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles());
user.setRoles(roles.isEmpty() user.setRoles(roles.isEmpty()
? Collections.singleton(new UserRole(UserRoleConstants.USER)) ? Collections.singleton(new UserRole(UserRoleConstants.USER))
: roles); : roles);
if (!StringUtils.isEmpty(userDto.getOldPassword())) { if (!StringUtils.isEmpty(userDto.getOldPassword())) {
if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
user.setPassword(passwordEncoder.encode(userDto.getPassword())); user.setPassword(passwordEncoder.encode(userDto.getPassword()));
log.debug("Changed password for User: {}", user.getLogin()); log.debug("Changed password for User: {}", user.getLogin());
} }
user = userRepository.save(user); user = userRepository.save(user);
log.debug("Changed Information for User: {}", user.getLogin()); log.debug("Changed Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user); return userMapper.userEntityToUserDto(user);
} }
public UserDto updateUserInformation(UserDto userDto) { public UserDto updateUserInformation(UserDto userDto) {
if (userDto.getId() == null) { if (userDto.getId() == null) {
throw new EntityIdIsNullException(); throw new EntityIdIsNullException();
} }
if (!Objects.equals( if (!Objects.equals(
Optional.ofNullable(getUserByEmail(userDto.getEmail())) Optional.ofNullable(getUserByEmail(userDto.getEmail()))
.map(BaseEntity::getId).orElse(userDto.getId()), .map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) { userDto.getId())) {
throw new UserEmailExistsException(userDto.getEmail()); throw new UserEmailExistsException(userDto.getEmail());
} }
User user = userRepository.findOne(userDto.getId()); User user = userRepository.findOne(userDto.getId());
if (user == null) { if (user == null) {
throw new UserNotFoundException(userDto.getId().toString()); throw new UserNotFoundException(userDto.getId().toString());
} }
user.setFirstName(userDto.getFirstName()); user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName()); user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail()); user.setEmail(userDto.getEmail());
user = userRepository.save(user); user = userRepository.save(user);
log.debug("Updated Information for User: {}", user.getLogin()); log.debug("Updated Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user); return userMapper.userEntityToUserDto(user);
} }
public UserDto changeUserPassword(UserDto userDto) { public UserDto changeUserPassword(UserDto userDto) {
if (userDto.getId() == null) { if (userDto.getId() == null) {
throw new EntityIdIsNullException(); throw new EntityIdIsNullException();
} }
if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
final String login = UserUtils.getCurrentUserLogin(); final String login = UserUtils.getCurrentUserLogin();
final User user = userRepository.findOneByLoginIgnoreCase(login); final User user = userRepository.findOneByLoginIgnoreCase(login);
if (user == null) { if (user == null) {
throw new UserNotFoundException(login); throw new UserNotFoundException(login);
} }
if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
user.setPassword(passwordEncoder.encode(userDto.getPassword())); user.setPassword(passwordEncoder.encode(userDto.getPassword()));
log.debug("Changed password for User: {}", user.getLogin()); log.debug("Changed password for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(userRepository.save(user)); return userMapper.userEntityToUserDto(userRepository.save(user));
} }
public boolean requestUserPasswordReset(String email) { public boolean requestUserPasswordReset(String email) {
User user = userRepository.findOneByEmailIgnoreCase(email); User user = userRepository.findOneByEmailIgnoreCase(email);
if (user == null) { if (user == null) {
throw new UserNotFoundException(email); throw new UserNotFoundException(email);
} }
if (!user.getActivated()) { if (!user.getActivated()) {
throw new UserNotActivatedException(); throw new UserNotActivatedException();
} }
user.setResetKey(UserUtils.generateResetKey()); user.setResetKey(UserUtils.generateResetKey());
user.setResetDate(new Date()); user.setResetDate(new Date());
user = userRepository.save(user); user = userRepository.save(user);
mailService.sendPasswordResetMail(user); mailService.sendPasswordResetMail(user);
log.debug("Created Reset Password Request for User: {}", user.getLogin()); log.debug("Created Reset Password Request for User: {}", user.getLogin());
return true; return true;
} }
public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) {
if (!userResetPasswordDto.isPasswordsValid()) { if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException(); throw new UserPasswordsNotValidOrNotMatchException();
} }
User user = userRepository.findOneByResetKey(key); User user = userRepository.findOneByResetKey(key);
if (user == null) { if (user == null) {
throw new UserResetKeyError(key); throw new UserResetKeyError(key);
} }
user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
user.setResetKey(null); user.setResetKey(null);
user.setResetDate(null); user.setResetDate(null);
user = userRepository.save(user); user = userRepository.save(user);
log.debug("Reset Password for User: {}", user.getLogin()); log.debug("Reset Password for User: {}", user.getLogin());
return true; return true;
} }
public UserDto deleteUser(Integer userId) { public UserDto deleteUser(Integer userId) {
final User user = userRepository.findOne(userId); final User user = userRepository.findOne(userId);
if (user == null) { if (user == null) {
throw new UserNotFoundException(userId.toString()); throw new UserNotFoundException(userId.toString());
} }
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
throw new UserIsUndeadException(user.getLogin()); throw new UserIsUndeadException(user.getLogin());
} }
userRepository.delete(user); userRepository.delete(user);
log.debug("Deleted User: {}", user.getLogin()); log.debug("Deleted User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user); return userMapper.userEntityToUserDto(user);
} }
@Override @Override
public UserDetails loadUserByUsername(String username) { public UserDetails loadUserByUsername(String username) {
final User user = userRepository.findOneByLoginIgnoreCase(username); final User user = userRepository.findOneByLoginIgnoreCase(username);
if (user == null) { if (user == null) {
throw new UserNotFoundException(username); throw new UserNotFoundException(username);
} }
if (!user.getActivated()) { if (!user.getActivated()) {
throw new UserNotActivatedException(); throw new UserNotActivatedException();
} }
return new org.springframework.security.core.userdetails.User(user.getLogin(), return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(), user.getPassword(),
Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
.map(role -> new SimpleGrantedAuthority(role.getName())) .map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public List<User> findByIds(List<Integer> ids) { public List<User> findByIds(List<Integer> ids) {
return userRepository.findAll(ids); return userRepository.findAll(ids);
} }
public User findById(Integer id) { public User findById(Integer id) {
return userRepository.findOne(id); return userRepository.findOne(id);
} }
}
public User getCurrentUser() {
String login = UserUtils.getCurrentUserLogin();
User user = userRepository.findOneByLoginIgnoreCase(login);
if (user == null) {
throw new UserNotFoundException(login);
}
return user;
}
}

View File

@ -18,4 +18,5 @@
<include file="db/changelog-20181111_000000-schema.xml"/> <include file="db/changelog-20181111_000000-schema.xml"/>
<include file="db/changelog-20181208_000000-schema.xml"/> <include file="db/changelog-20181208_000000-schema.xml"/>
<include file="db/changelog-20181224_000000-schema.xml"/> <include file="db/changelog-20181224_000000-schema.xml"/>
<include file="db/common/changelog-20190312_130000-schema.xml"/>
</databaseChangeLog> </databaseChangeLog>

View File

@ -0,0 +1,16 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="orion" id="20190312_130000-1">
<addColumn tableName="users">
<column name="patronymic" type="varchar(255)"/>
</addColumn>
</changeSet>
<changeSet author="orion" id="20190312_130000-2">
<sql>
update users
set first_name = 'Антон', patronymic = 'Алексеевич', last_name = 'Романов' where id = 1;
</sql>
</changeSet>
</databaseChangeLog>

View File

@ -1,6 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru" <html lang="ru"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"> xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.w3.org/1999/xhtml">
<head> <head>
<meta charset="utf-8"/> <meta charset="utf-8"/>
@ -53,6 +53,9 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link js-scroll-trigger" target="_blank" href="http://is.ulstu.ru">Сайт кафедры</a> <a class="nav-link js-scroll-trigger" target="_blank" href="http://is.ulstu.ru">Сайт кафедры</a>
</li> </li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" target="_blank" th:href="@{'http://timetable.athene.tech?filter='+${currentUser}}">Расписание</a>
</li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link js-scroll-trigger" target="_blank" href="https://kias.rfbr.ru/">КИАС РФФИ</a> <a class="nav-link js-scroll-trigger" target="_blank" href="https://kias.rfbr.ru/">КИАС РФФИ</a>
</li> </li>