add oauth2 google

This commit is contained in:
Anton Romanov 2019-11-27 19:41:10 +04:00
parent 71448364d7
commit ac55481bc6
12 changed files with 620 additions and 585 deletions

View File

@ -105,6 +105,9 @@ dependencies {
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5' compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5'
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner' compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5' compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5'
compile group: 'org.springframework.security', name: 'spring-security-oauth2-client'
compile group: 'org.springframework.security', name: 'spring-security-oauth2-jose'
compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure'
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5' compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'

View File

@ -9,7 +9,5 @@ public class MvcConfiguration implements WebMvcConfigurer {
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/index.xhtml"); registry.addRedirectViewController("/", "/index.xhtml");
registry.addRedirectViewController("/default", "/index.xhtml");
} }
} }

View File

@ -5,27 +5,48 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import ru.ulstu.core.model.AuthFailureHandler; import ru.ulstu.core.model.AuthFailureHandler;
import ru.ulstu.user.controller.UserController;
import ru.ulstu.user.model.UserRoleConstants; import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static List<String> clients = Arrays.asList("google");
private static String CLIENT_PROPERTY_KEY
= "spring.security.oauth2.client.registration.";
@Autowired
private Environment env;
@Value("${server.http.port}") @Value("${server.http.port}")
private int httpPort; private int httpPort;
@ -54,6 +75,124 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable();
if (applicationProperties.isDevMode()) {
log.debug("Security disabled");
http.authorizeRequests()
.anyRequest()
.permitAll();
http.anonymous()
.principal("admin")
.authorities(UserRoleConstants.ADMIN);
} else {
http.authorizeRequests()
.antMatchers("/login.xhtml", "/logout")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login.xhtml")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.permitAll()
.and()
.oauth2Login()
.loginPage("/login.xhtml")
.authorizationEndpoint()
.baseUri("/oauth2/authorize-client")
.authorizationRequestRepository(authorizationRequestRepository())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.defaultSuccessUrl("/index.xhtml")
.failureUrl("/loginFailure")
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.logoutSuccessUrl(Constants.LOGOUT_URL)
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies(Constants.COOKIES_NAME)
.permitAll();
http.csrf().disable();
}
if (applicationProperties.isUseHttps()) {
http.portMapper()
.http(httpPort)
.mapsTo(httpsPort)
.and()
.requiresChannel()
.anyRequest()
.requiresSecure();
}
}
@Bean
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new HttpSessionOAuth2AuthorizationRequestRepository();
}
@Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
return accessTokenResponseClient;
}
//@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
List<ClientRegistration> registrations = clients.stream()
.map(c -> getRegistration(c))
.filter(registration -> registration != null)
.collect(Collectors.toList());
return new InMemoryClientRegistrationRepository(registrations);
}
private ClientRegistration getRegistration(String client) {
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
if (clientId == null) {
return null;
}
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
if (client.equals("google")) {
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
return null;
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/css/**")
.antMatchers("/javax.faces.resource/**")
.antMatchers("/js/**")
.antMatchers("/templates/**")
.antMatchers("/webjars/**")
.antMatchers("/img/**");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
if (applicationProperties.isDevMode()) {
return;
}
try {
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
/* @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.csrf() http.csrf()
.disable(); .disable();
@ -126,5 +265,5 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} catch (Exception e) { } catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e); throw new BeanInitializationException("Security configuration failed", e);
} }
} }*/
} }

View File

@ -1,120 +0,0 @@
package ru.ulstu.core.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.model.ErrorConstants;
import ru.ulstu.core.model.response.Response;
import ru.ulstu.core.model.response.ResponseExtended;
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.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.service.UserService;
import java.util.Set;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private final UserService userService;
public AdviceController(UserService userService) {
this.userService = userService;
}
@ModelAttribute("currentUser")
public String getCurrentUser() {
return userService.getCurrentUser().getUserAbbreviate();
}
@ModelAttribute("flashMessage")
public String getFlashMessage() {
return null;
}
private Response<Void> handleException(ErrorConstants error) {
log.warn(error.toString());
return new Response<>(error);
}
private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) {
log.warn(error.toString());
return new ResponseExtended<>(error, errorData);
}
@ExceptionHandler(EntityIdIsNullException.class)
public Response<Void> handleEntityIdIsNullException(Throwable e) {
return handleException(ErrorConstants.ID_IS_NULL);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
final Set<String> errors = e.getBindingResult().getAllErrors().stream()
.filter(error -> error instanceof FieldError)
.map(error -> ((FieldError) error).getField())
.collect(Collectors.toSet());
return handleException(ErrorConstants.VALIDATION_ERROR, errors);
}
@ExceptionHandler(UserIdExistsException.class)
public Response<Void> handleUserIdExistsException(Throwable e) {
return handleException(ErrorConstants.USER_ID_EXISTS);
}
@ExceptionHandler(UserActivationError.class)
public ResponseExtended<String> handleUserActivationError(Throwable e) {
return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
}
@ExceptionHandler(UserLoginExistsException.class)
public ResponseExtended<String> handleUserLoginExistsException(Throwable e) {
return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
}
@ExceptionHandler(UserEmailExistsException.class)
public ResponseExtended<String> handleUserEmailExistsException(Throwable e) {
return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
}
@ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
}
// @ExceptionHandler(UserNotFoundException.class)
// 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());
}
@ExceptionHandler(UserSendingMailException.class)
public ResponseExtended<String> handleUserSendingMailException(Throwable e) {
return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage());
}
}

