Skip to content

Commit

Permalink
feat: support Response wrapper, use generic functions, refactor code (#…
Browse files Browse the repository at this point in the history
…48)

* feat: refactor to use generic. support response model wrapper.

- Support response model
- Add an abstract parent service class
- Use generic functions
- Simplify code
- Function returns data model alone

* fix: downgrade to java1.8

* reverted pom.xml

* fix: javadoc error
  • Loading branch information
wintbiit authored Jul 24, 2023
1 parent 7ac20f6 commit bea9ae7
Show file tree
Hide file tree
Showing 26 changed files with 382 additions and 879 deletions.
3 changes: 1 addition & 2 deletions src/main/java/org/casbin/casdoor/entity/CasdoorUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import java.io.Serializable;
import java.util.Map;

/**
Expand Down
36 changes: 13 additions & 23 deletions src/main/java/org/casbin/casdoor/service/CasdoorAccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,20 @@

package org.casbin.casdoor.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.casbin.casdoor.config.CasdoorConfig;
import org.casbin.casdoor.util.Map;
import org.casbin.casdoor.util.http.CasdoorResponse;
import org.casbin.casdoor.util.http.HttpClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
* Service Related to Account API
*/
public class CasdoorAccountService {
private final CasdoorConfig casdoorConfig;
final private ObjectMapper objectMapper = new ObjectMapper();

public class CasdoorAccountService extends CasdoorService {
public CasdoorAccountService(CasdoorConfig casdoorConfig) {
this.casdoorConfig = casdoorConfig;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
super(casdoorConfig);
}

/**
Expand All @@ -46,17 +40,13 @@ public CasdoorAccountService(CasdoorConfig casdoorConfig) {
* @throws IOException when JSON unmarshalling fails or HTTP requests fails
*/
public CasdoorResponse setPassword(String userName, String oldPassword, String newPassword) throws IOException {
String targetUrl = String.format("%s/api/set-password?owner=%s&clientId=%s&clientSecret=%s",
casdoorConfig.getEndpoint(), casdoorConfig.getOrganizationName(),
casdoorConfig.getClientId(), casdoorConfig.getClientSecret());

Map<String, String> formData = new HashMap<>(4);
formData.put("userOwner", casdoorConfig.getOrganizationName());
formData.put("userName", userName);
formData.put("oldPassword", oldPassword);
formData.put("newPassword", newPassword);

String responseStr = HttpClient.postForm(targetUrl, formData);
return objectMapper.readValue(responseStr, CasdoorResponse.class);
return doPost("set-password",
Map.of("owner", casdoorConfig.getOrganizationName()),
Map.of(
"userOwner", casdoorConfig.getOrganizationName(),
"userName", userName,
"oldPassword", oldPassword,
"newPassword", newPassword
), new TypeReference<CasdoorResponse<Object>>() {});
}
}
10 changes: 2 additions & 8 deletions src/main/java/org/casbin/casdoor/service/CasdoorAuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
package org.casbin.casdoor.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.Payload;
Expand Down Expand Up @@ -47,13 +45,9 @@
import java.text.ParseException;
import java.util.LinkedHashMap;

public class CasdoorAuthService {
private final CasdoorConfig casdoorConfig;
final private ObjectMapper objectMapper = new ObjectMapper();

public class CasdoorAuthService extends CasdoorService {
public CasdoorAuthService(CasdoorConfig casdoorConfig) {
this.casdoorConfig = casdoorConfig;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
super(casdoorConfig);
}

public String getOAuthToken(String code, String state) {
Expand Down
19 changes: 5 additions & 14 deletions src/main/java/org/casbin/casdoor/service/CasdoorEmailService.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,22 @@

package org.casbin.casdoor.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.casbin.casdoor.config.CasdoorConfig;
import org.casbin.casdoor.entity.CasdoorEmailForm;
import org.casbin.casdoor.util.http.CasdoorResponse;
import org.casbin.casdoor.util.http.HttpClient;

import java.io.IOException;

public class CasdoorEmailService {

private final CasdoorConfig casdoorConfig;
final private ObjectMapper objectMapper = new ObjectMapper();

public class CasdoorEmailService extends CasdoorService {
public CasdoorEmailService(CasdoorConfig casdoorConfig) {
this.casdoorConfig = casdoorConfig;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
super(casdoorConfig);
}

public CasdoorResponse sendEmail(String title, String content, String sender, String... receivers) throws IOException {
String targetUrl = String.format("%s/api/send-email?clientId=%s&clientSecret=%s",
casdoorConfig.getEndpoint(), casdoorConfig.getClientId(), casdoorConfig.getClientSecret());
CasdoorEmailForm casdoorEmailForm = new CasdoorEmailForm(title, content, sender, receivers);
String emailFormStr = objectMapper.writeValueAsString(casdoorEmailForm);
String responseStr = HttpClient.postString(targetUrl, emailFormStr);
return objectMapper.readValue(responseStr, CasdoorResponse.class);

return doPost("send-email", null, emailFormStr, new TypeReference<CasdoorResponse<Object>>() {});
}
}
116 changes: 31 additions & 85 deletions src/main/java/org/casbin/casdoor/service/CasdoorEnforcerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,108 +14,54 @@

package org.casbin.casdoor.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.casbin.casdoor.config.CasdoorConfig;
import org.casbin.casdoor.exception.CasdoorException;
import org.casbin.casdoor.util.Map;
import org.casbin.casdoor.util.http.CasdoorResponse;
import org.casbin.casdoor.util.http.HttpClient;
import org.casbin.casdoor.util.MapToUrlUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CasdoorEnforcerService {
private final CasdoorConfig casdoorConfig;
private final ObjectMapper objectMapper;
import java.util.Arrays;

public class CasdoorEnforcerService extends CasdoorService {
public CasdoorEnforcerService(CasdoorConfig casdoorConfig) {
this.casdoorConfig = casdoorConfig;
this.objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
super(casdoorConfig);
}

public boolean enforce(String permissionId, String modelId, String resourceId, Object[] casbinRequest) throws IOException {
byte[] postBytes = objectMapper.writeValueAsBytes(casbinRequest);
if (postBytes == null) {
throw new CasdoorException("Failed to get bytes from URL");
}
CasdoorResponse response = doEnforce("enforce", permissionId, modelId, resourceId, postBytes);

if (!(response.getStatus().equals("ok"))) {
throw new CasdoorException("Failed to unmarshal JSON");
}

List<?> results = (List<?>) response.getData();
for (Object result : results) {
if (!(result instanceof Boolean)) {
throw new CasdoorException("Invalid data");
}

if ((Boolean) result) {
return true;
}
}

return false;
CasdoorResponse<Boolean[]> response = doPost("enforce",
Map.of(
"permissionId", casdoorConfig.getOrganizationName() + "/" + permissionId,
"modelId", modelId,
"resourceId", resourceId
),
new String(postBytes, StandardCharsets.UTF_8),
new TypeReference<CasdoorResponse<Boolean[]>>() {}
);

// All true
return Arrays.stream(response.getData()).allMatch(Boolean::booleanValue);
}
public boolean[][] batchEnforce(String permissionId, String modelId, String resourceId, Object[][] casbinRequests) throws IOException {
public Boolean[][] batchEnforce(String permissionId, String modelId, String resourceId, Object[][] casbinRequests) throws IOException {
byte[] postBytes = objectMapper.writeValueAsBytes(casbinRequests);
if (postBytes == null) {
throw new CasdoorException("Failed to get bytes from URL");
}
CasdoorResponse response = doEnforce("batch-enforce", permissionId, modelId, resourceId, postBytes);

if (!(response.getStatus().equals("ok"))) {
throw new CasdoorException("Failed to unmarshal JSON");
}
List<?> responseData = (List<?>) response.getData();
boolean[][] allows = new boolean[responseData.size()][];

for (int i = 0; i < responseData.size(); i++) {
Object data = responseData.get(i);
if (!(data instanceof List<?>)) {
throw new CasdoorException("Invalid data");
}

List<?> dataSublist = (List<?>) data;
allows[i] = new boolean[dataSublist.size()];

for (int j = 0; j < dataSublist.size(); j++) {
Object elem = dataSublist.get(j);
if (!(elem instanceof Boolean)) {
throw new CasdoorException("Invalid data");
}
allows[i][j] = (Boolean) elem;
}
}

return allows;
CasdoorResponse<Boolean[][]> response = doPost("batch-enforce",
Map.of(
"permissionId", casdoorConfig.getOrganizationName() + "/" + permissionId,
"modelId", modelId,
"resourceId", resourceId
),
new String(postBytes, StandardCharsets.UTF_8),
new TypeReference<CasdoorResponse<Boolean[][]>>() {}
);

return response.getData();
}
public CasdoorResponse doEnforce(String action, String permissionId, String modelId, String resourceId, byte[] postBytes) throws IOException {
Map<String, String> queryMap = new HashMap<>();
queryMap.put("action", action);
queryMap.put("permissionId", casdoorConfig.getOrganizationName()+"/"+permissionId);
queryMap.put("modelId", modelId);
queryMap.put("resourceId", resourceId);
queryMap.put("clientSecret",casdoorConfig.getClientSecret());
queryMap.put("clientId", casdoorConfig.getClientId());

String url = null;
if(queryMap.get("action").equals("enforce")){
url = casdoorConfig.getEndpoint() + "/api/enforce?" + MapToUrlUtils.mapToUrlParams(queryMap);
}
else{
url = casdoorConfig.getEndpoint() + "/api/batch-enforce?" + MapToUrlUtils.mapToUrlParams(queryMap);

}
String data = new String(postBytes, StandardCharsets.UTF_8);
String response = HttpClient.postString(url, data);
CasdoorResponse casdoorResponse = objectMapper.readValue(response, CasdoorResponse.class);
if (!casdoorResponse.getStatus().equals("ok")){
throw new CasdoorException("Failed to unmarshal JSON");
}
return casdoorResponse;
}

}
Loading

0 comments on commit bea9ae7

Please sign in to comment.