[850b344] | 1 | package com.project.beautycenter.web;
|
---|
| 2 |
|
---|
| 3 | import com.project.beautycenter.model.Users;
|
---|
| 4 | import com.project.beautycenter.model.exceptions.InvalidArgumentException;
|
---|
| 5 | import com.project.beautycenter.service.UsersService;
|
---|
| 6 | import com.project.beautycenter.service.VraboteniService;
|
---|
| 7 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
| 8 | import org.springframework.stereotype.Controller;
|
---|
| 9 | import org.springframework.ui.Model;
|
---|
| 10 | import org.springframework.web.bind.annotation.GetMapping;
|
---|
| 11 | import org.springframework.web.bind.annotation.PostMapping;
|
---|
| 12 | import org.springframework.web.bind.annotation.RequestParam;
|
---|
| 13 |
|
---|
| 14 | import javax.servlet.http.HttpServletRequest;
|
---|
| 15 |
|
---|
| 16 | @Controller
|
---|
| 17 | public class LoginController {
|
---|
| 18 | private final UsersService usersService;
|
---|
| 19 | private final PasswordEncoder passwordEncoder;
|
---|
| 20 | private final VraboteniService vraboteniService;
|
---|
| 21 |
|
---|
| 22 | public LoginController(UsersService usersService, PasswordEncoder passwordEncoder, VraboteniService vraboteniService) {
|
---|
| 23 | this.usersService = usersService;
|
---|
| 24 | this.passwordEncoder = passwordEncoder;
|
---|
| 25 | this.vraboteniService = vraboteniService;
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | @GetMapping("/login")
|
---|
| 29 | public String showLoginForm(@RequestParam(required = false) String hasError,
|
---|
| 30 | @RequestParam(required = false) String error, Model model) {
|
---|
| 31 | model.addAttribute("hasError", hasError);
|
---|
| 32 | model.addAttribute("error", error);
|
---|
| 33 | return "login_form.html";
|
---|
| 34 | }
|
---|
| 35 |
|
---|
| 36 | @PostMapping("/login")
|
---|
| 37 | public String login(HttpServletRequest request) {
|
---|
| 38 |
|
---|
| 39 | try {
|
---|
| 40 | Users users = this.usersService.login(request.getParameter("username"),
|
---|
| 41 | request.getParameter("password"));
|
---|
| 42 | request.getSession().setAttribute("user", users);
|
---|
| 43 | if (users != null)
|
---|
| 44 | return "redirect:/home";
|
---|
| 45 | else return "redirect:/login?hasError=true&error=BadCredentials";
|
---|
| 46 | } catch (InvalidArgumentException exception) {
|
---|
| 47 | return "redirect:/login?hasError=true&error=" + exception.getMessage();
|
---|
| 48 |
|
---|
| 49 | }
|
---|
| 50 | }
|
---|
| 51 |
|
---|
| 52 |
|
---|
| 53 | @GetMapping("/logout")
|
---|
| 54 | public String logout(HttpServletRequest request) {
|
---|
| 55 | request.getSession().invalidate();
|
---|
| 56 | return "redirect:/home";
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | }
|
---|
| 60 |
|
---|
| 61 |
|
---|
| 62 |
|
---|