Add the Auth controller to login and get the user token.
continuous-integration/drone/push Build is passing Details

main
KKlochko 1 year ago
parent c6ff965796
commit adfcf34176

@ -0,0 +1,54 @@
package space.kklochko.spring_rest_example.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import space.kklochko.spring_rest_example.db.repositories.TokenRepository;
import space.kklochko.spring_rest_example.db.repositories.UserRepository;
import space.kklochko.spring_rest_example.models.Token;
import space.kklochko.spring_rest_example.models.User;
import space.kklochko.spring_rest_example.models.factories.TokenFactory;
import space.kklochko.spring_rest_example.security.hashes.Sha256Hash;
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private TokenRepository tokenRepository;
@Autowired
private TokenFactory tokenFactory;
@PostMapping("/login")
public ResponseEntity<String> authenticateUser(@RequestBody User user){
if(user.getUsername() == null || user.getUsername().isEmpty())
return ResponseEntity.status(500).body("Failed to login, because no username!!!");
if(user.getPassword() == null || user.getPassword().isEmpty())
return ResponseEntity.status(500).body("Failed to login, because no password!!!");
User expected = userRepository.read(user.getUsername());
if(expected == null)
return ResponseEntity.status(500).body("Failed to login, because the user does not exist!!! Please, check your username!!!");
String hashedPassword = (new Sha256Hash()).hashOf(user.getPassword());
if(!expected.getPassword().equals(hashedPassword))
return ResponseEntity.status(500).body("Failed to login, because incorrect password!!! Please, check your password!!!");
Token token = tokenFactory.create(expected.getUsername(), expected.getRole());
tokenRepository.create(token);
return new ResponseEntity<>(String.format("token: %s", token.getToken()), HttpStatus.OK);
}
}
Loading…
Cancel
Save