Merge branch '91-users-info' into 'dev'

Resolve "Сводка по пользователям"

Closes #91

See merge request romanov73/ng-tracker!99
This commit is contained in:
Anton Romanov 2019-05-27 18:03:41 +00:00
commit 6258e7b6bf
17 changed files with 724 additions and 357 deletions

View File

@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository<Conference, Integer>
@Override @Override
@Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") @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); 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);
} }

View File

@ -313,4 +313,8 @@ public class ConferenceService extends BaseService {
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public Conference getActiveConferenceByUser(User user) {
return conferenceRepository.findActiveByUser(user);
}
} }

View File

@ -43,6 +43,4 @@ public class ConferenceUserService {
newUser = conferenceUserRepository.save(newUser); newUser = conferenceUserRepository.save(newUser);
return newUser; return newUser;
} }
} }

View File

@ -48,4 +48,9 @@ public class UserMvcController extends OdinController<UserListDto, UserDto> {
User user = userSessionService.getUserBySessionId(sessionId); User user = userSessionService.getUserBySessionId(sessionId);
modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
} }
@GetMapping("/dashboard")
public void getUsersDashboard(ModelMap modelMap) {
modelMap.addAllAttributes(userService.getUsersInfo());
}
} }

View File

@ -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;
}
}

View File

@ -1,6 +1,7 @@
package ru.ulstu.user.repository; package ru.ulstu.user.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSession;
import java.util.Date; import java.util.Date;
@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository<UserSession, Intege
UserSession findOneBySessionId(String sessionId); UserSession findOneBySessionId(String sessionId);
List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date);
List<UserSession> findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date);
} }

View File

