From b050a74b75c41b1bacdebc491285f354066bcbcc Mon Sep 17 00:00:00 2001 From: Bartha Maxime <231026@umons.ac.be> Date: Wed, 6 Mar 2024 17:35:49 +0100 Subject: [PATCH] added LoginController Post(/login) --- .../Clyde/EndPoints/LoginController.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 backend/src/main/java/ovh/herisson/Clyde/EndPoints/LoginController.java diff --git a/backend/src/main/java/ovh/herisson/Clyde/EndPoints/LoginController.java b/backend/src/main/java/ovh/herisson/Clyde/EndPoints/LoginController.java new file mode 100644 index 0000000..863daa9 --- /dev/null +++ b/backend/src/main/java/ovh/herisson/Clyde/EndPoints/LoginController.java @@ -0,0 +1,45 @@ +package ovh.herisson.Clyde.EndPoints; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import ovh.herisson.Clyde.Services.TokenService; +import ovh.herisson.Clyde.Services.UserService; +import ovh.herisson.Clyde.Tables.User; + +import java.util.Date; + +@RestController +@CrossOrigin(origins = "http://localhost:5173") +public class LoginController { + private final UserService userService; + private final TokenService tokenService; + + public LoginController(UserService userService, TokenService tokenService){ + this.userService =userService; + this.tokenService = tokenService; + } + @PostMapping("/login") + public ResponseEntity login(@RequestParam String identifier, String password, Date expirationDate){ + + User user = userService.getUser(identifier); + if (user == null){ + return new ResponseEntity("wrong ID or Email", HttpStatus.BAD_REQUEST); + } + + if (!userService.checkPassword(user,password)){ + return new ResponseEntity("wrong Password",HttpStatus.BAD_REQUEST); + } + + String token = tokenService.generateNewToken(); + + + tokenService.saveToken(token,user,expirationDate); + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("Set-Cookie",String.format("session_token=%s",token)); + return ResponseEntity.ok().headers(responseHeaders).build(); + } +} + +