ClaptrapBot/src/main/java/net/Broken/Api/Controllers/AuthController.java

41 lines
1.5 KiB
Java
Raw Normal View History

2022-05-19 01:08:47 +02:00
package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Login;
2022-05-22 18:08:58 +02:00
import net.Broken.Api.Security.Data.JwtResponse;
2022-05-21 01:14:50 +02:00
import net.Broken.Api.Security.Services.JwtService;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository;
2022-05-19 01:08:47 +02:00
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
2022-05-21 01:14:50 +02:00
import org.springframework.validation.annotation.Validated;
2022-05-19 01:08:47 +02:00
import org.springframework.web.bind.annotation.*;
@RestController
2022-05-22 18:08:58 +02:00
@RequestMapping("/api/v2/auth")
2022-05-21 01:14:50 +02:00
@CrossOrigin(origins = "*", maxAge = 3600)
2022-05-19 01:08:47 +02:00
public class AuthController {
private final AuthenticationManager authenticationManager;
2022-05-21 01:14:50 +02:00
private final JwtService jwtService;
public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, JwtService jwtService) {
2022-05-19 01:08:47 +02:00
this.authenticationManager = authenticationManager;
2022-05-21 01:14:50 +02:00
this.jwtService = jwtService;
2022-05-19 01:08:47 +02:00
}
2022-05-22 18:08:58 +02:00
@PostMapping("/discord")
public JwtResponse loginDiscord(@Validated @RequestBody Login login) {
2022-05-19 01:08:47 +02:00
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(login.redirectUri(), login.code())
);
2022-05-22 18:08:58 +02:00
UserEntity user = (UserEntity) authentication.getPrincipal();
2022-05-19 01:08:47 +02:00
2022-05-22 18:08:58 +02:00
String jwt = jwtService.buildJwt(user);
2022-05-21 01:14:50 +02:00
2022-05-22 18:08:58 +02:00
return new JwtResponse(jwt);
2022-05-21 01:14:50 +02:00
}
2022-05-19 01:08:47 +02:00
}