Skip to content

Commit 68f0830

Browse files
author
Asaf Cohen
authored
Merge pull request #4 from permitio/asaf/per-3421-v2-java-sdk
Java SDK V2
2 parents 86daffb + 23a470c commit 68f0830

186 files changed

Lines changed: 14334 additions & 675 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,6 @@
77

88
# Ignore Gradle build output directory
99
build
10+
11+
# Ignore stg schemas
12+
stg-schemas/

Makefile

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
.PHONY: help
2+
3+
.DEFAULT_GOAL := help
4+
5+
# ENVIRONMENT?=dev
6+
7+
## generate openapi models
8+
generate-openapi:
9+
openapi-generator generate -i https://api.permit.io/v2/openapi.json -g java -o generated/ -c openapi-config.json
10+
11+
clean-openapi:
12+
rm -rf generated/
13+
14+
## generate open api models from json schema
15+
generate-jsonschema:
16+
openapi2jsonschema https://api.permit.io/v2/openapi.json -o schemas/
17+

README.md

Lines changed: 138 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,140 @@
1-
# Permit.io client for Java
1+
# Java SDK for Permit.io
22

3-
Java client library for the Permit.io full-stack permissions platform.
3+
Java SDK for interacting with the Permit.io full-stack permissions platform.
44

5+
## Overview
6+
7+
This guide will walk you through the steps of installing the Permit.io Java SDK and integrating it into your code.
8+
9+
## Installation
10+
11+
For [Maven](https://maven.apache.org/) projects, use:
12+
```xml
13+
<dependency>
14+
<groupId>io.permit</groupId>
15+
<artifactId>permit-sdk-java</artifactId>
16+
<version>1.0.0-RC</version>
17+
</dependency>
18+
```
19+
20+
For [Gradle](https://gradle.org/) projects, configure `permit-sdk-java` as a dependency in your `build.gradle` file:
21+
```groovy
22+
dependencies {
23+
// ...
24+
25+
implementation 'io.permit:permit-sdk-java:1.0.0-RC'
26+
}
27+
```
28+
29+
## Usage
30+
31+
### Initializing the SDK
32+
To init the SDK, you need to create a new Permit client with the API key you got from the Permit.io dashboard.
33+
34+
First we will create a new `PermitConfig` object so we can pass it to the Permit client.
35+
36+
Second, we will create a new `Permit` client with the `PermitConfig` object we created.
37+
38+
```java
39+
import io.permit.sdk.Permit;
40+
import io.permit.sdk.PermitConfig;
41+
42+
// This line initializes the SDK and connects your Java app
43+
// to the Permit.io PDP container you've set up in the previous step.
44+
Permit permit = new Permit(
45+
new PermitConfig.Builder("[YOUR_API_KEY]")
46+
// in production, you might need to change this url to fit your deployment
47+
.withPdpAddress("http://localhost:7766")
48+
// optionally, if you wish to get more debug messages to your log, set this to true
49+
.withDebugMode(false)
50+
.build()
51+
);
52+
```
53+
54+
### Checking permissions
55+
To check permissions using our `permit.check()` method, you will have to create User and Resource models as input to the permission check.
56+
The models are located in ``
57+
58+
Follow the example below:
59+
60+
```java
61+
import io.permit.sdk.enforcement.Resource;
62+
import io.permit.sdk.enforcement.User;
63+
import io.permit.sdk.Permit;
64+
65+
boolean permitted = permit.check(
66+
// building the user object using User.fromString()
67+
// the user key (this is the unique identifier of the user in the permission system).
68+
User.fromString("[USER KEY]"),
69+
// the action key (string)
70+
"create",
71+
// the resource object, can be initialized from string if the "default" tenant is used.
72+
Resource.fromString("document")
73+
);
74+
75+
if (permitted) {
76+
System.out.println("User is PERMITTED to create a document in the 'default' tenant");
77+
} else {
78+
System.out.println("User is NOT PERMITTED to create a document in the 'default' tenant");
79+
}
80+
```
81+
82+
A more complicated example (passing attributes on the user object, using an explicit tenant in the resource):
83+
```java
84+
import io.permit.sdk.enforcement.Resource;
85+
import io.permit.sdk.enforcement.User;
86+
import java.util.HashMap;
87+
88+
89+
HashMap<String, Object> userAttributes = new HashMap<>();
90+
userAttributes.put("age", Integer.valueOf(20));
91+
userAttributes.put("favorite_color", "yellow");
92+
93+
boolean permitted = permit.check(
94+
// building the user object using the User.Builder class
95+
new User.Builder("[USER KEY]").withAttributes(userAttributes).build(),
96+
// the action key (string)
97+
"create",
98+
// building the resource object using the Resource.Builder in order to pass an explicit tenant key: "awesome-inc"
99+
new Resource.Builder("document").withTenant("awesome-inc").build()
100+
);
101+
102+
if (permitted) {
103+
System.out.println("User is PERMITTED to create a document in the 'awesome-inc' tenant");
104+
} else {
105+
System.out.println("User is NOT PERMITTED to create a document in the 'awesome-inc' tenant");
106+
}
107+
```
108+
109+
### Syncing users
110+
When the user first logins, and after you check if he authenticated successfully (i.e: **by checking the JWT access token**) -
111+
you need to declare the user in the permission system so you can run `permit.check()` on that user.
112+
113+
To declare (or "sync") a user in the Permit.io API, use the `permit.api.users.sync()` method.
114+
115+
Follow the example below:
116+
```java
117+
import io.permit.sdk.api.models.CreateOrUpdateResult;
118+
import io.permit.sdk.enforcement.User;
119+
120+
HashMap<String, Object> userAttributes = new HashMap<>();
121+
userAttributes.put("age", Integer.valueOf(50));
122+
userAttributes.put("fav_color", "red");
123+
124+
CreateOrUpdateResult<UserRead> result = permit.api.users.sync(
125+
(new User.Builder("auth0|elon"))
126+
.withEmail("elonmusk@tesla.com")
127+
.withFirstName("Elon")
128+
.withLastName("Musk")
129+
.withAttributes(userAttributes)
130+
.build()
131+
);
132+
UserRead user = result.getResult();
133+
assertTrue(result.wasCreated());
134+
```
135+
136+
Most params to UserCreates are optional, and only the unique user key is needed. This is valid:
137+
138+
```java
139+
CreateOrUpdateResult<UserRead> result = permit.api.users.sync(new UserCreate("[USER KEY]"));
140+
```

build.gradle

Lines changed: 93 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ plugins {
1717
id 'com.palantir.git-version' version '0.13.0'
1818
// auto release to maven central (skip sonatype manual nexus release process)
1919
id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
20+
// translate json schemas to java classes
21+
id "org.jsonschema2pojo" version "1.1.3"
2022
}
2123

2224
// It is important to set the group and the version to the root project
@@ -41,20 +43,107 @@ java {
4143

4244
// package dependencies
4345
dependencies {
46+
// swagger
47+
implementation 'io.swagger:swagger-annotations:1.6.5'
48+
49+
// http client
50+
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
51+
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
52+
53+
// json serialization and deserialization
54+
implementation 'com.google.code.gson:gson:2.9.0'
55+
implementation 'io.gsonfire:gson-fire:1.8.5'
56+
57+
// openapi annotations
58+
implementation 'javax.ws.rs:jsr311-api:1.1.1'
59+
implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1'
60+
implementation 'org.openapitools:jackson-databind-nullable:0.2.3'
61+
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
62+
implementation "jakarta.annotation:jakarta.annotation-api:1.3.5"
63+
64+
// logger
4465
implementation 'ch.qos.logback:logback-classic:1.2.10'
4566
implementation 'ch.qos.logback:logback-core:1.2.10'
4667
implementation 'org.slf4j:slf4j-api:1.7.33'
4768

69+
70+
4871
// Use JUnit Jupiter for testing.
4972
testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'
5073

5174
// These dependencies are used internally, and not exposed to consumers on their own compile classpath.
5275
// google standard java library
5376
implementation 'com.google.guava:guava:30.1.1-jre'
54-
// json serialization and deserialization
55-
implementation 'com.google.code.gson:gson:2.8.9'
56-
// http client
57-
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
77+
78+
79+
}
80+
81+
jsonSchema2Pojo {
82+
// Location of the JSON Schema file(s). This may refer to a single file or a directory of files.
83+
source = files("schemas/")
84+
85+
// Target directory for generated Java source files. The plugin will add this directory to the
86+
// java source set so the compiler will find and compile the newly generated source files.
87+
targetDirectory = file("src/main/java")
88+
89+
// Package name used for generated Java classes (for types where a fully qualified name has not
90+
// been supplied in the schema using the 'javaType' property).
91+
targetPackage = 'io.permit.sdk.openapi.models'
92+
93+
// Whether to allow 'additional' properties to be supported in classes by adding a map to
94+
// hold these. This is true by default, meaning that the schema rule 'additionalProperties'
95+
// controls whether the map is added. Set this to false to globally disable additional properties.
96+
includeAdditionalProperties = false
97+
98+
// Whether to include a javax.annotation.Generated (Java 8 and lower) or
99+
// javax.annotation.processing.Generated (Java 9+) in on generated types (default true).
100+
// See also: targetVersion.
101+
includeGeneratedAnnotation = true
102+
103+
// Whether to use the 'title' property of the schema to decide the class name (if not
104+
// set to true, the filename and property names are used).
105+
useTitleAsClassname = true
106+
107+
// Whether to empty the target directory before generation occurs, to clear out all source files
108+
// that have been generated previously. <strong>Be warned</strong>, when activated this option
109+
// will cause jsonschema2pojo to <strong>indiscriminately delete the entire contents of the target
110+
// directory (all files and folders)</strong> before it begins generating sources.
111+
removeOldOutput = false
112+
113+
// Whether to generate builder-style methods of the form withXxx(value) (that return this),
114+
// alongside the standard, void-return setters.
115+
generateBuilders = true
116+
117+
// If set to true, then the gang of four builder pattern will be used to generate builders on
118+
// generated classes. Note: This property works in collaboration with generateBuilders.
119+
// If generateBuilders is false then this property will not do anything.
120+
useInnerClassBuilders = false
121+
122+
// Whether to include hashCode and equals methods in generated Java types.
123+
includeHashcodeAndEquals = false
124+
125+
// Whether to include a toString method in generated Java types.
126+
includeToString = false
127+
128+
// Whether to include getters or to omit these accessor methods and create public fields instead.
129+
includeGetters = false
130+
131+
// Whether to include setters or to omit these accessor methods and create public fields instead.
132+
includeSetters = false
133+
134+
// Whether to use java.util.Optional for getters on properties that are not required
135+
useOptionalForGetters = true
136+
137+
// Whether to generate constructors or not.
138+
includeConstructors = true
139+
140+
// Whether to include only 'required' fields in generated constructors
141+
constructorsRequiredPropertiesOnly = true
142+
143+
annotationStyle = 'gson'
144+
145+
// Whether to initialize Set and List fields as empty collections, or leave them as null.
146+
initializeCollections = false
58147
}
59148

60149
publishing {

openapi-config.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"apiPackage": "io.permit.sdk.openapi.api",
3+
"invokerPackage": "io.permit.sdk.openapi.client",
4+
"modelPackage": "io.permit.sdk.openapi.model",
5+
"serializationLibrary": "gson",
6+
"legacyDiscriminatorBehavior": "true"
7+
}

schemas/actionblockeditable.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"title": "ActionBlockEditable",
3+
"type": "object",
4+
"properties": {
5+
"name": {
6+
"title": "Name",
7+
"type": "string",
8+
"description": "a more descriptive name for the action"
9+
},
10+
"description": {
11+
"title": "Description",
12+
"type": "string",
13+
"description": "optional description string explaining what this action represents in your system"
14+
}
15+
},
16+
"additionalProperties": false,
17+
"$schema": "http://json-schema.org/schema#"
18+
}

schemas/actionblockread.json

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"title": "ActionBlockRead",
3+
"required": [
4+
"id"
5+
],
6+
"type": "object",
7+
"properties": {
8+
"name": {
9+
"title": "Name",
10+
"type": "string",
11+
"description": "a more descriptive name for the action"
12+
},
13+
"description": {
14+
"title": "Description",
15+
"type": "string",
16+
"description": "optional description string explaining what this action represents in your system"
17+
},
18+
"id": {
19+
"title": "Id",
20+
"type": "string",
21+
"description": "Unique id of the action"
22+
},
23+
"key": {
24+
"title": "Key",
25+
"type": "string",
26+
"description": "action key"
27+
}
28+
},
29+
"additionalProperties": false,
30+
"$schema": "http://json-schema.org/schema#"
31+
}

schemas/addrolepermissions.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"title": "AddRolePermissions",
3+
"required": [
4+
"permissions"
5+
],
6+
"type": "object",
7+
"properties": {
8+
"permissions": {
9+
"title": "Permissions",
10+
"type": "array",
11+
"items": {
12+
"type": "string"
13+
},
14+
"description": "List of permissions to assign to the role. If a permission is already granted to the role it is skipped. Each permission can be either a resource action id, or `{resource_key}:{action_key}`, i.e: the \"permission name\"."
15+
}
16+
},
17+
"additionalProperties": false,
18+
"example": {
19+
"permissions": [
20+
"document:write"
21+
]
22+
},
23+
"$schema": "http://json-schema.org/schema#"
24+
}

0 commit comments

Comments
 (0)