View File

@ -1,23 +0,0 @@
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;
import springfox.documentation.annotations.ApiIgnore;
@Controller()
@RequestMapping(value = "/index")
@ApiIgnore
public class IndexController extends AdviceController {
public IndexController(UserService userService) {
super(userService);
}
@GetMapping
public void currentUser(ModelMap modelMap) {
//нужен здесь для добавления параметров на стартовой странице
}
}

View File

@ -1,435 +1,438 @@
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.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
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.mail.MailException; import org.springframework.mail.MailException;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
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.conference.service.ConferenceService; import ru.ulstu.conference.service.ConferenceService;
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.UserActivity; import ru.ulstu.core.model.UserActivity;
import ru.ulstu.core.model.response.PageableItems; import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.ping.model.Ping; import ru.ulstu.ping.model.Ping;
import ru.ulstu.ping.service.PingService; import ru.ulstu.ping.service.PingService;
import ru.ulstu.user.error.UserActivationError; import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserBlockedException; import ru.ulstu.user.error.UserBlockedException;
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.error.UserSendingMailException; import ru.ulstu.user.error.UserSendingMailException;
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.UserInfoNow; import ru.ulstu.user.model.UserInfoNow;
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 ru.ulstu.utils.timetable.TimetableService; import ru.ulstu.utils.timetable.TimetableService;
import ru.ulstu.utils.timetable.errors.TimetableClientException; import ru.ulstu.utils.timetable.errors.TimetableClientException;
import ru.ulstu.utils.timetable.model.Lesson; import ru.ulstu.utils.timetable.model.Lesson;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
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.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
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 static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
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;
private final TimetableService timetableService; private final TimetableService timetableService;
private final ConferenceService conferenceService; private final ConferenceService conferenceService;
private final UserSessionService userSessionService; private final UserSessionService userSessionService;
private final PingService pingService; private final PingService pingService;
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,
@Lazy PingService pingService, @Lazy PingService pingService,
@Lazy ConferenceService conferenceRepository, @Lazy ConferenceService conferenceRepository,
@Lazy UserSessionService userSessionService) throws ParseException { @Lazy UserSessionService userSessionService) throws ParseException {
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;
this.conferenceService = conferenceRepository; this.conferenceService = conferenceRepository;
this.timetableService = new TimetableService(); this.timetableService = new TimetableService();
this.userSessionService = userSessionService; this.userSessionService = userSessionService;
this.pingService = pingService; this.pingService = pingService;
} }
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, Sort.by("id"))); final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, Sort.by("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.getOne(userDto.getId()); User user = userRepository.getOne(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(User user, UserDto updateUser) { public UserDto updateUserInformation(User user, UserDto updateUser) {
user.setFirstName(updateUser.getFirstName()); user.setFirstName(updateUser.getFirstName());
user.setLastName(updateUser.getLastName()); user.setLastName(updateUser.getLastName());
user.setEmail(updateUser.getEmail()); user.setEmail(updateUser.getEmail());
user.setLogin(updateUser.getLogin()); user.setLogin(updateUser.getLogin());
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 void changeUserPassword(User user, Map<String, String> payload) { public void changeUserPassword(User user, Map<String, String> payload) {
if (!payload.get("password").equals(payload.get("confirmPassword"))) { if (!payload.get("password").equals(payload.get("confirmPassword"))) {
throw new UserPasswordsNotValidOrNotMatchException(""); throw new UserPasswordsNotValidOrNotMatchException("");
} }
if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
} }
user.setPassword(passwordEncoder.encode(payload.get("password"))); user.setPassword(passwordEncoder.encode(payload.get("password")));
log.debug("Changed password for User: {}", user.getLogin()); log.debug("Changed password for User: {}", user.getLogin());
userRepository.save(user); userRepository.save(user);
mailService.sendChangePasswordMail(user); mailService.sendChangePasswordMail(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);
try { try {
mailService.sendPasswordResetMail(user); mailService.sendPasswordResetMail(user);
} catch (MessagingException | MailException e) { } catch (MessagingException | MailException e) {
throw new UserSendingMailException(email); throw new UserSendingMailException(email);
} }
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(UserResetPasswordDto userResetPasswordDto) { public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) {
if (!userResetPasswordDto.isPasswordsValid()) { if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают");
} }
User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey());
if (user == null) { if (user == null) {
throw new UserResetKeyError(userResetPasswordDto.getResetKey()); throw new UserResetKeyError(userResetPasswordDto.getResetKey());
} }
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);
mailService.sendChangePasswordMail(user); mailService.sendChangePasswordMail(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.getOne(userId); final User user = userRepository.getOne(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();
} }
if (user.getBlocker() != null) { if (user.getBlocker() != null) {
throw new UserBlockedException(String.format("Вы заблокированы пользователем %s", user.getBlocker().getUserAbbreviate())); throw new UserBlockedException(String.format("Вы заблокированы пользователем %s", user.getBlocker().getUserAbbreviate()));
} }
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.findAllById(ids); return userRepository.findAllById(ids);
} }
public User findById(Integer id) { public User findById(Integer id) {
return userRepository.getOne(id); return userRepository.getOne(id);
} }
public User getCurrentUser() { public User getCurrentUser() {
String login = UserUtils.getCurrentUserLogin(SecurityContextHolder.getContext()); String loginOrEmail = UserUtils.getCurrentUserLoginOrEmail(SecurityContextHolder.getContext());
User user = userRepository.findOneByLoginIgnoreCase(login); User user = userRepository.findOneByLoginIgnoreCase(loginOrEmail);
if (user == null) { if (user == null) {
throw new UserNotFoundException(login); user = userRepository.findOneByEmailIgnoreCase(loginOrEmail);
} }
return user; if (user == null) {
} throw new UserNotFoundException(loginOrEmail);
}
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { return user;
return userRepository.filterByAgeAndDegree(hasDegree, hasAge); }
}
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
public void inviteUser(String email) throws UserSendingMailException { return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
if (userRepository.findOneByEmailIgnoreCase(email) != null) { }
throw new UserEmailExistsException(email);
} public void inviteUser(String email) throws UserSendingMailException {
if (userRepository.findOneByEmailIgnoreCase(email) != null) {
String password = UserUtils.generatePassword(); throw new UserEmailExistsException(email);
}
User user = new User();
user.setPassword(passwordEncoder.encode(password)); String password = UserUtils.generatePassword();
user.setLogin(email);
user.setEmail(email); User user = new User();
user.setFirstName("user"); user.setPassword(passwordEncoder.encode(password));
user.setLastName("user"); user.setLogin(email);
user.setActivated(true); user.setEmail(email);
userRepository.save(user); user.setFirstName("user");
user.setLastName("user");
Map<String, Object> variables = ImmutableMap.of("password", password, "email", email); user.setActivated(true);
try { userRepository.save(user);
mailService.sendInviteMail(variables, email);
} catch (MessagingException | MailException e) { Map<String, Object> variables = ImmutableMap.of("password", password, "email", email);
throw new UserSendingMailException(email); try {
} mailService.sendInviteMail(variables, email);
} } catch (MessagingException | MailException e) {
throw new UserSendingMailException(email);
public User findOneByLoginIgnoreCase(String login) { }
return userRepository.findOneByLoginIgnoreCase(login); }
}
public User findOneByLoginIgnoreCase(String login) {
public Map<String, Object> getUsersInfo() { return userRepository.findOneByLoginIgnoreCase(login);
List<UserInfoNow> usersInfoNow = new ArrayList<>(); }
String err = "";
public Map<String, Object> getUsersInfo() {
for (User user : userRepository.findAll()) { List<UserInfoNow> usersInfoNow = new ArrayList<>();
Lesson lesson = null; String err = "";
try {
lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); for (User user : userRepository.findAll()) {
} catch (TimetableClientException e) { Lesson lesson = null;
err = "Не удалось загрузить расписание"; try {
} lesson = timetableService.getCurrentLesson(user.getUserAbbreviate());
usersInfoNow.add(new UserInfoNow( } catch (TimetableClientException e) {
lesson, err = "Не удалось загрузить расписание";
conferenceService.getActiveConferenceByUser(user), }
user, usersInfoNow.add(new UserInfoNow(
userSessionService.isOnline(user)) lesson,
); conferenceService.getActiveConferenceByUser(user),
} user,
return ImmutableMap.of("users", usersInfoNow, "error", err); userSessionService.isOnline(user))
} );
}
public Map<String, Integer> getActivitiesPings(Integer userId, return ImmutableMap.of("users", usersInfoNow, "error", err);
String activityName) { }
User user = null;
if (userId != null) { public Map<String, Integer> getActivitiesPings(Integer userId,
user = findById(userId); String activityName) {
} User user = null;
Map<String, Integer> activitiesPings = new HashMap<>(); if (userId != null) {
user = findById(userId);
for (Ping ping : pingService.getPings(activityName)) { }
UserActivity activity = ping.getActivity(); Map<String, Integer> activitiesPings = new HashMap<>();
if (user != null && !activity.getActivityUsers().contains(user)) { for (Ping ping : pingService.getPings(activityName)) {
continue; UserActivity activity = ping.getActivity();
}
if (user != null && !activity.getActivityUsers().contains(user)) {
if (activitiesPings.containsKey(activity.getTitle())) { continue;
activitiesPings.put(activity.getTitle(), activitiesPings.get(activity.getTitle()) + 1); }
} else {
activitiesPings.put(activity.getTitle(), 1); if (activitiesPings.containsKey(activity.getTitle())) {
} activitiesPings.put(activity.getTitle(), activitiesPings.get(activity.getTitle()) + 1);
} else {
} activitiesPings.put(activity.getTitle(), 1);
return activitiesPings; }
}
}
public void blockUser(int userId) { return activitiesPings;
User userToBlock = findById(userId); }
userToBlock.setBlocker(getCurrentUser());
userRepository.save(userToBlock); public void blockUser(int userId) {
} User userToBlock = findById(userId);
} userToBlock.setBlocker(getCurrentUser());
userRepository.save(userToBlock);
}
}