@ -1,355 +1,392 @@
package ru.ulstu.user.service; package ru.ulstu.user.service;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
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.context.annotation.Lazy;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Page;
import org.springframework.mail.MailException; import org.springframework.data.domain.Sort;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.mail.MailException;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.configuration.ApplicationProperties; import org.springframework.util.StringUtils;
import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.core.jpa.OffsetablePageRequest; import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.model.response.PageableItems; import ru.ulstu.core.jpa.OffsetablePageRequest;
import ru.ulstu.user.error.UserActivationError; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.error.UserEmailExistsException; import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.user.error.UserIdExistsException; import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserIsUndeadException; import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserLoginExistsException; import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.model.User; import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserRole; import ru.ulstu.user.model.UserInfoNow;
import ru.ulstu.user.model.UserRoleConstants; import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.model.UserRoleDto; import ru.ulstu.user.model.UserResetPasswordDto;
import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.model.UserRole;
import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.util.UserUtils; import ru.ulstu.user.model.UserRoleDto;
import ru.ulstu.user.repository.UserRepository;
import javax.mail.MessagingException; import ru.ulstu.user.repository.UserRoleRepository;
import java.util.Collections; import ru.ulstu.user.util.UserUtils;
import java.util.Comparator; import ru.ulstu.utils.timetable.TimetableService;
import java.util.Date; import ru.ulstu.utils.timetable.errors.TimetableClientException;
import java.util.List; import ru.ulstu.utils.timetable.model.Lesson;
import java.util.Map;
import java.util.Objects; import javax.mail.MessagingException;
import java.util.Optional; import java.text.ParseException;
import java.util.Set; import java.util.ArrayList;
import java.util.stream.Collectors; import java.util.Collections;
import java.util.Comparator;
@Service import java.util.Date;
@Transactional import java.util.List;
public class UserService implements UserDetailsService { import java.util.Map;
private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; import java.util.Objects;
import java.util.Optional;
private final Logger log = LoggerFactory.getLogger(UserService.class); import java.util.Set;
private final UserRepository userRepository; import java.util.stream.Collectors;
private final PasswordEncoder passwordEncoder;
private final UserRoleRepository userRoleRepository; @Service
private final UserMapper userMapper; @Transactional
private final MailService mailService; public class UserService implements UserDetailsService {
private final ApplicationProperties applicationProperties; private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
public UserService(UserRepository userRepository, private final Logger log = LoggerFactory.getLogger(UserService.class);
PasswordEncoder passwordEncoder, private final UserRepository userRepository;
UserRoleRepository userRoleRepository, private final PasswordEncoder passwordEncoder;
UserMapper userMapper, private final UserRoleRepository userRoleRepository;
MailService mailService, private final UserMapper userMapper;
ApplicationProperties applicationProperties) { private final MailService mailService;
this.userRepository = userRepository; private final ApplicationProperties applicationProperties;
this.passwordEncoder = passwordEncoder; private final TimetableService timetableService;
this.userRoleRepository = userRoleRepository; private final ConferenceService conferenceService;
this.userMapper = userMapper; private final UserSessionService userSessionService;
this.mailService = mailService;
this.applicationProperties = applicationProperties; public UserService(UserRepository userRepository,
} PasswordEncoder passwordEncoder,
UserRoleRepository userRoleRepository,
private User getUserByEmail(String email) { UserMapper userMapper,
return userRepository.findOneByEmailIgnoreCase(email); MailService mailService,
} ApplicationProperties applicationProperties,
@Lazy ConferenceService conferenceRepository,
private User getUserByActivationKey(String activationKey) { @Lazy UserSessionService userSessionService) throws ParseException {
return userRepository.findOneByActivationKey(activationKey); this.userRepository = userRepository;
} this.passwordEncoder = passwordEncoder;
this.userRoleRepository = userRoleRepository;
public User getUserByLogin(String login) { this.userMapper = userMapper;
return userRepository.findOneByLoginIgnoreCase(login); this.mailService = mailService;
} this.applicationProperties = applicationProperties;
this.conferenceService = conferenceRepository;
@Transactional(readOnly = true) this.timetableService = new TimetableService();
public UserDto getUserWithRolesById(Integer userId) { this.userSessionService = userSessionService;
final User userEntity = userRepository.findOneWithRolesById(userId); }
if (userEntity == null) {
throw new UserNotFoundException(userId.toString()); private User getUserByEmail(String email) {
} return userRepository.findOneByEmailIgnoreCase(email);
return userMapper.userEntityToUserDto(userEntity); }
}
private User getUserByActivationKey(String activationKey) {
@Transactional(readOnly = true) return userRepository.findOneByActivationKey(activationKey);
public PageableItems<UserListDto> getAllUsers(int offset, int count) { }
final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); public User getUserByLogin(String login) {
} return userRepository.findOneByLoginIgnoreCase(login);
}
// TODO: read only active users
public List<User> findAll() { @Transactional(readOnly = true)
return userRepository.findAll(); public UserDto getUserWithRolesById(Integer userId) {
} final User userEntity = userRepository.findOneWithRolesById(userId);
if (userEntity == null) {
@Transactional(readOnly = true) throw new UserNotFoundException(userId.toString());
public PageableItems<UserRoleDto> getUserRoles() { }
final List<UserRoleDto> roles = userRoleRepository.findAll().stream() return userMapper.userEntityToUserDto(userEntity);
.map(UserRoleDto::new) }
.sorted(Comparator.comparing(UserRoleDto::getViewValue))
.collect(Collectors.toList()); @Transactional(readOnly = true)
return new PageableItems<>(roles.size(), roles); public PageableItems<UserListDto> getAllUsers(int offset, int count) {
} final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
public UserDto createUser(UserDto userDto) { }
if (userDto.getId() != null) {
throw new UserIdExistsException(); // TODO: read only active users
} public List<User> findAll() {
if (getUserByLogin(userDto.getLogin()) != null) { return userRepository.findAll();
throw new UserLoginExistsException(userDto.getLogin()); }
}
if (getUserByEmail(userDto.getEmail()) != null) { @Transactional(readOnly = true)
throw new UserEmailExistsException(userDto.getEmail()); public PageableItems<UserRoleDto> getUserRoles() {
} final List<UserRoleDto> roles = userRoleRepository.findAll().stream()
if (!userDto.isPasswordsValid()) { .map(UserRoleDto::new)
throw new UserPasswordsNotValidOrNotMatchException(""); .sorted(Comparator.comparing(UserRoleDto::getViewValue))
} .collect(Collectors.toList());
User user = userMapper.userDtoToUserEntity(userDto); return new PageableItems<>(roles.size(), roles);
user.setActivated(false); }
user.setActivationKey(UserUtils.generateActivationKey());
user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); public UserDto createUser(UserDto userDto) {
user.setPassword(passwordEncoder.encode(userDto.getPassword())); if (userDto.getId() != null) {
user = userRepository.save(user); throw new UserIdExistsException();
mailService.sendActivationEmail(user); }
log.debug("Created Information for User: {}", user.getLogin()); if (getUserByLogin(userDto.getLogin()) != null) {
return userMapper.userEntityToUserDto(user); throw new UserLoginExistsException(userDto.getLogin());
} }
if (getUserByEmail(userDto.getEmail()) != null) {
public UserDto activateUser(String activationKey) { throw new UserEmailExistsException(userDto.getEmail());
final User user = getUserByActivationKey(activationKey); }
if (user == null) { if (!userDto.isPasswordsValid()) {
throw new UserActivationError(activationKey); throw new UserPasswordsNotValidOrNotMatchException("");
} }
user.setActivated(true); User user = userMapper.userDtoToUserEntity(userDto);
user.setActivationKey(null); user.setActivated(false);
user.setActivationDate(null); user.setActivationKey(UserUtils.generateActivationKey());
log.debug("Activated user: {}", user.getLogin()); user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
return userMapper.userEntityToUserDto(userRepository.save(user)); user.setPassword(passwordEncoder.encode(userDto.getPassword()));
} user = userRepository.save(user);
mailService.sendActivationEmail(user);
public UserDto updateUser(UserDto userDto) { log.debug("Created Information for User: {}", user.getLogin());
if (userDto.getId() == null) { return userMapper.userEntityToUserDto(user);
throw new EntityIdIsNullException(); }
}
if (!Objects.equals( public UserDto activateUser(String activationKey) {
Optional.ofNullable(getUserByEmail(userDto.getEmail())) final User user = getUserByActivationKey(activationKey);
.map(BaseEntity::getId).orElse(userDto.getId()), if (user == null) {
userDto.getId())) { throw new UserActivationError(activationKey);
throw new UserEmailExistsException(userDto.getEmail()); }
} user.setActivated(true);
if (!Objects.equals( user.setActivationKey(null);
Optional.ofNullable(getUserByLogin(userDto.getLogin())) user.setActivationDate(null);
.map(BaseEntity::getId).orElse(userDto.getId()), log.debug("Activated user: {}", user.getLogin());
userDto.getId())) { return userMapper.userEntityToUserDto(userRepository.save(user));
throw new UserLoginExistsException(userDto.getLogin()); }
}
User user = userRepository.findOne(userDto.getId()); public UserDto updateUser(UserDto userDto) {
if (user == null) { if (userDto.getId() == null) {
throw new UserNotFoundException(userDto.getId().toString()); throw new EntityIdIsNullException();
} }
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { if (!Objects.equals(
userDto.setLogin(applicationProperties.getUndeadUserLogin()); Optional.ofNullable(getUserByEmail(userDto.getEmail()))
userDto.setActivated(true); .map(BaseEntity::getId).orElse(userDto.getId()),
userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); userDto.getId())) {
} throw new UserEmailExistsException(userDto.getEmail());
user.setLogin(userDto.getLogin()); }
user.setFirstName(userDto.getFirstName()); if (!Objects.equals(
user.setLastName(userDto.getLastName()); Optional.ofNullable(getUserByLogin(userDto.getLogin()))
user.setEmail(userDto.getEmail()); .map(BaseEntity::getId).orElse(userDto.getId()),
if (userDto.isActivated() != user.getActivated()) { userDto.getId())) {
if (userDto.isActivated()) { throw new UserLoginExistsException(userDto.getLogin());
user.setActivationKey(null); }
user.setActivationDate(null); User user = userRepository.findOne(userDto.getId());
} else { if (user == null) {
user.setActivationKey(UserUtils.generateActivationKey()); throw new UserNotFoundException(userDto.getId().toString());
user.setActivationDate(new Date()); }
} if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
} userDto.setLogin(applicationProperties.getUndeadUserLogin());
user.setActivated(userDto.isActivated()); userDto.setActivated(true);
final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles()); userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
user.setRoles(roles.isEmpty() }
? Collections.singleton(new UserRole(UserRoleConstants.USER)) user.setLogin(userDto.getLogin());
: roles); user.setFirstName(userDto.getFirstName());
if (!StringUtils.isEmpty(userDto.getOldPassword())) { user.setLastName(userDto.getLastName());
if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { user.setEmail(userDto.getEmail());
throw new UserPasswordsNotValidOrNotMatchException(""); if (userDto.isActivated() != user.getActivated()) {
} if (userDto.isActivated()) {
if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { user.setActivationKey(null);
throw new UserPasswordsNotValidOrNotMatchException(""); user.setActivationDate(null);
} } else {
user.setPassword(passwordEncoder.encode(userDto.getPassword())); user.setActivationKey(UserUtils.generateActivationKey());
log.debug("Changed password for User: {}", user.getLogin()); user.setActivationDate(new Date());
} }
user = userRepository.save(user); }
log.debug("Changed Information for User: {}", user.getLogin()); user.setActivated(userDto.isActivated());
return userMapper.userEntityToUserDto(user); final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles());
} user.setRoles(roles.isEmpty()
? Collections.singleton(new UserRole(UserRoleConstants.USER))
public UserDto updateUserInformation(User user, UserDto updateUser) { : roles);
user.setFirstName(updateUser.getFirstName()); if (!StringUtils.isEmpty(userDto.getOldPassword())) {
user.setLastName(updateUser.getLastName()); if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
user.setEmail(updateUser.getEmail()); throw new UserPasswordsNotValidOrNotMatchException("");
user.setLogin(updateUser.getLogin()); }
user = userRepository.save(user); if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
log.debug("Updated Information for User: {}", user.getLogin()); throw new UserPasswordsNotValidOrNotMatchException("");
return userMapper.userEntityToUserDto(user); }
} user.setPassword(passwordEncoder.encode(userDto.getPassword()));
log.debug("Changed password for User: {}", user.getLogin());
public void changeUserPassword(User user, Map<String, String> payload) { }
if (!payload.get("password").equals(payload.get("confirmPassword"))) { user = userRepository.save(user);
throw new UserPasswordsNotValidOrNotMatchException(""); log.debug("Changed Information for User: {}", user.getLogin());
} return userMapper.userEntityToUserDto(user);
if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { }
throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
} public UserDto updateUserInformation(User user, UserDto updateUser) {
user.setPassword(passwordEncoder.encode(payload.get("password"))); user.setFirstName(updateUser.getFirstName());
log.debug("Changed password for User: {}", user.getLogin()); user.setLastName(updateUser.getLastName());
userRepository.save(user); user.setEmail(updateUser.getEmail());
user.setLogin(updateUser.getLogin());
mailService.sendChangePasswordMail(user); user = userRepository.save(user);
} log.debug("Updated Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
public boolean requestUserPasswordReset(String email) { }
User user = userRepository.findOneByEmailIgnoreCase(email);
if (user == null) { public void changeUserPassword(User user, Map<String, String> payload) {
throw new UserNotFoundException(email); if (!payload.get("password").equals(payload.get("confirmPassword"))) {
} throw new UserPasswordsNotValidOrNotMatchException("");
if (!user.getActivated()) { }
throw new UserNotActivatedException(); if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
} throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
user.setResetKey(UserUtils.generateResetKey()); }
user.setResetDate(new Date()); user.setPassword(passwordEncoder.encode(payload.get("password")));
user = userRepository.save(user); log.debug("Changed password for User: {}", user.getLogin());
try { userRepository.save(user);
mailService.sendPasswordResetMail(user);
} catch (MessagingException | MailException e) { mailService.sendChangePasswordMail(user);
throw new UserSendingMailException(email); }
}
log.debug("Created Reset Password Request for User: {}", user.getLogin()); public boolean requestUserPasswordReset(String email) {
return true; User user = userRepository.findOneByEmailIgnoreCase(email);
} if (user == null) {
throw new UserNotFoundException(email);
public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { }
if (!userResetPasswordDto.isPasswordsValid()) { if (!user.getActivated()) {
throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); throw new UserNotActivatedException();
} }
User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); user.setResetKey(UserUtils.generateResetKey());
if (user == null) { user.setResetDate(new Date());
throw new UserResetKeyError(userResetPasswordDto.getResetKey()); user = userRepository.save(user);
} try {
user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); mailService.sendPasswordResetMail(user);
user.setResetKey(null); } catch (MessagingException | MailException e) {
user.setResetDate(null); throw new UserSendingMailException(email);
user = userRepository.save(user); }
log.debug("Created Reset Password Request for User: {}", user.getLogin());
mailService.sendChangePasswordMail(user); return true;
}
log.debug("Reset Password for User: {}", user.getLogin());
return true; public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) {
} if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают");
public UserDto deleteUser(Integer userId) { }
final User user = userRepository.findOne(userId); User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey());
if (user == null) { if (user == null) {
throw new UserNotFoundException(userId.toString()); throw new UserResetKeyError(userResetPasswordDto.getResetKey());
} }
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
throw new UserIsUndeadException(user.getLogin()); user.setResetKey(null);
} user.setResetDate(null);
userRepository.delete(user); user = userRepository.save(user);
log.debug("Deleted User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user); mailService.sendChangePasswordMail(user);
}
log.debug("Reset Password for User: {}", user.getLogin());
@Override return true;
public UserDetails loadUserByUsername(String username) { }
final User user = userRepository.findOneByLoginIgnoreCase(username);
if (user == null) { public UserDto deleteUser(Integer userId) {
throw new UserNotFoundException(username); final User user = userRepository.findOne(userId);
} if (user == null) {
if (!user.getActivated()) { throw new UserNotFoundException(userId.toString());
throw new UserNotActivatedException(); }
} if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
return new org.springframework.security.core.userdetails.User(user.getLogin(), throw new UserIsUndeadException(user.getLogin());
user.getPassword(), }
Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() userRepository.delete(user);
.map(role -> new SimpleGrantedAuthority(role.getName())) log.debug("Deleted User: {}", user.getLogin());
.collect(Collectors.toList())); return userMapper.userEntityToUserDto(user);
} }
public List<User> findByIds(List<Integer> ids) { @Override
return userRepository.findAll(ids); public UserDetails loadUserByUsername(String username) {
} final User user = userRepository.findOneByLoginIgnoreCase(username);
if (user == null) {
public User findById(Integer id) { throw new UserNotFoundException(username);
return userRepository.findOne(id); }
} if (!user.getActivated()) {
throw new UserNotActivatedException();
public User getCurrentUser() { }
String login = UserUtils.getCurrentUserLogin(); return new org.springframework.security.core.userdetails.User(user.getLogin(),
User user = userRepository.findOneByLoginIgnoreCase(login); user.getPassword(),
if (user == null) { Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
throw new UserNotFoundException(login); .map(role -> new SimpleGrantedAuthority(role.getName()))
} .collect(Collectors.toList()));
return user; }
}
public List<User> findByIds(List<Integer> ids) {
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { return userRepository.findAll(ids);
return userRepository.filterByAgeAndDegree(hasDegree, hasAge); }
}
public User findById(Integer id) {
public void inviteUser(String email) throws UserSendingMailException { return userRepository.findOne(id);
if (userRepository.findOneByEmailIgnoreCase(email) != null) { }
throw new UserEmailExistsException(email);
} public User getCurrentUser() {
String login = UserUtils.getCurrentUserLogin();
String password = UserUtils.generatePassword(); User user = userRepository.findOneByLoginIgnoreCase(login);
if (user == null) {
User user = new User(); throw new UserNotFoundException(login);
user.setPassword(passwordEncoder.encode(password)); }
user.setLogin(email); return user;
user.setEmail(email); }
user.setFirstName("user");
user.setLastName("user"); public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
user.setActivated(true); return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
userRepository.save(user); }
Map<String, Object> variables = ImmutableMap.of("password", password, "email", email); public void inviteUser(String email) throws UserSendingMailException {
try { if (userRepository.findOneByEmailIgnoreCase(email) != null) {
mailService.sendInviteMail(variables, email); throw new UserEmailExistsException(email);
} catch (MessagingException | MailException e) { }
throw new UserSendingMailException(email);
} String password = UserUtils.generatePassword();
}
User user = new User();
public User findOneByLoginIgnoreCase(String login) { user.setPassword(passwordEncoder.encode(password));
return userRepository.findOneByLoginIgnoreCase(login); user.setLogin(email);
} user.setEmail(email);
} user.setFirstName("user");
user.setLastName("user");
user.setActivated(true);
userRepository.save(user);
Map<String, Object> 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<String, Object> getUsersInfo() {
List<UserInfoNow> 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);
}
}

