1 | package com.example.web;
|
---|
2 |
|
---|
3 | import com.example.exceptions.InvalidUserCredentialsException;
|
---|
4 | import com.example.exceptions.InvalidUsernameOrPasswordException;
|
---|
5 | import com.example.model.User;
|
---|
6 | import com.example.service.AuthService;
|
---|
7 | import com.example.service.UserService;
|
---|
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 |
|
---|
19 | private final AuthService authService;
|
---|
20 | private final UserService userService;
|
---|
21 |
|
---|
22 | public LoginController(AuthService authService, UserService userService) {
|
---|
23 | this.authService = authService;
|
---|
24 | this.userService = userService;
|
---|
25 | }
|
---|
26 |
|
---|
27 | @GetMapping("/login")
|
---|
28 | public String getLoginPage() {
|
---|
29 | return "login";
|
---|
30 | }
|
---|
31 |
|
---|
32 | @PostMapping("/login")
|
---|
33 | public String handleLogin(@RequestParam String username,
|
---|
34 | @RequestParam String password,
|
---|
35 | HttpServletRequest request,
|
---|
36 | Model model) {
|
---|
37 | // HttpServletResponse resp) throws IOException {
|
---|
38 | User user = null;
|
---|
39 | try {
|
---|
40 | user = authService.login(username, password);
|
---|
41 | request.getSession().setAttribute("user", user);
|
---|
42 | request.getSession().setAttribute("username",username);
|
---|
43 | request.getSession().setAttribute("role",
|
---|
44 | userService.findByUsername(username).get().getRole().toString());
|
---|
45 | System.out.println(request.getSession().getAttribute("role").toString());
|
---|
46 | return "redirect:/home";
|
---|
47 | } catch (InvalidUserCredentialsException exception) {
|
---|
48 | model.addAttribute("hasError", true);
|
---|
49 | model.addAttribute("error", exception.getMessage());
|
---|
50 | return "login";
|
---|
51 | } catch (InvalidUsernameOrPasswordException exception) {
|
---|
52 | model.addAttribute("hasError", true);
|
---|
53 | model.addAttribute("error", exception.getMessage());
|
---|
54 | return "login";
|
---|
55 | }
|
---|
56 | }
|
---|
57 |
|
---|
58 | @GetMapping("/logout")
|
---|
59 | public String getLogout(HttpServletRequest request) {
|
---|
60 | request.getSession().invalidate();
|
---|
61 | return "redirect:/login";
|
---|
62 | }
|
---|
63 | }
|
---|