View File

@ -4,6 +4,7 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
public class UserUtils { public class UserUtils {
@ -17,7 +18,7 @@ public class UserUtils {
return RandomStringUtils.randomNumeric(DEF_COUNT); return RandomStringUtils.randomNumeric(DEF_COUNT);
} }
public static String getCurrentUserLogin(SecurityContext securityContext) { public static String getCurrentUserLoginOrEmail(SecurityContext securityContext) {
if (securityContext == null) { if (securityContext == null) {
return null; return null;
} }
@ -27,6 +28,10 @@ public class UserUtils {
final UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); final UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername(); return springSecurityUser.getUsername();
} }
if (authentication.getPrincipal() instanceof DefaultOidcUser) {
final DefaultOidcUser oauth2User = (DefaultOidcUser) authentication.getPrincipal();
return oauth2User.getEmail();
}
if (authentication.getPrincipal() instanceof String) { if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal(); return (String) authentication.getPrincipal();
} }

View File

@ -38,7 +38,7 @@
<p:menuitem value="Quit" url="http://www.primefaces.org" icon="pi pi-times"/> <p:menuitem value="Quit" url="http://www.primefaces.org" icon="pi pi-times"/>
<f:facet name="options"> <f:facet name="options">
<p:link href="/logout" value="Logout"/> <p:link href="/logout" value="Выход"/>
</f:facet> </f:facet>
</p:menubar> </p:menubar>
<div class="ui-fluid"> <div class="ui-fluid">

