Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Djw api #15 add new users keycloak #18

Merged
merged 7 commits into from
Feb 1, 2024
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies {
// implementation("io.quarkiverse.helm:quarkus-helm:0.1.2")

implementation("io.quarkus:quarkus-arc")
implementation("io.quarkus:quarkus-keycloak-admin-client-reactive")
implementation("io.quarkus:quarkus-resteasy-reactive-jackson")
testImplementation("io.rest-assured:rest-assured")
testImplementation("io.quarkus:quarkus-test-security-oidc")
Expand Down
56 changes: 56 additions & 0 deletions src/main/java/org/orph2020/pst/apiimpl/rest/KeycloakResource.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package org.orph2020.pst.apiimpl.rest;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;

import java.util.List;

@Path("admin")
public class KeycloakResource {

Keycloak keycloak;

@ConfigProperty(name = "keycloak.admin-username")
String admin_username;

@ConfigProperty(name = "keycloak.admin-password")
String admin_password;

@PostConstruct
public void initKeyCloak() {
keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:53536")
.realm("master")
.clientId("admin-cli")
.grantType("password")
.username(admin_username)
.password(admin_password)
.build();
}

@PreDestroy
public void closeKeycloak() {
keycloak.close();
}


@GET
@Path("/roles")
public List<RoleRepresentation> getRoles() {
return keycloak.realm("orppst").roles().list();
}

@GET
@Path("/userRepresentations")
public List<UserRepresentation> getUserRepresentation() {
return keycloak.realm("orppst").users().list();
}

}
17 changes: 17 additions & 0 deletions src/main/java/org/orph2020/pst/apiimpl/rest/PersonResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.ivoa.dm.proposal.prop.Person;
import org.ivoa.dm.ivoa.StringIdentifier ;
import org.jboss.resteasy.reactive.RestQuery;
import org.orph2020.pst.apiimpl.entities.SubjectMap;
import org.orph2020.pst.common.json.ObjectIdentifier;

import jakarta.transaction.Transactional;
Expand Down Expand Up @@ -48,6 +49,22 @@ public Person createPerson(Person person)
return persistObject(person);
}

@POST
@Path("{keycloakUid}")
@Operation(summary = "create a new Person in the database from a keycloak 'user'")
@Consumes(MediaType.APPLICATION_JSON)
@Transactional(rollbackOn = {WebApplicationException.class})
public Person createPersonFromKeycloak(@PathParam("keycloakUid") String kcUid, Person person)
throws WebApplicationException
{
Person result = persistObject(person);

//store the user's keycloak UID
em.persist(new SubjectMap(person, kcUid));

return result;
}

@DELETE
@Path("{id}")
@Operation(summary = "delete the Person specified by the 'id' from the database")
Expand Down
171 changes: 171 additions & 0 deletions src/main/java/org/orph2020/pst/apiimpl/rest/SubjectMapResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,109 @@
* Created on 13/04/2023 by Paul Harrison (paul.harrison@manchester.ac.uk).
*/

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.ivoa.dm.ivoa.StringIdentifier;
import org.ivoa.dm.proposal.prop.Organization;
import org.ivoa.dm.proposal.prop.Person;
import org.jboss.resteasy.reactive.RestQuery;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.UserRepresentation;
import org.orph2020.pst.apiimpl.entities.SubjectMap;

