@@ -4,7 +4,6 @@ import com.google.api.client.auth.oauth2.AuthorizationCodeFlow
4
4
import com.google.api.client.auth.oauth2.BearerToken
5
5
import com.google.api.client.auth.oauth2.ClientParametersAuthentication
6
6
import com.google.api.client.auth.oauth2.Credential
7
- import com.google.api.client.auth.oauth2.StoredCredential
8
7
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
9
8
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
10
9
import com.google.api.client.http.GenericUrl
@@ -30,9 +29,20 @@ actual object ModelixAuthClient {
30
29
private var DATA_STORE_FACTORY : DataStoreFactory = MemoryDataStoreFactory ()
31
30
private val HTTP_TRANSPORT : HttpTransport = NetHttpTransport ()
32
31
private val JSON_FACTORY : JsonFactory = GsonFactory ()
32
+ private val userId = " modelix-user"
33
+ private var lastCredentials: Credential ? = null
33
34
34
- fun getTokens (): StoredCredential ? {
35
- return StoredCredential .getDefaultDataStore(DATA_STORE_FACTORY ).get(" user" )
35
+ fun getTokens (): Credential ? {
36
+ return lastCredentials?.refreshIfExpired()?.takeIf { ! it.isExpired() }
37
+ }
38
+
39
+ private fun Credential.isExpired () = (expiresInSeconds ? : 0 ) < 60
40
+
41
+ private fun Credential.refreshIfExpired (): Credential {
42
+ if (isExpired()) {
43
+ refreshToken()
44
+ }
45
+ return this
36
46
}
37
47
38
48
suspend fun authorize (modelixServerUrl : String ): Credential {
@@ -67,6 +77,10 @@ actual object ModelixAuthClient {
67
77
.enablePKCE()
68
78
.setDataStoreFactory(DATA_STORE_FACTORY )
69
79
.build()
80
+
81
+ val existingTokens = flow.loadCredential(userId)?.refreshIfExpired()
82
+ if (existingTokens?.isExpired() == false ) return @withContext existingTokens
83
+
70
84
val receiver: LocalServerReceiver = LocalServerReceiver .Builder ().setHost(" 127.0.0.1" ).build()
71
85
val browser = authRequestBrowser?.let {
72
86
object : AuthorizationCodeInstalledApp .Browser {
@@ -75,7 +89,11 @@ actual object ModelixAuthClient {
75
89
}
76
90
}
77
91
} ? : AuthorizationCodeInstalledApp .DefaultBrowser ()
78
- AuthorizationCodeInstalledApp (flow, receiver, browser).authorize(" user" )
92
+ val tokens = AuthorizationCodeInstalledApp (flow, receiver, browser).authorize(userId)
93
+ if ((tokens.expiresInSeconds ? : 0 ) < 60 ) {
94
+ tokens.refreshToken()
95
+ }
96
+ tokens
79
97
}
80
98
}
81
99
@@ -136,8 +154,6 @@ actual object ModelixAuthClient {
136
154
authorize(url)
137
155
}
138
156
139
- println (" Access token: ${tokens.accessToken} " )
140
- println (" Refresh token: ${tokens.refreshToken} " )
141
157
BearerTokens (tokens.accessToken, tokens.refreshToken)
142
158
}
143
159
}
0 commit comments