View File

@ -45,6 +45,8 @@
</tr> </tr>
<tr> <tr>
<td> <td>
<a href="oauth2/authorize-client/google"
class="list-group-item active">Войти с учетной записью Google</a>
</td> </td>
</tr> </tr>
</tbody> </tbody>

View File

@ -45,3 +45,5 @@ ng-tracker.debug_email=romanov73@gmail.com
ng-tracker.use-https=false ng-tracker.use-https=false
ng-tracker.check-run=false ng-tracker.check-run=false
ng-tracker.driver-path= ng-tracker.driver-path=
spring.security.oauth2.client.registration.google.client-id=128435862215-4ltm7dr6enb6sfll0qhkt6a1op9juve6.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=W_B-KMpqsSdKahqFxpuK4OoT

View File

@ -34,10 +34,14 @@
</div> </div>
</fieldset> </fieldset>
</form> </form>
<h3>Login with:</h3>
<p th:each="url : ${urls}">
<a th:text="${url.key}" th:href="${url.value}">Client</a>
</p>
</div> </div>
</div> </div>
</div> </div>
</section> </section>
</div> </div>
</body> </body>
</html> </html>

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Oauth2 Login</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<div class="col-sm-3 well">
<h3>Login with:</h3>
<div class="list-group">
<p th:each="url : ${urls}">
<a th:text="${url.key}" th:href="${url.value}" class="list-group-item active">Client</a>
</p>
</div>
</div>
</div>
</body>
</html>