refactor(security): remove unused GitHubService and comments
Some checks failed
CI / Get Changed Files (pull_request) Successful in 8s
CI / oxlint (pull_request) Successful in 24s
CI / Docker frontend validation (pull_request) Successful in 26s
CI / eslint (pull_request) Successful in 31s
CI / prettier (pull_request) Failing after 32s
CI / Checkstyle Main (pull_request) Failing after 1m2s
CI / test-build (pull_request) Successful in 59s
CI / Docker backend validation (pull_request) Successful in 1m14s

This commit is contained in:
Constantin Simonis 2025-05-21 10:56:56 +02:00
commit 6f6bbe6d8b
No known key found for this signature in database
GPG key ID: 3878FF77C24AF4D2
7 changed files with 2 additions and 35 deletions

View file

@ -23,9 +23,6 @@ public class AuthController {
@Autowired
private AuthService authService;
@Autowired
private GitHubService githubService;
@PostMapping("/login")
public ResponseEntity<AuthResponseDto> authenticateUser(@Valid @RequestBody LoginRequestDto loginRequest) throws EmailNotVerifiedException {
AuthResponseDto response = authService.login(loginRequest);

View file

@ -23,7 +23,6 @@ public class CorsFilter implements Filter {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
// Allow requests from the frontend
response.setHeader("Access-Control-Allow-Origin", frontendHost);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");

View file

@ -45,22 +45,18 @@ public class GitHubService {
public AuthResponseDto processGithubCode(String code) {
try {
// Exchange code for access token
RestTemplate restTemplate = new RestTemplate();
// Create request body for token endpoint
Map<String, String> requestBody = new HashMap<>();
requestBody.put("client_id", clientId);
requestBody.put("client_secret", clientSecret);
requestBody.put("code", code);
// Set headers
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
// Get access token
ResponseEntity<Map> response = restTemplate.exchange(
"https://github.com/login/oauth/access_token",
HttpMethod.POST,
@ -70,7 +66,6 @@ public class GitHubService {
Map<String, Object> responseBody = response.getBody();
// Check if there's an error in the response
if (responseBody.containsKey("error")) {
String error = (String) responseBody.get("error");
String errorDescription = (String) responseBody.get("error_description");
@ -84,7 +79,6 @@ public class GitHubService {
throw new RuntimeException("Failed to receive access token from GitHub");
}
// Get user info
HttpHeaders userInfoHeaders = new HttpHeaders();
userInfoHeaders.set("Authorization", "Bearer " + accessToken);
@ -99,7 +93,6 @@ public class GitHubService {
Map<String, Object> userAttributes = userResponse.getBody();
// Get user emails
HttpHeaders emailsHeaders = new HttpHeaders();
emailsHeaders.set("Authorization", "Bearer " + accessToken);
@ -115,7 +108,6 @@ public class GitHubService {
List<Map<String, Object>> emails = emailsResponse.getBody();
String email = null;
// Find primary email
for (Map<String, Object> emailInfo : emails) {
Boolean primary = (Boolean) emailInfo.get("primary");
if (primary != null && primary) {
@ -124,24 +116,19 @@ public class GitHubService {
}
}
// If no primary email, just use the first one
if (email == null && !emails.isEmpty()) {
email = (String) emails.get(0).get("email");
}
// Process user data
String githubId = userAttributes.get("id").toString();
String username = (String) userAttributes.get("login");
// Check if user exists by provider ID
Optional<UserEntity> userOptional = userRepository.findByProviderId(githubId);
UserEntity user;
if (userOptional.isPresent()) {
// Update existing user
user = userOptional.get();
} else {
// Check if email exists
userOptional = userRepository.findByEmail(email);
if (userOptional.isPresent()) {
@ -149,7 +136,6 @@ public class GitHubService {
user.setProvider(AuthProvider.GITHUB);
user.setProviderId(githubId);
} else {
// Create new user
user = new UserEntity();
user.setEmail(email);
user.setUsername(username);
@ -168,7 +154,6 @@ public class GitHubService {
Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getEmail(), randomPassword));
// Generate JWT token
String token = jwtUtils.generateToken(authentication);
return new AuthResponseDto(token);

View file

@ -32,9 +32,6 @@ public class SecurityConfig {
@Value("${app.frontend-host}")
private String frontendHost;
@Value("${app.oauth2.authorizedRedirectUris}")
private String authorizedRedirectUri;
@Autowired
private UserDetailsService userDetailsService;
@ -73,8 +70,6 @@ public class SecurityConfig {
.requestMatchers(org.springframework.http.HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated();
})
// Disable Spring's built-in OAuth2 login since we're implementing a custom flow
// We're using our own GitHubController for OAuth2 login
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

View file

@ -45,7 +45,6 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
String registrationId = oAuth2UserRequest.getClientRegistration().getRegistrationId();
OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, oAuth2User.getAttributes());
// For GitHub, the email might not be directly available in attributes
String email = oAuth2UserInfo.getEmail();
if (StringUtils.isEmpty(email)) {
email = oAuth2UserInfo.getName() + "@github.user";
@ -79,7 +78,6 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
username = "github_" + oAuth2UserInfo.getId();
}
// Check if username already exists and append a suffix if needed
if (userRepository.findByUsername(username).isPresent()) {
username = username + "_" + UUID.randomUUID().toString().substring(0, 8);
}
@ -90,11 +88,10 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
user.setEmail(email);
user.setEmailVerified(true);
// Generate a random password for OAuth users (they won't use it)
String randomPassword = UUID.randomUUID().toString();
user.setPassword(oauth2PasswordEncoder.encode(randomPassword));
user.setBalance(new BigDecimal("1000.00")); // Starting balance
user.setBalance(new BigDecimal("100.00")); // Starting balance
return userRepository.save(user);
}

View file

@ -1,8 +1,6 @@
package de.szut.casino.security.oauth2;
import de.szut.casino.security.jwt.JwtUtils;
import de.szut.casino.user.UserRepository;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
@ -26,12 +24,9 @@ public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationS
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserRepository userRepository;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
throws IOException {
String targetUrl = determineTargetUrl(authentication);
logger.info("OAuth2 Authentication successful, redirecting to: {}", targetUrl);

View file

@ -58,7 +58,6 @@ public class UserPrincipal implements OAuth2User, UserDetails {
@Override
public String getUsername() {
// We're using email as the username for authentication
return email;
}