source: src/main/java/com/example/web/LoginController.java@ a51a591

Last change on this file since a51a591 was a51a591, checked in by colovik <j.colovik@…>, 14 months ago

final

  • Property mode set to 100644
File size: 2.3 KB
Line 
1package com.example.web;
2
3import com.example.exceptions.InvalidUserCredentialsException;
4import com.example.exceptions.InvalidUsernameOrPasswordException;
5import com.example.model.User;
6import com.example.service.AuthService;
7import com.example.service.UserService;
8import org.springframework.stereotype.Controller;
9import org.springframework.ui.Model;
10import org.springframework.web.bind.annotation.GetMapping;
11import org.springframework.web.bind.annotation.PostMapping;
12import org.springframework.web.bind.annotation.RequestParam;
13
14import javax.servlet.http.HttpServletRequest;
15
16@Controller
17public 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}
Note: See TracBrowser for help on using the repository browser.