-
Notifications
You must be signed in to change notification settings - Fork 6
Push notification and auth improvements #1049
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Isti01
merged 3 commits into
staging
from
feature/push-notification-and-auth-improvements
Jul 9, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
backend/src/main/kotlin/hu/bme/sch/cmsch/component/login/LoginRejectedException.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package hu.bme.sch.cmsch.component.login | ||
|
|
||
| import org.springframework.security.oauth2.core.OAuth2AuthenticationException | ||
| import org.springframework.security.oauth2.core.OAuth2Error | ||
|
|
||
| class LoginRejectedException(val userMessage: String) : | ||
| OAuth2AuthenticationException(OAuth2Error("login_rejected", userMessage, null), userMessage) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 0 additions & 49 deletions
49
...main/kotlin/hu/bme/sch/cmsch/component/pushnotification/FirebaseMessagingConfiguration.kt
This file was deleted.
Oops, something went wrong.
131 changes: 89 additions & 42 deletions
131
...nd/src/main/kotlin/hu/bme/sch/cmsch/component/pushnotification/PushNotificationService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,108 +1,155 @@ | ||
| package hu.bme.sch.cmsch.component.pushnotification | ||
|
|
||
| import com.google.auth.oauth2.GoogleCredentials | ||
| import hu.bme.sch.cmsch.dto.CmschNotification | ||
| import hu.bme.sch.cmsch.model.RoleType | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.awaitAll | ||
| import kotlinx.coroutines.coroutineScope | ||
| import kotlinx.coroutines.runBlocking | ||
| import hu.bme.sch.cmsch.util.transaction | ||
| import org.slf4j.LoggerFactory | ||
| import org.springframework.beans.factory.annotation.Value | ||
| import org.springframework.boot.autoconfigure.condition.ConditionalOnBean | ||
| import org.springframework.stereotype.Service | ||
| import org.springframework.transaction.annotation.Isolation | ||
| import org.springframework.transaction.PlatformTransactionManager | ||
| import org.springframework.transaction.annotation.Transactional | ||
| import org.springframework.web.reactive.function.client.WebClient | ||
| import org.springframework.web.reactive.function.client.awaitBodilessEntity | ||
| import org.springframework.web.reactive.function.client.WebClientResponseException | ||
| import reactor.core.publisher.Flux | ||
| import reactor.core.publisher.Mono | ||
| import reactor.util.retry.Retry | ||
| import tools.jackson.databind.ObjectMapper | ||
| import java.time.Duration | ||
| import java.util.concurrent.ConcurrentLinkedQueue | ||
|
|
||
| private const val MAX_CONCURRENT_SENDS = 100 | ||
| private const val MAX_RETRIES = 4L | ||
| private val RETRY_INITIAL_BACKOFF = Duration.ofMillis(500) | ||
| private val RETRY_MAX_BACKOFF = Duration.ofSeconds(5) | ||
|
|
||
| @Service | ||
| @ConditionalOnBean(PushNotificationComponent::class) | ||
| class PushNotificationService( | ||
| private val credentials: GoogleCredentials, | ||
| private val projectId: String, | ||
| private val fcmWebClient: WebClient, | ||
| @Value($$"${hu.bme.sch.cmsch.google.service-account-key}") accountKey: String, | ||
| webClientBuilder: WebClient.Builder, | ||
| objectMapper: ObjectMapper, | ||
| private val transactionManager: PlatformTransactionManager, | ||
| private val messagingTokenRepository: MessagingTokenRepository, | ||
| ) { | ||
| private val log = LoggerFactory.getLogger(javaClass) | ||
| private val fcmWebClient = webClientBuilder.baseUrl("https://fcm.googleapis.com/v1/projects/").build() | ||
| private val credentials = PushNotificationServiceCredentials(accountKey, objectMapper) | ||
|
|
||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| fun sendToUser(userId: Int, notification: CmschNotification): Int { | ||
| log.info("Sending notification {} to user: {}", notification, userId) | ||
| val tokens = messagingTokenRepository.findAllTokensByUserId(userId) | ||
| val tokens = transactionManager.transaction(readOnly = true) { | ||
| messagingTokenRepository.findAllTokensByUserId(userId) | ||
| } | ||
| return sendNotifications(tokens, notification) | ||
| } | ||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| fun sendToGroup(groupId: Int, notification: CmschNotification): Int { | ||
| log.info("Sending notification {} to group: {}", notification, groupId) | ||
| val tokens = messagingTokenRepository.findAllTokensByGroupId(groupId) | ||
| val tokens = transactionManager.transaction(readOnly = true) { | ||
| messagingTokenRepository.findAllTokensByGroupId(groupId) | ||
| } | ||
| return sendNotifications(tokens, notification) | ||
| } | ||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| fun sendToAllUsers(notification: CmschNotification): Int { | ||
| log.info("Sending notification {} to all users", notification) | ||
| val tokens = messagingTokenRepository.findAllTokens() | ||
| val tokens = transactionManager.transaction(readOnly = true) { | ||
| messagingTokenRepository.findAllTokens() | ||
| } | ||
| return sendNotifications(tokens, notification) | ||
| } | ||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| fun sendToRole(role: RoleType, notification: CmschNotification): Int { | ||
| log.info("Sending notification {} to users with role {}", notification, role.displayName) | ||
| val tokens = messagingTokenRepository.findAllTokensByRole(role) | ||
| val tokens = transactionManager.transaction(readOnly = true) { | ||
| messagingTokenRepository.findAllTokensByRole(role) | ||
| } | ||
| return sendNotifications(tokens, notification) | ||
| } | ||
|
|
||
| private fun getAccessToken(): String { | ||
| credentials.refreshIfExpired() | ||
| return credentials.accessToken.tokenValue | ||
| return credentials.getAccessToken() | ||
| } | ||
|
|
||
| private fun sendNotifications(tokens: List<String>, notification: CmschNotification): Int = runBlocking { | ||
| if (tokens.isEmpty()) return@runBlocking 0 | ||
| private fun sendNotifications(tokens: List<String>, notification: CmschNotification): Int { | ||
| if (tokens.isEmpty()) return 0 | ||
|
|
||
| val accessToken = runCatching { getAccessToken() }.getOrElse { | ||
| log.error("Failed to get FCM access token", it) | ||
| return@runBlocking 0 | ||
| return 0 | ||
| } | ||
|
|
||
| val results = coroutineScope { | ||
| tokens.chunked(100).flatMap { chunk -> | ||
| chunk.map { token -> | ||
| async { | ||
| runCatching { | ||
| fcmWebClient.post() | ||
| .uri("{projectId}/messages:send", projectId) | ||
| .header("Authorization", "Bearer $accessToken") | ||
| .bodyValue(notification.toFcmRequest(token)) | ||
| .retrieve() | ||
| .awaitBodilessEntity() | ||
| true | ||
| }.getOrElse { e -> | ||
| val staleTokens = ConcurrentLinkedQueue<String>() | ||
|
|
||
| val results = Flux.fromIterable(tokens) | ||
| .flatMap({ token -> | ||
| fcmWebClient.post() | ||
| .uri("{projectId}/messages:send", credentials.projectId) | ||
| .header("Authorization", "Bearer $accessToken") | ||
| .bodyValue(notification.toFcmRequest(token)) | ||
| .retrieve() | ||
| .toBodilessEntity() | ||
| .retryWhen( | ||
| Retry.backoff(MAX_RETRIES, RETRY_INITIAL_BACKOFF) | ||
| .maxBackoff(RETRY_MAX_BACKOFF) | ||
| .filter(::isRetryable) | ||
| .doBeforeRetry { signal -> | ||
| log.error( | ||
| "Retryable error sending to token {} (attempt {}), retrying", | ||
| token, signal.totalRetries() + 1, signal.failure() | ||
| ) | ||
| } | ||
| ) | ||
| .thenReturn(SendResult.SUCCESS) | ||
| .onErrorResume { e -> | ||
| if (e is WebClientResponseException.NotFound) { | ||
| staleTokens.add(token) | ||
| Mono.just(SendResult.STALE) | ||
| } else { | ||
| log.error("Failed to send notification to token {}", token, e) | ||
| false | ||
| Mono.just(SendResult.FAILURE) | ||
| } | ||
| } | ||
| }.awaitAll() | ||
| }, MAX_CONCURRENT_SENDS) | ||
| .collectList() | ||
| .block() ?: emptyList() | ||
|
|
||
| if (staleTokens.isNotEmpty()) { | ||
| val deleted = transactionManager.transaction(readOnly = false) { | ||
| messagingTokenRepository.deleteByTokenIn(staleTokens.toList()) | ||
| } | ||
| log.info("Deleted {} stale messaging tokens", deleted) | ||
| } | ||
|
|
||
| val successCount = results.count { it } | ||
| val successCount = results.count { it == SendResult.SUCCESS } | ||
| log.info("Successfully sent notification to {} out of {} devices", successCount, tokens.size) | ||
| successCount | ||
| return successCount | ||
| } | ||
|
|
||
| private fun isRetryable(e: Throwable): Boolean = when (e) { | ||
| is WebClientResponseException -> e.statusCode.is5xxServerError || e.statusCode.value() == 429 | ||
| else -> true | ||
| } | ||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| @Transactional(readOnly = false) | ||
| fun addToken(userId: Int, token: String) { | ||
| if (messagingTokenRepository.existsByUserIdAndToken(userId, token)) return | ||
|
|
||
| log.debug("Inserting messaging token for user: {}, token: {}", userId, token) | ||
| messagingTokenRepository.save(MessagingTokenEntity(userId = userId, token = token)) | ||
| } | ||
|
|
||
| @Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE) | ||
| @Transactional(readOnly = false) | ||
| fun deleteToken(userId: Int, token: String) { | ||
| log.debug("Deleting messaging token for user: {}, token: {}", userId, token) | ||
| messagingTokenRepository.deleteByUserIdAndToken(userId, token) | ||
| } | ||
| } | ||
|
|
||
| private enum class SendResult { | ||
| SUCCESS, | ||
| STALE, | ||
| FAILURE, | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.