|
| 1 | +package de.tum.in.www1.hephaestus.gitprovider.user; |
| 2 | + |
| 3 | +import de.tum.in.www1.hephaestus.SecurityUtils; |
| 4 | +import de.tum.in.www1.hephaestus.core.LoggingUtils; |
| 5 | +import de.tum.in.www1.hephaestus.gitprovider.common.GitProvider; |
| 6 | +import de.tum.in.www1.hephaestus.gitprovider.common.GitProviderRepository; |
| 7 | +import de.tum.in.www1.hephaestus.gitprovider.common.GitProviderType; |
| 8 | +import de.tum.in.www1.hephaestus.gitprovider.common.gitlab.GitLabProperties; |
| 9 | +import java.util.Optional; |
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | +import org.springframework.http.HttpStatus; |
| 13 | +import org.springframework.lang.Nullable; |
| 14 | +import org.springframework.security.core.Authentication; |
| 15 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 16 | +import org.springframework.security.oauth2.jwt.Jwt; |
| 17 | +import org.springframework.stereotype.Service; |
| 18 | +import org.springframework.transaction.annotation.Transactional; |
| 19 | +import org.springframework.web.server.ResponseStatusException; |
| 20 | + |
| 21 | +@Service |
| 22 | +public class AuthenticatedGitProviderUserService { |
| 23 | + |
| 24 | + private static final Logger log = LoggerFactory.getLogger(AuthenticatedGitProviderUserService.class); |
| 25 | + private static final String GITHUB_SERVER_URL = "https://github.com"; |
| 26 | + |
| 27 | + private final UserRepository userRepository; |
| 28 | + private final GitProviderRepository gitProviderRepository; |
| 29 | + private final GitLabProperties gitLabProperties; |
| 30 | + |
| 31 | + public AuthenticatedGitProviderUserService( |
| 32 | + UserRepository userRepository, |
| 33 | + GitProviderRepository gitProviderRepository, |
| 34 | + GitLabProperties gitLabProperties |
| 35 | + ) { |
| 36 | + this.userRepository = userRepository; |
| 37 | + this.gitProviderRepository = gitProviderRepository; |
| 38 | + this.gitLabProperties = gitLabProperties; |
| 39 | + } |
| 40 | + |
| 41 | + @Transactional |
| 42 | + public Optional<User> resolveOrProvisionCurrentUser(@Nullable String gitLabServerUrl) { |
| 43 | + var currentUser = userRepository.getCurrentUser(); |
| 44 | + if (currentUser.isPresent()) { |
| 45 | + return currentUser; |
| 46 | + } |
| 47 | + |
| 48 | + Optional<String> currentLogin = SecurityUtils.getCurrentUserLogin(); |
| 49 | + if (currentLogin.isEmpty()) { |
| 50 | + return Optional.empty(); |
| 51 | + } |
| 52 | + String login = currentLogin.orElseThrow(); |
| 53 | + |
| 54 | + Jwt jwt = getCurrentJwt(); |
| 55 | + if (jwt == null) { |
| 56 | + return Optional.empty(); |
| 57 | + } |
| 58 | + |
| 59 | + Long gitlabId = jwt.getClaim("gitlab_id"); |
| 60 | + if (gitlabId != null) { |
| 61 | + String resolvedUrl = resolveGitLabServerUrl(gitLabServerUrl); |
| 62 | + Long userId = upsertGitLabUser( |
| 63 | + gitlabId, |
| 64 | + login, |
| 65 | + login, |
| 66 | + "", |
| 67 | + resolvedUrl + "/" + login, |
| 68 | + resolvedUrl, |
| 69 | + User.Type.USER |
| 70 | + ); |
| 71 | + return userRepository.findById(userId); |
| 72 | + } |
| 73 | + |
| 74 | + Long githubId = jwt.getClaim("github_id"); |
| 75 | + if (githubId != null) { |
| 76 | + Long userId = upsertGitHubUser(githubId, login, login, "", GITHUB_SERVER_URL + "/" + login, User.Type.USER); |
| 77 | + return userRepository.findById(userId); |
| 78 | + } |
| 79 | + |
| 80 | + return Optional.empty(); |
| 81 | + } |
| 82 | + |
| 83 | + @Transactional |
| 84 | + public void ensureCurrentGitLabUserExists(@Nullable String gitLabServerUrl) { |
| 85 | + String login = SecurityUtils.getCurrentUserLoginOrThrow(); |
| 86 | + if (userRepository.findByLogin(login).isPresent()) { |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + Jwt jwt = getCurrentJwt(); |
| 91 | + if (jwt == null) { |
| 92 | + throw new IllegalStateException("No JWT found for authenticated user"); |
| 93 | + } |
| 94 | + |
| 95 | + Long gitlabId = jwt.getClaim("gitlab_id"); |
| 96 | + if (gitlabId != null) { |
| 97 | + String resolvedUrl = resolveGitLabServerUrl(gitLabServerUrl); |
| 98 | + upsertGitLabUser(gitlabId, login, login, "", resolvedUrl + "/" + login, resolvedUrl, User.Type.USER); |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + Long githubId = jwt.getClaim("github_id"); |
| 103 | + if (githubId != null) { |
| 104 | + throw new ResponseStatusException( |
| 105 | + HttpStatus.CONFLICT, |
| 106 | + "You need to link your GitLab account before creating a GitLab workspace. Go to Settings → Linked Accounts to connect your GitLab identity." |
| 107 | + ); |
| 108 | + } |
| 109 | + |
| 110 | + throw new ResponseStatusException( |
| 111 | + HttpStatus.CONFLICT, |
| 112 | + "No GitLab identity found. Please link your GitLab account in Settings → Linked Accounts." |
| 113 | + ); |
| 114 | + } |
| 115 | + |
| 116 | + @Nullable |
| 117 | + private Jwt getCurrentJwt() { |
| 118 | + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 119 | + if (auth == null || !(auth.getPrincipal() instanceof Jwt jwt)) { |
| 120 | + return null; |
| 121 | + } |
| 122 | + return jwt; |
| 123 | + } |
| 124 | + |
| 125 | + private String resolveGitLabServerUrl(@Nullable String configServerUrl) { |
| 126 | + if (configServerUrl != null && !configServerUrl.isBlank()) { |
| 127 | + String url = configServerUrl.trim(); |
| 128 | + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; |
| 129 | + } |
| 130 | + return gitLabProperties.defaultServerUrl(); |
| 131 | + } |
| 132 | + |
| 133 | + private Long upsertGitHubUser( |
| 134 | + Long nativeId, |
| 135 | + String login, |
| 136 | + String name, |
| 137 | + String avatarUrl, |
| 138 | + String webUrl, |
| 139 | + User.Type userType |
| 140 | + ) { |
| 141 | + GitProvider provider = gitProviderRepository |
| 142 | + .findByTypeAndServerUrl(GitProviderType.GITHUB, GITHUB_SERVER_URL) |
| 143 | + .orElseGet(() -> gitProviderRepository.save(new GitProvider(GitProviderType.GITHUB, GITHUB_SERVER_URL))); |
| 144 | + |
| 145 | + return upsertUser(nativeId, login, name, avatarUrl, webUrl, userType, provider); |
| 146 | + } |
| 147 | + |
| 148 | + private Long upsertGitLabUser( |
| 149 | + Long nativeId, |
| 150 | + String login, |
| 151 | + String name, |
| 152 | + String avatarUrl, |
| 153 | + String webUrl, |
| 154 | + String serverUrl, |
| 155 | + User.Type userType |
| 156 | + ) { |
| 157 | + String safeAvatar = avatarUrl != null ? (avatarUrl.startsWith("/") ? serverUrl + avatarUrl : avatarUrl) : ""; |
| 158 | + GitProvider provider = gitProviderRepository |
| 159 | + .findByTypeAndServerUrl(GitProviderType.GITLAB, serverUrl) |
| 160 | + .orElseGet(() -> { |
| 161 | + log.info("Creating GitProvider for self-hosted GitLab: serverUrl={}", serverUrl); |
| 162 | + return gitProviderRepository.save(new GitProvider(GitProviderType.GITLAB, serverUrl)); |
| 163 | + }); |
| 164 | + |
| 165 | + return upsertUser(nativeId, login, name, safeAvatar, webUrl, userType, provider); |
| 166 | + } |
| 167 | + |
| 168 | + private Long upsertUser( |
| 169 | + Long nativeId, |
| 170 | + String login, |
| 171 | + String name, |
| 172 | + String avatarUrl, |
| 173 | + String webUrl, |
| 174 | + User.Type userType, |
| 175 | + GitProvider provider |
| 176 | + ) { |
| 177 | + String safeName = name != null ? name : login; |
| 178 | + String safeAvatar = avatarUrl != null ? avatarUrl : ""; |
| 179 | + String safeWebUrl = webUrl != null ? webUrl : ""; |
| 180 | + Long providerId = provider.getId(); |
| 181 | + |
| 182 | + userRepository.acquireLoginLock(login, providerId); |
| 183 | + userRepository.freeLoginConflicts(login, nativeId, providerId); |
| 184 | + userRepository.upsertUser( |
| 185 | + nativeId, |
| 186 | + providerId, |
| 187 | + login, |
| 188 | + safeName, |
| 189 | + safeAvatar, |
| 190 | + safeWebUrl, |
| 191 | + userType.name(), |
| 192 | + null, |
| 193 | + null, |
| 194 | + null |
| 195 | + ); |
| 196 | + log.info( |
| 197 | + "Upserted authenticated git provider user: userLogin={}, nativeId={}, providerType={}, type={}", |
| 198 | + LoggingUtils.sanitizeForLog(login), |
| 199 | + nativeId, |
| 200 | + provider.getType(), |
| 201 | + userType |
| 202 | + ); |
| 203 | + return userRepository |
| 204 | + .findByLoginAndProviderId(login, providerId) |
| 205 | + .map(User::getId) |
| 206 | + .orElseThrow(() -> new IllegalStateException("User not found after upsert: login=" + login)); |
| 207 | + } |
| 208 | +} |
0 commit comments