import jakarta.persistence.TypedQuery;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Path("subjectMap")
@Tag(name="mapping between AAI user ids and People")
@Produces(MediaType.APPLICATION_JSON)
public class SubjectMapResource extends ObjectResourceBase {

Keycloak keycloak;

RealmResource realm;

@ConfigProperty(name = "keycloak.admin-username")
String admin_username;

@ConfigProperty(name = "keycloak.admin-password")
String admin_password;

@PostConstruct
public void initKeyCloak() {
keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:53536")
.realm("master")
.clientId("admin-cli")
.grantType("password")
.username(admin_username)
.password(admin_password)
.build();

realm = keycloak.realm("orppst");
}

@PreDestroy
public void closeKeycloak() {
keycloak.close();
}


@GET
@Operation(summary = "get a list of the SubjectMaps stored in the database, optionally provide a 'uid' to get that specific SubjectMap")
public List<SubjectMap> subjectMapList(@RestQuery String uid) {

String selectStr = "select o from SubjectMap o";
String uidSearchStr = uid != null ? " where o.uid = :uid" : "";

TypedQuery<SubjectMap> q = em.createQuery(
selectStr + uidSearchStr, SubjectMap.class
);

if (uid != null) {
q.setParameter("uid", uid);
}

List<SubjectMap> usersInDB = q.getResultList();

//list all users in the keycloak realm
List<UserRepresentation> usersInRealm = realm.users().list();

//deal with superuser
usersInRealm.removeIf(ur->ur.getUsername().equals("superuser"));

if (usersInDB.size() > usersInRealm.size())
{
int diff = usersInDB.size() - usersInRealm.size();
int count = 0;

// we have people in DB that are not in the keycloak realm,
// find which ones and take appropriate action
for(SubjectMap sm : usersInDB)
{
if (usersInRealm.stream().noneMatch(ur -> sm.uid.equals(ur.getId())))
{
sm.setInKeycloakRealm(false);
count++;
}
if (count == diff) break;
}
}

return usersInDB;
}

@GET
@Path("{id}")
@Operation(summary = "get the SubjectMap specified by the 'id'")
Expand All @@ -31,7 +120,89 @@ public SubjectMap subjectMap(@PathParam("id") String id)
else {
return res.get(0);
}
}

@GET
@Path("keycloakUserUIDs")
@Operation(summary = "get the unique IDs of existing keycloak realm users")
public List<String> existingUserUIDs()
{
List<UserRepresentation> userRepresentations = realm.users().list();

return userRepresentations
.stream()
.map(UserRepresentation::getId)
.collect(Collectors.toList());
}


@GET
@Path("newUsers")
@Operation(summary = "checks for new users, adds them as a Person if found, returns the number of new users found")
@Transactional(rollbackOn = {WebApplicationException.class})
public Integer checkForNewUsers()
throws WebApplicationException
{
AtomicReference<Integer> result = new AtomicReference<>(0);

List<UserRepresentation> userRepresentations = realm.users().list();

userRepresentations.forEach((ur) -> {
TypedQuery<SubjectMap> q = em.createQuery(
"select o from SubjectMap o where o.uid = :uid", SubjectMap.class
);
q.setParameter("uid", ur.getId());
List<SubjectMap> res = q.getResultList();

//notice "superuser" should not be used
if (res.isEmpty() && !ur.getUsername().equals("superuser")) {
//new user

//fixme: organisation details
Organization organization = findObject(Organization.class, 1L);

Person newPerson = persistObject(
new Person( ur.getFirstName() + " " + ur.getLastName(),
ur.getEmail(),
new StringIdentifier(""), //fixme: orchid id
organization
)
);

persistObject(new SubjectMap(newPerson, ur.getId()));

result.getAndSet(result.get() + 1);

} // else user exists as a Person, do nothing
});

return result.get();
}

@DELETE
@Path("cleanUsers")
@Operation(summary = "admin only: cleans up users that have been removed from the keycloak realm")
@Transactional(rollbackOn = {WebApplicationException.class})
public Response cleanUsers()
throws WebApplicationException
{
//query to get all SubjectMap objects in DB
TypedQuery<SubjectMap> q = em.createQuery(
"select o from SubjectMap o", SubjectMap.class
);
List<SubjectMap> usersInDB = q.getResultList();

for (SubjectMap subjectMap : usersInDB) {
if (!subjectMap.inKeycloak()) {
//remove the current SubjectMap AND related Person
Person person = findObject(Person.class, subjectMap.getPerson().getId());
em.remove(person);
em.remove(subjectMap);
}
}

return emptyResponse204();
}


}
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ quarkus.oidc.credentials.secret=eLt4izrWhxRftFTWTIcMbQsYlbyhfZtU
quarkus.oidc.roles.source=accesstoken
quarkus.oidc.application-type=service

#fixme we should have these in a 'secrets' file, here for convenience for the Java gradle CI
keycloak.admin-username="admin"
keycloak.admin-password="admin"

#k8 related
#should be picked up from name
quarkus.helm.name=pst-api-service
Expand Down
Loading