View File

@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession;
import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.model.UserSessionListDto;
import ru.ulstu.user.repository.UserSessionRepository; import ru.ulstu.user.repository.UserSessionRepository;
import java.util.Date;
import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.core.util.StreamApiUtils.convert;
@Service @Service
@ -58,4 +60,8 @@ public class UserSessionService {
public User getUserBySessionId(String sessionId) { public User getUserBySessionId(String sessionId) {
return userSessionRepository.findOneBySessionId(sessionId).getUser(); return userSessionRepository.findOneBySessionId(sessionId).getUser();
} }
public boolean isOnline(User user) {
return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty();
}
} }

View File

@ -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<Lesson> 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);
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.utils.timetable.errors;
public class TimetableClientException extends RuntimeException {
public TimetableClientException(String message) {
super(message);
}
}

View File

@ -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<List<Lesson>> lessons = new ArrayList<>();
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
public List<List<Lesson>> getLessons() {
return lessons;
}
public void setLessons(List<List<Lesson>> lessons) {
this.lessons = lessons;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.utils.timetable.model;
import java.util.ArrayList;
import java.util.List;
public class Response {
private List<Week> weeks = new ArrayList<>();
public List<Week> getWeeks() {
return weeks;
}
public void setWeeks(List<Week> weeks) {
this.weeks = weeks;
}
}

View File

@ -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;
}
}

