source: src/main/java/finki/it/terapijamkbackend/spring/controllers/AuthController.java

Last change on this file was 43c9090, checked in by macagaso <gasoskamarija@…>, 5 weeks ago

Updated version

  • Property mode set to 100644
File size: 2.7 KB
Line 
1package finki.it.terapijamkbackend.spring.controllers;
2
3import finki.it.terapijamkbackend.spring.dto.LoginResponse;
4import finki.it.terapijamkbackend.spring.entities.User;
5import finki.it.terapijamkbackend.spring.services.UserService;
6import jakarta.servlet.http.Cookie;
7import jakarta.servlet.http.HttpServletResponse;
8import org.springframework.beans.factory.annotation.Autowired;
9import org.springframework.http.HttpStatus;
10import org.springframework.http.ResponseEntity;
11import org.springframework.web.bind.annotation.PostMapping;
12import org.springframework.web.bind.annotation.RequestBody;
13import org.springframework.web.bind.annotation.RequestMapping;
14import org.springframework.web.bind.annotation.RestController;
15
16import java.util.Map;
17
18import static finki.it.terapijamkbackend.spring.entities.UserRole.*;
19
20@RestController
21@RequestMapping("/api/auth")
22public class AuthController {
23
24 @Autowired
25 private UserService userService;
26
27 @PostMapping(path = "/login")
28 public ResponseEntity<LoginResponse> loginUser(@RequestBody Map<String, String> userData, HttpServletResponse response) {
29 LoginResponse loginResponse = new LoginResponse(false, "Invalid credentials", USER, userData.get("name"), userData.get("surname"));
30
31 if(userService.isUserBlocked(userData.get("username"))){
32 loginResponse=new LoginResponse(false,"Blocked account",USER,userData.get("name"), userData.get("surname"));
33 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(loginResponse);
34 }
35 if (!userService.doesExist(userData.get("username"), userData.get("password"))) {
36 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(loginResponse);
37 }
38
39 try {
40 User temp = userService.getUserByUsername(userData.get("username"));
41 if(temp.getUserRole()== ADMIN){
42 loginResponse = new LoginResponse(true, "Login successful", ADMIN, temp.getName(), temp.getSurname());
43 }
44 else{
45 loginResponse = new LoginResponse(true, "Login successful", USER, temp.getName(), temp.getSurname());
46 }
47
48 Cookie usernameCookie = new Cookie("username", temp.getUsername());
49 usernameCookie.setPath("/");
50 usernameCookie.setMaxAge(600);
51 response.addCookie(usernameCookie);
52
53 Cookie roleCookie = new Cookie("role", temp.getUserRole().toString());
54 roleCookie.setPath("/");
55 roleCookie.setMaxAge(600);
56 response.addCookie(roleCookie);
57
58 return ResponseEntity.ok(loginResponse);
59 } catch (Exception e) {
60 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(loginResponse);
61 }
62 }
63}
Note: See TracBrowser for help on using the repository browser.