diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java index 2b0a428..8f9e05f 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java @@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository @Override @Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + + "AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)") + Conference findActiveByUser(@Param("user") User user); } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 4ee4198..1b8e67b 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -313,4 +313,8 @@ public class ConferenceService extends BaseService { .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .collect(Collectors.toList())); } + + public Conference getActiveConferenceByUser(User user) { + return conferenceRepository.findActiveByUser(user); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java index f771b2a..16842c1 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java @@ -43,6 +43,4 @@ public class ConferenceUserService { newUser = conferenceUserRepository.save(newUser); return newUser; } - - } diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java index 5bcbd13..044bde8 100644 --- a/src/main/java/ru/ulstu/user/controller/UserMvcController.java +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -48,4 +48,9 @@ public class UserMvcController extends OdinController { User user = userSessionService.getUserBySessionId(sessionId); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); } + + @GetMapping("/dashboard") + public void getUsersDashboard(ModelMap modelMap) { + modelMap.addAllAttributes(userService.getUsersInfo()); + } } diff --git a/src/main/java/ru/ulstu/user/model/UserInfoNow.java b/src/main/java/ru/ulstu/user/model/UserInfoNow.java new file mode 100644 index 0000000..7d69c56 --- /dev/null +++ b/src/main/java/ru/ulstu/user/model/UserInfoNow.java @@ -0,0 +1,50 @@ +package ru.ulstu.user.model; + +import ru.ulstu.conference.model.Conference; +import ru.ulstu.utils.timetable.model.Lesson; + +public class UserInfoNow { + private Lesson lesson; + private Conference conference; + private User user; + private boolean isOnline; + + public UserInfoNow(Lesson lesson, Conference conference, User user, boolean isOnline) { + this.lesson = lesson; + this.conference = conference; + this.user = user; + this.isOnline = isOnline; + } + + public Lesson getLesson() { + return lesson; + } + + public void setLesson(Lesson lesson) { + this.lesson = lesson; + } + + public Conference getConference() { + return conference; + } + + public void setConference(Conference conference) { + this.conference = conference; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public boolean isOnline() { + return isOnline; + } + + public void setOnline(boolean online) { + isOnline = online; + } +} diff --git a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java index b922e4f..5319245 100644 --- a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java +++ b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java @@ -1,6 +1,7 @@ package ru.ulstu.user.repository; import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserSession; import java.util.Date; @@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); + + List findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date); } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index 7534110..217215b 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -1,355 +1,392 @@ -package ru.ulstu.user.service; - -import com.google.common.collect.ImmutableMap; -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; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; -import ru.ulstu.configuration.ApplicationProperties; -import ru.ulstu.core.error.EntityIdIsNullException; -import ru.ulstu.core.jpa.OffsetablePageRequest; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.response.PageableItems; -import ru.ulstu.user.error.UserActivationError; -import ru.ulstu.user.error.UserEmailExistsException; -import ru.ulstu.user.error.UserIdExistsException; -import ru.ulstu.user.error.UserIsUndeadException; -import ru.ulstu.user.error.UserLoginExistsException; -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.model.User; -import ru.ulstu.user.model.UserDto; -import ru.ulstu.user.model.UserListDto; -import ru.ulstu.user.model.UserResetPasswordDto; -import ru.ulstu.user.model.UserRole; -import ru.ulstu.user.model.UserRoleConstants; -import ru.ulstu.user.model.UserRoleDto; -import ru.ulstu.user.repository.UserRepository; -import ru.ulstu.user.repository.UserRoleRepository; -import ru.ulstu.user.util.UserUtils; - -import javax.mail.MessagingException; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@Transactional -public class UserService implements UserDetailsService { - private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; - - private final Logger log = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; - private final UserRoleRepository userRoleRepository; - private final UserMapper userMapper; - private final MailService mailService; - private final ApplicationProperties applicationProperties; - - public UserService(UserRepository userRepository, - PasswordEncoder passwordEncoder, - UserRoleRepository userRoleRepository, - UserMapper userMapper, - MailService mailService, - ApplicationProperties applicationProperties) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - this.userRoleRepository = userRoleRepository; - this.userMapper = userMapper; - this.mailService = mailService; - this.applicationProperties = applicationProperties; - } - - private User getUserByEmail(String email) { - return userRepository.findOneByEmailIgnoreCase(email); - } - - private User getUserByActivationKey(String activationKey) { - return userRepository.findOneByActivationKey(activationKey); - } - - public User getUserByLogin(String login) { - return userRepository.findOneByLoginIgnoreCase(login); - } - - @Transactional(readOnly = true) - public UserDto getUserWithRolesById(Integer userId) { - final User userEntity = userRepository.findOneWithRolesById(userId); - if (userEntity == null) { - throw new UserNotFoundException(userId.toString()); - } - return userMapper.userEntityToUserDto(userEntity); - } - - @Transactional(readOnly = true) - public PageableItems getAllUsers(int offset, int count) { - final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); - return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); - } - - // TODO: read only active users - public List findAll() { - return userRepository.findAll(); - } - - @Transactional(readOnly = true) - public PageableItems getUserRoles() { - final List roles = userRoleRepository.findAll().stream() - .map(UserRoleDto::new) - .sorted(Comparator.comparing(UserRoleDto::getViewValue)) - .collect(Collectors.toList()); - return new PageableItems<>(roles.size(), roles); - } - - public UserDto createUser(UserDto userDto) { - if (userDto.getId() != null) { - throw new UserIdExistsException(); - } - if (getUserByLogin(userDto.getLogin()) != null) { - throw new UserLoginExistsException(userDto.getLogin()); - } - if (getUserByEmail(userDto.getEmail()) != null) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!userDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - User user = userMapper.userDtoToUserEntity(userDto); - user.setActivated(false); - user.setActivationKey(UserUtils.generateActivationKey()); - user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - user = userRepository.save(user); - mailService.sendActivationEmail(user); - log.debug("Created Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto activateUser(String activationKey) { - final User user = getUserByActivationKey(activationKey); - if (user == null) { - throw new UserActivationError(activationKey); - } - user.setActivated(true); - user.setActivationKey(null); - user.setActivationDate(null); - log.debug("Activated user: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); - } - - public UserDto updateUser(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!Objects.equals( - Optional.ofNullable(getUserByLogin(userDto.getLogin())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserLoginExistsException(userDto.getLogin()); - } - User user = userRepository.findOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - userDto.setLogin(applicationProperties.getUndeadUserLogin()); - userDto.setActivated(true); - userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); - } - user.setLogin(userDto.getLogin()); - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); - if (userDto.isActivated() != user.getActivated()) { - if (userDto.isActivated()) { - user.setActivationKey(null); - user.setActivationDate(null); - } else { - user.setActivationKey(UserUtils.generateActivationKey()); - user.setActivationDate(new Date()); - } - } - user.setActivated(userDto.isActivated()); - final Set roles = userMapper.rolesFromDto(userDto.getRoles()); - user.setRoles(roles.isEmpty() - ? Collections.singleton(new UserRole(UserRoleConstants.USER)) - : roles); - if (!StringUtils.isEmpty(userDto.getOldPassword())) { - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - log.debug("Changed password for User: {}", user.getLogin()); - } - user = userRepository.save(user); - log.debug("Changed Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto updateUserInformation(User user, UserDto updateUser) { - user.setFirstName(updateUser.getFirstName()); - user.setLastName(updateUser.getLastName()); - user.setEmail(updateUser.getEmail()); - user.setLogin(updateUser.getLogin()); - user = userRepository.save(user); - log.debug("Updated Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public void changeUserPassword(User user, Map payload) { - if (!payload.get("password").equals(payload.get("confirmPassword"))) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); - } - user.setPassword(passwordEncoder.encode(payload.get("password"))); - log.debug("Changed password for User: {}", user.getLogin()); - userRepository.save(user); - - mailService.sendChangePasswordMail(user); - } - - public boolean requestUserPasswordReset(String email) { - User user = userRepository.findOneByEmailIgnoreCase(email); - if (user == null) { - throw new UserNotFoundException(email); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - user.setResetKey(UserUtils.generateResetKey()); - user.setResetDate(new Date()); - user = userRepository.save(user); - try { - mailService.sendPasswordResetMail(user); - } catch (MessagingException | MailException e) { - throw new UserSendingMailException(email); - } - log.debug("Created Reset Password Request for User: {}", user.getLogin()); - return true; - } - - public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { - if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); - } - User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); - if (user == null) { - throw new UserResetKeyError(userResetPasswordDto.getResetKey()); - } - user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); - user.setResetKey(null); - user.setResetDate(null); - user = userRepository.save(user); - - mailService.sendChangePasswordMail(user); - - log.debug("Reset Password for User: {}", user.getLogin()); - return true; - } - - public UserDto deleteUser(Integer userId) { - final User user = userRepository.findOne(userId); - if (user == null) { - throw new UserNotFoundException(userId.toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - throw new UserIsUndeadException(user.getLogin()); - } - userRepository.delete(user); - log.debug("Deleted User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - @Override - public UserDetails loadUserByUsername(String username) { - final User user = userRepository.findOneByLoginIgnoreCase(username); - if (user == null) { - throw new UserNotFoundException(username); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() - .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList())); - } - - public List findByIds(List ids) { - return userRepository.findAll(ids); - } - - public User findById(Integer 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; - } - - public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { - return userRepository.filterByAgeAndDegree(hasDegree, hasAge); - } - - public void inviteUser(String email) throws UserSendingMailException { - if (userRepository.findOneByEmailIgnoreCase(email) != null) { - throw new UserEmailExistsException(email); - } - - String password = UserUtils.generatePassword(); - - User user = new User(); - user.setPassword(passwordEncoder.encode(password)); - user.setLogin(email); - user.setEmail(email); - user.setFirstName("user"); - user.setLastName("user"); - user.setActivated(true); - userRepository.save(user); - - Map variables = ImmutableMap.of("password", password, "email", email); - try { - mailService.sendInviteMail(variables, email); - } catch (MessagingException | MailException e) { - throw new UserSendingMailException(email); - } - } - - public User findOneByLoginIgnoreCase(String login) { - return userRepository.findOneByLoginIgnoreCase(login); - } -} +package ru.ulstu.user.service; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; +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; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import ru.ulstu.conference.service.ConferenceService; +import ru.ulstu.configuration.ApplicationProperties; +import ru.ulstu.core.error.EntityIdIsNullException; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.user.error.UserActivationError; +import ru.ulstu.user.error.UserEmailExistsException; +import ru.ulstu.user.error.UserIdExistsException; +import ru.ulstu.user.error.UserIsUndeadException; +import ru.ulstu.user.error.UserLoginExistsException; +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.model.User; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserInfoNow; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.model.UserResetPasswordDto; +import ru.ulstu.user.model.UserRole; +import ru.ulstu.user.model.UserRoleConstants; +import ru.ulstu.user.model.UserRoleDto; +import ru.ulstu.user.repository.UserRepository; +import ru.ulstu.user.repository.UserRoleRepository; +import ru.ulstu.user.util.UserUtils; +import ru.ulstu.utils.timetable.TimetableService; +import ru.ulstu.utils.timetable.errors.TimetableClientException; +import ru.ulstu.utils.timetable.model.Lesson; + +import javax.mail.MessagingException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@Transactional +public class UserService implements UserDetailsService { + private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; + + private final Logger log = LoggerFactory.getLogger(UserService.class); + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final UserRoleRepository userRoleRepository; + private final UserMapper userMapper; + private final MailService mailService; + private final ApplicationProperties applicationProperties; + private final TimetableService timetableService; + private final ConferenceService conferenceService; + private final UserSessionService userSessionService; + + public UserService(UserRepository userRepository, + PasswordEncoder passwordEncoder, + UserRoleRepository userRoleRepository, + UserMapper userMapper, + MailService mailService, + ApplicationProperties applicationProperties, + @Lazy ConferenceService conferenceRepository, + @Lazy UserSessionService userSessionService) throws ParseException { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.userRoleRepository = userRoleRepository; + this.userMapper = userMapper; + this.mailService = mailService; + this.applicationProperties = applicationProperties; + this.conferenceService = conferenceRepository; + this.timetableService = new TimetableService(); + this.userSessionService = userSessionService; + } + + private User getUserByEmail(String email) { + return userRepository.findOneByEmailIgnoreCase(email); + } + + private User getUserByActivationKey(String activationKey) { + return userRepository.findOneByActivationKey(activationKey); + } + + public User getUserByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Transactional(readOnly = true) + public UserDto getUserWithRolesById(Integer userId) { + final User userEntity = userRepository.findOneWithRolesById(userId); + if (userEntity == null) { + throw new UserNotFoundException(userId.toString()); + } + return userMapper.userEntityToUserDto(userEntity); + } + + @Transactional(readOnly = true) + public PageableItems getAllUsers(int offset, int count) { + final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); + return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); + } + + // TODO: read only active users + public List findAll() { + return userRepository.findAll(); + } + + @Transactional(readOnly = true) + public PageableItems getUserRoles() { + final List roles = userRoleRepository.findAll().stream() + .map(UserRoleDto::new) + .sorted(Comparator.comparing(UserRoleDto::getViewValue)) + .collect(Collectors.toList()); + return new PageableItems<>(roles.size(), roles); + } + + public UserDto createUser(UserDto userDto) { + if (userDto.getId() != null) { + throw new UserIdExistsException(); + } + if (getUserByLogin(userDto.getLogin()) != null) { + throw new UserLoginExistsException(userDto.getLogin()); + } + if (getUserByEmail(userDto.getEmail()) != null) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!userDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userMapper.userDtoToUserEntity(userDto); + user.setActivated(false); + user.setActivationKey(UserUtils.generateActivationKey()); + user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + user = userRepository.save(user); + mailService.sendActivationEmail(user); + log.debug("Created Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto activateUser(String activationKey) { + final User user = getUserByActivationKey(activationKey); + if (user == null) { + throw new UserActivationError(activationKey); + } + user.setActivated(true); + user.setActivationKey(null); + user.setActivationDate(null); + log.debug("Activated user: {}", user.getLogin()); + return userMapper.userEntityToUserDto(userRepository.save(user)); + } + + public UserDto updateUser(UserDto userDto) { + if (userDto.getId() == null) { + throw new EntityIdIsNullException(); + } + if (!Objects.equals( + Optional.ofNullable(getUserByEmail(userDto.getEmail())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!Objects.equals( + Optional.ofNullable(getUserByLogin(userDto.getLogin())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserLoginExistsException(userDto.getLogin()); + } + User user = userRepository.findOne(userDto.getId()); + if (user == null) { + throw new UserNotFoundException(userDto.getId().toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + userDto.setLogin(applicationProperties.getUndeadUserLogin()); + userDto.setActivated(true); + userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); + } + user.setLogin(userDto.getLogin()); + user.setFirstName(userDto.getFirstName()); + user.setLastName(userDto.getLastName()); + user.setEmail(userDto.getEmail()); + if (userDto.isActivated() != user.getActivated()) { + if (userDto.isActivated()) { + user.setActivationKey(null); + user.setActivationDate(null); + } else { + user.setActivationKey(UserUtils.generateActivationKey()); + user.setActivationDate(new Date()); + } + } + user.setActivated(userDto.isActivated()); + final Set roles = userMapper.rolesFromDto(userDto.getRoles()); + user.setRoles(roles.isEmpty() + ? Collections.singleton(new UserRole(UserRoleConstants.USER)) + : roles); + if (!StringUtils.isEmpty(userDto.getOldPassword())) { + if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + log.debug("Changed password for User: {}", user.getLogin()); + } + user = userRepository.save(user); + log.debug("Changed Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto updateUserInformation(User user, UserDto updateUser) { + user.setFirstName(updateUser.getFirstName()); + user.setLastName(updateUser.getLastName()); + user.setEmail(updateUser.getEmail()); + user.setLogin(updateUser.getLogin()); + user = userRepository.save(user); + log.debug("Updated Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public void changeUserPassword(User user, Map payload) { + if (!payload.get("password").equals(payload.get("confirmPassword"))) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); + } + user.setPassword(passwordEncoder.encode(payload.get("password"))); + log.debug("Changed password for User: {}", user.getLogin()); + userRepository.save(user); + + mailService.sendChangePasswordMail(user); + } + + public boolean requestUserPasswordReset(String email) { + User user = userRepository.findOneByEmailIgnoreCase(email); + if (user == null) { + throw new UserNotFoundException(email); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + user.setResetKey(UserUtils.generateResetKey()); + user.setResetDate(new Date()); + user = userRepository.save(user); + try { + mailService.sendPasswordResetMail(user); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + log.debug("Created Reset Password Request for User: {}", user.getLogin()); + return true; + } + + public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { + if (!userResetPasswordDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); + } + User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); + if (user == null) { + throw new UserResetKeyError(userResetPasswordDto.getResetKey()); + } + user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); + user.setResetKey(null); + user.setResetDate(null); + user = userRepository.save(user); + + mailService.sendChangePasswordMail(user); + + log.debug("Reset Password for User: {}", user.getLogin()); + return true; + } + + public UserDto deleteUser(Integer userId) { + final User user = userRepository.findOne(userId); + if (user == null) { + throw new UserNotFoundException(userId.toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + throw new UserIsUndeadException(user.getLogin()); + } + userRepository.delete(user); + log.debug("Deleted User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + @Override + public UserDetails loadUserByUsername(String username) { + final User user = userRepository.findOneByLoginIgnoreCase(username); + if (user == null) { + throw new UserNotFoundException(username); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + return new org.springframework.security.core.userdetails.User(user.getLogin(), + user.getPassword(), + Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() + .map(role -> new SimpleGrantedAuthority(role.getName())) + .collect(Collectors.toList())); + } + + public List findByIds(List ids) { + return userRepository.findAll(ids); + } + + public User findById(Integer 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; + } + + public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { + return userRepository.filterByAgeAndDegree(hasDegree, hasAge); + } + + public void inviteUser(String email) throws UserSendingMailException { + if (userRepository.findOneByEmailIgnoreCase(email) != null) { + throw new UserEmailExistsException(email); + } + + String password = UserUtils.generatePassword(); + + User user = new User(); + user.setPassword(passwordEncoder.encode(password)); + user.setLogin(email); + user.setEmail(email); + user.setFirstName("user"); + user.setLastName("user"); + user.setActivated(true); + userRepository.save(user); + + Map variables = ImmutableMap.of("password", password, "email", email); + try { + mailService.sendInviteMail(variables, email); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + } + + public User findOneByLoginIgnoreCase(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + public Map getUsersInfo() { + List usersInfoNow = new ArrayList<>(); + String err = ""; + + for (User user : userRepository.findAll()) { + Lesson lesson = null; + try { + lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); + } catch (TimetableClientException e) { + err = "Не удалось загрузить расписание"; + } + usersInfoNow.add(new UserInfoNow( + lesson, + conferenceService.getActiveConferenceByUser(user), + user, + userSessionService.isOnline(user)) + ); + } + return ImmutableMap.of("users", usersInfoNow, "error", err); + } +} diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java index ae289d0..17a7f5b 100644 --- a/src/main/java/ru/ulstu/user/service/UserSessionService.java +++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java @@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.repository.UserSessionRepository; +import java.util.Date; + import static ru.ulstu.core.util.StreamApiUtils.convert; @Service @@ -58,4 +60,8 @@ public class UserSessionService { public User getUserBySessionId(String sessionId) { return userSessionRepository.findOneBySessionId(sessionId).getUser(); } + + public boolean isOnline(User user) { + return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty(); + } } diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java new file mode 100644 index 0000000..aa49fed --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -0,0 +1,91 @@ +package ru.ulstu.utils.timetable; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import ru.ulstu.utils.timetable.errors.TimetableClientException; +import ru.ulstu.utils.timetable.model.Lesson; +import ru.ulstu.utils.timetable.model.TimetableResponse; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class TimetableService { + private static final String TIMETABLE_URL = "http://timetable.athene.tech/api/1.0/timetable?filter=%s"; + private SimpleDateFormat lessonTimeFormat = new SimpleDateFormat("hh:mm"); + + private long[] lessonsStarts = new long[] { + lessonTimeFormat.parse("8:00:00").getTime(), + lessonTimeFormat.parse("9:40:00").getTime(), + lessonTimeFormat.parse("11:30:00").getTime(), + lessonTimeFormat.parse("13:10:00").getTime(), + lessonTimeFormat.parse("14:50:00").getTime(), + lessonTimeFormat.parse("16:30:00").getTime(), + lessonTimeFormat.parse("18:10:00").getTime(), + }; + + public TimetableService() throws ParseException { + } + + private int getCurrentDay() { + Calendar calendar = Calendar.getInstance(); + int day = calendar.get(Calendar.DAY_OF_WEEK); + return (day + 5) % 7; + } + + private int getCurrentLessonNumber() { + long lessonDuration = 90 * 60000; + Date now = new Date(); + long timeNow = now.getTime() % (24 * 60 * 60 * 1000L); + + for (int i = 0; i < lessonsStarts.length; i++) { + if (timeNow > lessonsStarts[i] && timeNow < lessonsStarts[i] + lessonDuration) { + return i; + } + } + return -1; + } + + private int getCurrentWeek() { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + return (cal.get(Calendar.WEEK_OF_YEAR) + 1) % 2; + } + + private TimetableResponse getTimetableForUser(String userFIO) throws RestClientException { + RestTemplate restTemplate = new RestTemplate(); + return restTemplate.getForObject(String.format(TIMETABLE_URL, userFIO), TimetableResponse.class); + } + + public Lesson getCurrentLesson(String userFio) { + TimetableResponse response; + try { + response = getTimetableForUser(userFio); + } catch (RestClientException e) { + e.printStackTrace(); + throw new TimetableClientException(userFio); + } + + int lessonNumber = getCurrentLessonNumber(); + if (lessonNumber < 0) { + return null; + } + + List lessons = response + .getResponse() + .getWeeks() + .get(getCurrentWeek()) + .getDays() + .get(getCurrentDay()) + .getLessons() + .get(lessonNumber); + + if (lessons.size() == 0) { + return null; + } + return new ObjectMapper().convertValue(lessons.get(0), Lesson.class); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java new file mode 100644 index 0000000..4723bda --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java @@ -0,0 +1,7 @@ +package ru.ulstu.utils.timetable.errors; + +public class TimetableClientException extends RuntimeException { + public TimetableClientException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/utils/timetable/model/Day.java new file mode 100644 index 0000000..e4e37f9 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Day.java @@ -0,0 +1,28 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.ArrayList; +import java.util.List; + + +public class Day { + + private Integer day; + private List> lessons = new ArrayList<>(); + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public List> getLessons() { + return lessons; + } + + public void setLessons(List> lessons) { + this.lessons = lessons; + } +} + diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java new file mode 100644 index 0000000..b1b1707 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java @@ -0,0 +1,24 @@ +package ru.ulstu.utils.timetable.model; + +public class Lesson { + private String group; + private String nameOfLesson; + private String teacher; + private String room; + + public String getGroup() { + return group; + } + + public String getNameOfLesson() { + return nameOfLesson; + } + + public String getTeacher() { + return teacher; + } + + public String getRoom() { + return room; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/utils/timetable/model/Response.java new file mode 100644 index 0000000..dfd3a84 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Response.java @@ -0,0 +1,17 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.ArrayList; +import java.util.List; + +public class Response { + + private List weeks = new ArrayList<>(); + + public List getWeeks() { + return weeks; + } + + public void setWeeks(List weeks) { + this.weeks = weeks; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java new file mode 100644 index 0000000..925d9a8 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java @@ -0,0 +1,22 @@ +package ru.ulstu.utils.timetable.model; + +public class TimetableResponse { + private Response response; + private String error; + + public Response getResponse() { + return response; + } + + public void setResponse(Response response) { + this.response = response; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/utils/timetable/model/Week.java new file mode 100644 index 0000000..8ea76ea --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Week.java @@ -0,0 +1,18 @@ +package ru.ulstu.utils.timetable.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class Week implements Serializable { + + private List days = new ArrayList<>(); + + public List getDays() { + return days; + } + + public void setDays(List days) { + this.days = days; + } +} diff --git a/src/main/resources/templates/users/dashboard.html b/src/main/resources/templates/users/dashboard.html new file mode 100644 index 0000000..e5b7563 --- /dev/null +++ b/src/main/resources/templates/users/dashboard.html @@ -0,0 +1,35 @@ + + + + + + +
+
+
+
+

Пользователи

+
+
+

teste

+
+
+ +
+ +
+
+
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users/fragments/userDashboardFragment.html b/src/main/resources/templates/users/fragments/userDashboardFragment.html new file mode 100644 index 0000000..267bbf8 --- /dev/null +++ b/src/main/resources/templates/users/fragments/userDashboardFragment.html @@ -0,0 +1,18 @@ + + + + + + +
+
+
+

+

+

+

Онлайн

+
+
+
+ + \ No newline at end of file