package com.project.beautycenter.web; import com.project.beautycenter.model.Users; import com.project.beautycenter.model.exceptions.InvalidArgumentException; import com.project.beautycenter.service.UsersService; import com.project.beautycenter.service.VraboteniService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller public class LoginController { private final UsersService usersService; private final PasswordEncoder passwordEncoder; private final VraboteniService vraboteniService; public LoginController(UsersService usersService, PasswordEncoder passwordEncoder, VraboteniService vraboteniService) { this.usersService = usersService; this.passwordEncoder = passwordEncoder; this.vraboteniService = vraboteniService; } @GetMapping("/login") public String showLoginForm(@RequestParam(required = false) String hasError, @RequestParam(required = false) String error, Model model) { model.addAttribute("hasError", hasError); model.addAttribute("error", error); return "login_form.html"; } @PostMapping("/login") public String login(HttpServletRequest request) { try { Users users = this.usersService.login(request.getParameter("username"), request.getParameter("password")); request.getSession().setAttribute("user", users); if (users != null) return "redirect:/home"; else return "redirect:/login?hasError=true&error=BadCredentials"; } catch (InvalidArgumentException exception) { return "redirect:/login?hasError=true&error=" + exception.getMessage(); } } @GetMapping("/logout") public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "redirect:/home"; } }