View File

@ -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<Day> days = new ArrayList<>();
public List<Day> getDays() {
return days;
}
public void setDays(List<Day> days) {
this.days = days;
}
}

View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<script src="/js/core.js"></script>
</head>
<body>
<div class="container" layout:fragment="content">
<section id="services">
<div class="container">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Пользователи</h2>
</div>
<div class="text-center">
<h2 th:text="${error}">teste</h2>
</div>
<div class="row justify-content-center" id="dashboard">
<th:block th:each="user : ${users}">
<div th:replace="users/fragments/userDashboardFragment :: userDashboard(user=${user})"/>
</th:block>
</div>
</div>
</section>
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function () {
var error = /*[[${error}]]*/
showFeedbackMessage(error, MessageTypesEnum.WARNING)
});
/*]]>*/
</script>
</div>
</body>
</html>

View File

@ -0,0 +1,18 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="headerfiles">
<meta charset="UTF-8"/>
</head>
<body>
<div th:fragment="userDashboard (user)" class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3 dashboard-card">
<div class="row">
<div class="col col-10">
<b><p th:text="${user.user.lastName} + ' ' + ${user.user.firstName} + ' ' + ${user.user.patronymic}"></p></b>
<i><p th:if="${user.conference != null}" th:text="'Сейчас на конференции ' + ${user.conference.title}"></p></i>
<i><p th:if="${user.lesson != null}" th:text="'Сейчас на паре ' + ${user.lesson.nameOfLesson} + ' в аудитории ' + ${user.lesson.room}"></p></i>
<p th:if="${user.isOnline()}">Онлайн</p>
</div>
</div>
</div>
</body>
</html>