Skip to content

Commit 7eddf52

Browse files
authored
Use our lock to make token manager thread safe (#154)
1 parent 8444d65 commit 7eddf52

File tree

1 file changed

+29
-26
lines changed

1 file changed

+29
-26
lines changed

Sources/APNSwift/APNSAuthenticationTokenManager.swift

+29-26
Original file line numberDiff line numberDiff line change
@@ -75,32 +75,35 @@ final class APNSAuthenticationTokenManager {
7575
/// If there is a previously generated token that is still valid it will be returned, otherwise a fresh token will be generated.
7676
var nextValidToken: String {
7777
get throws {
78-
// First we check if there is a previously generated token
79-
// and if that token is still valid.
80-
if let lastGeneratedToken = lastGeneratedToken,
81-
self.currentTimeFactory().asSecondsSince1970 - lastGeneratedToken.issuedAt.asSecondsSince1970 < Self
82-
.expirationDurationInSeconds
83-
{
84-
// The last generated token is still valid
85-
86-
logger.debug(
87-
"APNSAuthenticationTokenManager reusing previously generated token",
88-
metadata: [
89-
LoggingKeys.authenticationTokenIssuedAt: "\(lastGeneratedToken.issuedAt)",
90-
LoggingKeys.authenticationTokenIssuer: "\(teamIdentifier)",
91-
LoggingKeys.authenticationTokenKeyID: "\(keyIdentifier)",
92-
]
93-
)
94-
return lastGeneratedToken.token
95-
} else {
96-
let token = try generateNewToken(
97-
privateKey: privateKey,
98-
teamIdentifier: teamIdentifier,
99-
keyIdentifier: keyIdentifier
100-
)
101-
lastGeneratedToken = token
102-
103-
return token.token
78+
try lock.withLock {
79+
80+
// First we check if there is a previously generated token
81+
// and if that token is still valid.
82+
if let lastGeneratedToken = lastGeneratedToken,
83+
self.currentTimeFactory().asSecondsSince1970 - lastGeneratedToken.issuedAt.asSecondsSince1970 < Self
84+
.expirationDurationInSeconds
85+
{
86+
// The last generated token is still valid
87+
88+
logger.debug(
89+
"APNSAuthenticationTokenManager reusing previously generated token",
90+
metadata: [
91+
LoggingKeys.authenticationTokenIssuedAt: "\(lastGeneratedToken.issuedAt)",
92+
LoggingKeys.authenticationTokenIssuer: "\(teamIdentifier)",
93+
LoggingKeys.authenticationTokenKeyID: "\(keyIdentifier)",
94+
]
95+
)
96+
return lastGeneratedToken.token
97+
} else {
98+
let token = try generateNewToken(
99+
privateKey: privateKey,
100+
teamIdentifier: teamIdentifier,
101+
keyIdentifier: keyIdentifier
102+
)
103+
lastGeneratedToken = token
104+
105+
return token.token
106+
}
104107
}
105108
}
106109
}

0 commit comments

Comments
 (0)