Advertisement
joaopaulofcc

Untitled

Nov 16th, 2023
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. package com.example.springjwt.controllers;
  2.  
  3. import com.example.springjwt.auth.JwtUtil;
  4. import com.example.springjwt.model.User;
  5. import com.example.springjwt.model.request.LoginReq;
  6. import com.example.springjwt.model.response.ErrorRes;
  7. import com.example.springjwt.model.response.LoginRes;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.security.authentication.AuthenticationManager;
  11. import org.springframework.security.authentication.BadCredentialsException;
  12. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  13. import org.springframework.security.core.Authentication;
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.web.bind.annotation.*;
  16.  
  17. @Controller
  18. @RequestMapping("/rest/auth")
  19. public class AuthController {
  20.  
  21. private final AuthenticationManager authenticationManager;
  22.  
  23.  
  24. private JwtUtil jwtUtil;
  25. public AuthController(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
  26. this.authenticationManager = authenticationManager;
  27. this.jwtUtil = jwtUtil;
  28.  
  29. }
  30.  
  31. @ResponseBody
  32. @RequestMapping(value = "/login",method = RequestMethod.POST)
  33. public ResponseEntity login(@RequestBody LoginReq loginReq) {
  34.  
  35. try {
  36. Authentication authentication =
  37. authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginReq.getEmail(), loginReq.getPassword()));
  38. String email = authentication.getName();
  39. User user = new User(email,"");
  40. String token = jwtUtil.createToken(user);
  41. LoginRes loginRes = new LoginRes(email,token);
  42.  
  43. return ResponseEntity.ok(loginRes);
  44.  
  45. }catch (BadCredentialsException e){
  46. ErrorRes errorResponse = new ErrorRes(HttpStatus.BAD_REQUEST,"Invalid username or password");
  47. return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
  48. }catch (Exception e){
  49. ErrorRes errorResponse = new ErrorRes(HttpStatus.BAD_REQUEST, e.getMessage());
  50. return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement