Skip to content

Commit 86daffb

Browse files
authored
Merge pull request #3 from permitio/raz/per-3687-publish-java-sdk-with-elements
Raz/per 3687 publish java sdk with elements
2 parents 71f0f75 + 22ca90c commit 86daffb

6 files changed

Lines changed: 152 additions & 5 deletions

File tree

src/main/java/io/permit/sdk/Permit.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.google.gson.Gson;
44
import com.google.gson.GsonBuilder;
55
import io.permit.sdk.api.ApiClient;
6+
import io.permit.sdk.api.ElementsClient;
67
import io.permit.sdk.enforcement.Enforcer;
78
import io.permit.sdk.enforcement.IEnforcerApi;
89
import io.permit.sdk.enforcement.Resource;
@@ -19,10 +20,12 @@ public class Permit implements IEnforcerApi {
1920
private final Enforcer enforcer;
2021
public final PermitConfig config;
2122
public final ApiClient api;
23+
public final ElementsClient elements;
2224

2325
public Permit(PermitConfig config) {
2426
this.config = config;
2527
this.api = new ApiClient(this.config);
28+
this.elements = new ElementsClient(this.config);
2629
this.enforcer = new Enforcer(this.config);
2730

2831
if (this.config.isDebugMode()) {

src/main/java/io/permit/sdk/PermitConfig.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ public class PermitConfig {
66
// main config vars
77
private final String token;
88
private final String pdp;
9+
private final String apiUrl;
910
private final Boolean debugMode;
1011

1112
// logger config
@@ -25,6 +26,7 @@ public class PermitConfig {
2526
private PermitConfig(Builder builder) {
2627
this.token = builder.token;
2728
this.pdp = builder.pdp;
29+
this.apiUrl = builder.apiUrl;
2830
this.debugMode = builder.debugMode;
2931
this.logLevel = builder.logLevel;
3032
this.logLabel = builder.logLabel;
@@ -40,6 +42,7 @@ private PermitConfig(Builder builder) {
4042
public String getToken() {
4143
return token;
4244
}
45+
public String getApiUrl() { return apiUrl; }
4346
public String getPdpAddress() {
4447
return pdp;
4548
}
@@ -74,7 +77,8 @@ public Boolean shouldUseDefaultTenantIfEmpty() {
7477
public static class Builder {
7578
// main config vars
7679
private String token;
77-
private String pdp = "http://localhost:7000";
80+
private String pdp = "http://localhost:7766";
81+
private String apiUrl = "https://api.permit.io";
7882
private Boolean debugMode = false;
7983

8084
// logger config
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package io.permit.sdk.api;
2+
3+
import com.google.gson.FieldNamingPolicy;
4+
import com.google.gson.Gson;
5+
import com.google.gson.GsonBuilder;
6+
import io.permit.sdk.PermitConfig;
7+
import io.permit.sdk.api.models.*;
8+
import okhttp3.*;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
import java.io.IOException;
13+
import java.util.HashMap;
14+
import java.util.List;
15+
16+
interface IElementsApi {
17+
UserLoginResponse loginAs(String userId, String tenantId) throws IOException, PermitApiException;
18+
}
19+
20+
public class ElementsClient implements IElementsApi {
21+
final static Logger logger = LoggerFactory.getLogger(ApiClient.class);
22+
private final OkHttpClient client = new OkHttpClient();
23+
private final PermitConfig config;
24+
private final Headers headers;
25+
private final String apiUrl;
26+
27+
public ElementsClient(PermitConfig config) {
28+
this.config = config;
29+
this.headers = new Headers.Builder()
30+
.add("Content-Type", "application/json")
31+
.add("Authorization", String.format("Bearer %s", this.config.getToken()))
32+
.build();
33+
this.apiUrl = this.config.getApiUrl();
34+
}
35+
36+
private void throwIfErrorResponseCode(String requestRepr, Response response, String responseContent, List<Integer> expectedErrorCodes) throws PermitApiException {
37+
String log = String.format("Received response: %s : status code %d : %s", requestRepr, response.code(), responseContent);
38+
if (!response.isSuccessful() && this.config.isDebugMode()) {
39+
this.logger.error(log);
40+
} else {
41+
this.logger.debug(log);
42+
}
43+
if (!response.isSuccessful() && !expectedErrorCodes.contains(response.code())) {
44+
throw new PermitApiException(
45+
String.format(
46+
"unexpected status code: %d for request: %s",
47+
response.code(),
48+
requestRepr
49+
)
50+
);
51+
}
52+
}
53+
54+
private void throwIfErrorResponseCode(String requestRepr, Response response, String responseContent) throws PermitApiException {
55+
throwIfErrorResponseCode(requestRepr, response, responseContent, List.of());
56+
}
57+
58+
@Override
59+
public UserLoginResponse loginAs(String userId, String tenantId) throws IOException, PermitApiException {
60+
UserLoginRequest element = new UserLoginRequest();
61+
element.tenantId = tenantId;
62+
element.userId = userId;
63+
64+
// request body
65+
Gson gson = new GsonBuilder()
66+
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
67+
.create();
68+
String requestBody = gson.toJson(element);
69+
RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/json"));
70+
71+
// create the request
72+
String url = String.format("%s/v2/auth/elements_login_as", this.config.getApiUrl());
73+
Request request = new Request.Builder()
74+
.url(url)
75+
.headers(this.headers)
76+
.post(body)
77+
.build();
78+
79+
String requestRepr = String.format("permit.elements.login_as(%s)", requestBody);
80+
this.logger.debug(String.format("Sending request: %s", requestRepr));
81+
82+
// send the request
83+
try (Response response = client.newCall(request).execute()) {
84+
ResponseBody responseBody = response.body();
85+
if (responseBody == null) {
86+
throw new IOException("got empty response");
87+
}
88+
String responseString = responseBody.string();
89+
throwIfErrorResponseCode(requestRepr, response, responseString);
90+
UserLoginResponse userLoginResponse = gson.fromJson(responseString, UserLoginResponse.class);
91+
userLoginResponse.content = new HashMap<>();
92+
userLoginResponse.content.put("url", userLoginResponse.redirectUrl);
93+
return userLoginResponse;
94+
}
95+
}
96+
97+
public String getApiUrl() {
98+
return apiUrl;
99+
}
100+
}
101+
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package io.permit.sdk.api.models;
2+
3+
public class UserLoginRequest {
4+
public String userId = null;
5+
public String tenantId = null;
6+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package io.permit.sdk.api.models;
2+
3+
import java.util.Map;
4+
5+
public class UserLoginResponse {
6+
public String error = null;
7+
public String token = null;
8+
public String extra = null;
9+
public String redirectUrl = null;
10+
public Map<String, String> content = null;
11+
}

src/test/java/io/permit/sdk/PermitIntegrationTests.java

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import com.google.common.base.Strings;
44
import com.google.gson.Gson;
55
import io.permit.sdk.api.PermitApiException;
6+
import io.permit.sdk.api.models.UserLoginResponse;
67
import io.permit.sdk.api.models.UserModel;
7-
import io.permit.sdk.enforcement.AssignedRole;
88
import io.permit.sdk.enforcement.Resource;
99
import io.permit.sdk.enforcement.User;
1010
import okhttp3.HttpUrl;
@@ -15,7 +15,7 @@
1515
import java.io.IOException;
1616
import java.net.InetSocketAddress;
1717
import java.net.Socket;
18-
import java.util.ArrayList;
18+
import java.util.Random;
1919

2020
import static org.junit.jupiter.api.Assertions.*;
2121

@@ -32,9 +32,12 @@ class PermitIntegrationTests {
3232
private final static int loggerSeparatorLength = 80;
3333
private boolean skipTests = false;
3434

35+
static Random rand = new Random();
36+
static String suffixedUserKey = "test|" + rand.nextInt();
37+
3538
private final static String roleKey = "captain";
3639
private final static String tenantKey = "tortuga";
37-
private final static String userKey = "test|13d4dd3ff127";
40+
private final static String userKey = suffixedUserKey;
3841
private final static String userEmail = "jack@pirates.com";
3942
private final static String userFirstName = "Jack";
4043
private final static String userLastName = "Sparrow";
@@ -90,7 +93,7 @@ private static void logTestIsStarting(String testName) {
9093
Boolean allowed = null;
9194
try {
9295
allowed = permit.check(
93-
User.fromString("55de594980944d48944dc10b9c70483c"),
96+
User.fromString(userKey),
9497
"create",
9598
Resource.fromString("document")
9699
);
@@ -101,6 +104,25 @@ private static void logTestIsStarting(String testName) {
101104
assertTrue(allowed, "permit.check() should be true");
102105
}
103106

107+
@Test void testPermitElementsLoginAs() {
108+
if (skipTests) {
109+
return;
110+
}
111+
logTestIsStarting("permitCheckSucceeds");
112+
Permit permit = new Permit(this.config);
113+
UserLoginResponse loginAs = null;
114+
try {
115+
loginAs = permit.elements.loginAs("raz@permit.io", "fafb66f9c98647ad954f129b9f2b1c84");
116+
} catch (IOException e) {
117+
fail(e);
118+
} catch (PermitApiException e) {
119+
e.printStackTrace();
120+
}
121+
122+
assertNotNull(loginAs.redirectUrl);
123+
assertNotNull(loginAs.content);
124+
}
125+
104126
@Test void testPermitApiUserLifecycle() {
105127
if (skipTests) {
106128
return;

0 commit comments

Comments
 (0)