@PostMapping("/registration")
public String registerUser(@ModelAttribute("customer") Customer customer, BindingResult customerResult,
@ModelAttribute("address") Address address, BindingResult addressResult, Role role, Model model) {
if (customerResult.hasErrors() || addressResult.hasErrors()) {
log.error("Validation errors occurred during user registration.");
return "registration";
}
if (customerService.findByEmail(customer.getEmail()) != null) {
log.error("Email already exists during user registration.");
customerResult.rejectValue("email", null, "Email already exists");
return "registration";
}
String encodedPassword = passwordEncoder.encode(customer.getPassword());
customer.setPassword(encodedPassword);
customer.setAddress(address);
customer.setRole(role.Users);
customerService.save(customer, address);
log.info("User registered successfully.");
return "redirect:/Main";
}
@PostMapping("/login")
public String login(@RequestParam("email") String email, @RequestParam("password") String password, Model model) {
if (isAdmin(email, password, customerService)) {
return "redirect:/AdminPanel";
} else {
model.addAttribute("email", email);
model.addAttribute("password", password);
// Возвращаем страницу входа с сообщением об ошибке
model.addAttribute("error", "Invalid credentials");
return "redirect:/Main";
}
}
public boolean isAdmin(String email, String password, CustomerService customerService) {
Customer admin = customerService.findByEmail(email);
if (admin != null && admin.getEmail().equals(AppConfig.ADMIN_EMAIL) && admin.getPassword().equals(password)) {
return true;
}
return false;
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // Включаем CSRF защиту
.csrf().disable() // Используем Cookie для хранения CSRF токенов
.authorizeRequests()
.antMatchers("/registration", "/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
// Добавьте другие правила авторизации, если необходимо
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/Main", true)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login").permitAll();
}
@Bean
@Primary
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppConfig extends GlobalMethodSecurityConfiguration {
public static final String ADMIN_EMAIL = "[email protected]";
@Bean
public CommandLineRunner demo(final CustomerService customerService,
final PasswordEncoder encoder) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
// Создаем объекты Customer и Address для администратора
Customer adminCustomer = new Customer();
adminCustomer.setEmail(ADMIN_EMAIL);
adminCustomer.setPassword(encoder.encode("1"));
adminCustomer.setRole(Role.Admin);
Address adminAddress = new Address();
// Задайте адрес администратора по вашему желанию
// Сохраняем администратора
customerService.save(adminCustomer, adminAddress);
Customer userCustomer = new Customer();
userCustomer.setEmail("[email protected]");
userCustomer.setPassword(encoder.encode("password"));
userCustomer.setRole(Role.Users);
Address userAddress = new Address();
customerService.save(userCustomer, userAddress);
}
};
}
}