forked from bunq/sdk_java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiContext.java
More file actions
403 lines (341 loc) · 12.2 KB
/
ApiContext.java
File metadata and controls
403 lines (341 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package com.bunq.sdk.context;
import com.bunq.sdk.exception.BunqException;
import com.bunq.sdk.http.BunqResponse;
import com.bunq.sdk.json.BunqGsonBuilder;
import com.bunq.sdk.model.core.DeviceServerInternal;
import com.bunq.sdk.model.core.Installation;
import com.bunq.sdk.model.core.PaymentServiceProviderCredentialInternal;
import com.bunq.sdk.model.core.SessionServer;
import com.bunq.sdk.model.generated.endpoint.SessionApiObject;
import com.bunq.sdk.model.generated.endpoint.UserCredentialPasswordIpApiObject;
import com.bunq.sdk.model.generated.object.CertificateObject;
import com.bunq.sdk.security.SecurityUtils;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* The context to make the API calls in. Consists of:
* > Environment type (SANDBOX or PRODUCTION)
* > Bunq API Key for the corresponding environment
* > Installation context
* > Session context
*/
public class ApiContext implements java.io.Serializable {
/**
* Error constants.
*/
private static final String ERROR_COULD_NOT_SAVE_API_CONTEXT =
"Could not save the API context.";
private static final String ERROR_COULD_NOT_RESTORE_API_CONTEXT =
"Could not restore the API context.";
/**
* Default path to store the serialized API context.
*/
private static final String PATH_API_CONTEXT_DEFAULT = "bunq.conf";
/**
* Dummy ID to pass to Session endpoint.
*/
private static final long SESSION_ID_DUMMY = 0;
/**
* Minimum time to session expiry not requiring session reset.
*/
private static final int TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS = 30;
/**
* Constant for converting milliseconds to seconds.
*/
private static final int MILLISECONDS_IN_SECOND = 1000;
/**
* Encoding of the serialized API context.
*/
private static final String ENCODING_BUNQ_CONF = "UTF-8";
protected static Gson gson = BunqGsonBuilder.buildDefault().create();
@Expose
@SerializedName("environment_type")
private final ApiEnvironmentType environmentType;
@Expose
@SerializedName("api_key")
private String apiKey;
@Expose
@SerializedName("installation_context")
private InstallationContext installationContext;
@Expose
@SerializedName("session_context")
private SessionContext sessionContext;
@Expose
@SerializedName("proxy")
private String proxy;
/**
* Create empty API context without apiKey.
*/
private ApiContext(ApiEnvironmentType environmentType) {
this.environmentType = environmentType;
}
/**
* Create an empty API context.
*/
private ApiContext(ApiEnvironmentType environmentType, String apiKey) {
this(environmentType);
this.apiKey = apiKey;
}
/**
* Create and initialize an API Context with current IP as permitted and no proxy.
*/
public static ApiContext create(
ApiEnvironmentType environmentType,
String apiKey,
String deviceDescription
) {
return create(environmentType, apiKey, deviceDescription, new ArrayList<String>());
}
/**
* Create and initialize an API Context with given permitted ips and no proxy.
*/
public static ApiContext create(ApiEnvironmentType environmentType,
String apiKey,
String deviceDescription,
List<String> permittedIps) {
return create(environmentType, apiKey, deviceDescription, permittedIps, null);
}
/**
* Create and initialize an API Context with current IP as permitted and a proxy.
*/
public static ApiContext create(ApiEnvironmentType environmentType,
String apiKey,
String deviceDescription,
String proxy) {
return create(environmentType, apiKey, deviceDescription, new ArrayList<String>(), proxy);
}
/**
* Create and initialize an API Context.
*/
public static ApiContext create(ApiEnvironmentType environmentType,
String apiKey,
String deviceDescription,
List<String> permittedIps,
String proxy) {
ApiContext apiContext = new ApiContext(environmentType, apiKey);
apiContext.proxy = proxy;
apiContext.initialize(deviceDescription, permittedIps);
return apiContext;
}
/**
* Create and initialize a PSD2 API Context.
*/
public static ApiContext createForPsd2(
ApiEnvironmentType environmentType,
CertificateObject certificate,
PrivateKey privateKey,
CertificateObject[] allChainCertificate,
String description,
List<String> allPermittedIp
) {
ApiContext apiContext = new ApiContext(environmentType);
apiContext.initializeInstallation();
UserCredentialPasswordIpApiObject serviceProviderCredential = apiContext.initializePsd2Credential(
certificate,
privateKey,
allChainCertificate
);
apiContext.apiKey = serviceProviderCredential.getTokenValue();
apiContext.initializeDeviceRegistration(description, allPermittedIp);
apiContext.initializeSession();
return apiContext;
}
/**
* Set up a PSD2 ApiContext.
*
* @return ApiContext
*/
public static ApiContext createForPsd2(
ApiEnvironmentType environmentType,
CertificateObject certificate,
PrivateKey privateKey,
CertificateObject[] allChainCertificate,
String description,
List<String> allPermittedIp,
String proxy
) {
ApiContext context = createForPsd2(environmentType, certificate, privateKey, allChainCertificate, description, allPermittedIp);
context.proxy = proxy;
return context;
}
/**
* Restores a context from a default location.
*/
public static ApiContext restore() {
return restore(PATH_API_CONTEXT_DEFAULT);
}
/**
* Restores a context from a given file.
*/
public static ApiContext restore(String fileName) {
try {
File file = new File(fileName);
String json = FileUtils.readFileToString(file, ENCODING_BUNQ_CONF);
return fromJson(json);
} catch (IOException exception) {
throw new BunqException(ERROR_COULD_NOT_RESTORE_API_CONTEXT, exception);
}
}
/**
* Restores a context from a given JSON string.
*/
public static ApiContext fromJson(String json) {
return gson.fromJson(json, ApiContext.class);
}
private void initialize(String deviceDescription, List<String> permittedIps) {
/* The calls below are order-sensitive: to initialize a Device Registration, we need an
* Installation, and to initialize a Session we need a Device Registration. */
initializeInstallation();
initializeDeviceRegistration(deviceDescription, permittedIps);
initializeSession();
}
/**
* Create a new installation and store its data in an InstallationContext.
*/
private void initializeInstallation() {
KeyPair keyPairClient = SecurityUtils.generateKeyPair();
Installation installation = Installation.create(
this,
SecurityUtils.getPublicKeyFormattedString(keyPairClient.getPublic())
).getValue();
installationContext = new InstallationContext(installation, keyPairClient);
}
/**
* Initialize the context with Psd2 credentials.
*/
private UserCredentialPasswordIpApiObject initializePsd2Credential(
CertificateObject certificate,
PrivateKey privateKey,
CertificateObject[] allChainCertificate
) {
String sessionToken = installationContext.getToken();
KeyPair clientKeyPair = installationContext.getKeyPairClient();
String stringToSign = SecurityUtils.getPublicKeyFormattedString(clientKeyPair.getPublic()) + sessionToken;
String encodedSignature = SecurityUtils.generateSignature(stringToSign, privateKey);
BunqResponse<UserCredentialPasswordIpApiObject> paymentProviderResponse = PaymentServiceProviderCredentialInternal.createWithApiContext(
certificate.getCertificate(),
SecurityUtils.getCertificateChainString(allChainCertificate),
encodedSignature,
this
);
return paymentProviderResponse.getValue();
}
private void initializeDeviceRegistration(String deviceDescription, List<String> permittedIps) {
DeviceServerInternal.create(this, deviceDescription, this.apiKey, permittedIps);
}
/**
* Create a new session and its data in a SessionContext.
*/
private void initializeSession() {
sessionContext = new SessionContext(SessionServer.create(this).getValue());
}
/**
* Closes the current session and opens a new one.
*/
public void resetSession() {
dropSessionContext();
initializeSession();
}
private void dropSessionContext() {
sessionContext = null;
}
/**
* Closes the current session.
*/
public void closeSession() {
deleteSession();
dropSessionContext();
}
private void deleteSession() {
SessionApiObject.delete(SESSION_ID_DUMMY);
}
/**
* Check if current time is too close to the saved session expiry time and reset session if
* needed.
*/
public boolean ensureSessionActive() {
if (!isSessionActive()) {
resetSession();
return true;
}
return false;
}
public boolean isSessionActive() {
return sessionContext != null &&
getTimeToSessionExpiryInSeconds() > TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS;
}
private long getTimeToSessionExpiryInSeconds() {
long timeToSessionExpiryMilliseconds = sessionContext.getExpiryTime().getTime() -
new Date().getTime();
return timeToSessionExpiryMilliseconds / MILLISECONDS_IN_SECOND;
}
/**
* Save a JSON representation of the API Context to the default location.
*/
public void save() {
save(PATH_API_CONTEXT_DEFAULT);
}
/**
* Save a JSON representation of the API Context to a given file.
*/
public void save(String fileName) {
try {
File file = new File(fileName);
FileUtils.writeStringToFile(file, toJson(), ENCODING_BUNQ_CONF);
} catch (IOException exception) {
throw new BunqException(ERROR_COULD_NOT_SAVE_API_CONTEXT, exception);
}
}
/**
* Serializes the context to JSON.
*/
public String toJson() {
return gson.toJson(this);
}
/**
* @return The base URI of the current environment.
*/
public String getBaseUri() {
return environmentType.getBaseUri();
}
public String getApiVersion() {
return environmentType.getApiVersion();
}
/**
* @return The session token, installation token if the session isn't created yet, or null if no
* installation is created either.
*/
public String getSessionToken() {
if (sessionContext != null) {
return sessionContext.getToken();
} else if (installationContext != null) {
return installationContext.getToken();
} else {
return null;
}
}
public ApiEnvironmentType getEnvironmentType() {
return environmentType;
}
public String getApiKey() {
return apiKey;
}
public InstallationContext getInstallationContext() {
return installationContext;
}
public SessionContext getSessionContext() {
return sessionContext;
}
public String getProxy() {
return proxy;
}
}