add service methods

This commit is contained in:
Anton Romanov 2019-03-12 12:51:59 +03:00
parent 20ecb47867
commit da7a17ee49
3 changed files with 479 additions and 418 deletions

View File

@ -23,11 +23,29 @@ import ru.ulstu.user.error.UserResetKeyError;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import ru.ulstu.user.service.UserService;
@RestController
@ControllerAdvice
public class AdviceController {
private final static String USER_NAME_TEMPLATE = "%s %s %s";
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private final UserService userService;
public AdviceController(UserService userService) {
this.userService = userService;
}
@ModelAttribute
public void globalAttributes(Model model) {
model.addAttribute("currentUser", String.format(USER_NAME_TEMPLATE,
userService.getCurrentUser().getLastName(),
userService.getCurrentUser().getFirstName().substring(0, 1),
userService.getCurrentUser().getFirstName().substring(0, 1)));
}
private Response<Void> handleException(ErrorConstants error) {
log.warn(error.toString());

View File

@ -315,4 +315,13 @@ public class UserService implements UserDetailsService {
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;
}
}

View File

@ -0,0 +1,34 @@
package ru.ulstu.user.service;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
public class UserUtils {
private static final int DEF_COUNT = 20;
public static String generateActivationKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
public static String generateResetKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
public static String getCurrentUserLogin() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext == null) {
return null;
}
final Authentication authentication = securityContext.getAuthentication();
if (authentication.getPrincipal() instanceof UserDetails) {
final UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
}
if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
}
}