Removed duplicate clients in user client lists.

Change-Id: If9806e5a2f98153b1428498f74c5bded989b7d70
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
index 444659e..7bde510 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
@@ -11,7 +11,7 @@
 import javax.persistence.TypedQuery;
 import javax.persistence.criteria.CriteriaBuilder;
 import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.ListJoin;
+import javax.persistence.criteria.Join;
 import javax.persistence.criteria.Predicate;
 import javax.persistence.criteria.Root;
 
@@ -116,7 +116,7 @@
                 builder.createQuery(OAuth2Client.class);
 
         Root<OAuth2Client> client = query.from(OAuth2Client.class);
-        ListJoin<OAuth2Client, RefreshToken> refreshToken =
+        Join<OAuth2Client, RefreshToken> refreshToken =
                 client.join(OAuth2Client_.refreshTokens);
         Predicate condition = builder.and(
                 builder.equal(refreshToken.get(RefreshToken_.userId), username),
@@ -128,6 +128,7 @@
                                 .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE))));
         query.select(client);
         query.where(condition);
+        query.distinct(true);
         TypedQuery<OAuth2Client> q = entityManager.createQuery(query);
         return q.getResultList();
     }
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
index 23b8267..f1e4de0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
@@ -346,11 +346,6 @@
         return clientDao.retrieveClientById(clientId);
     }
 
-    public List<OAuth2Client> retrieveUserClients (String username)
-            throws KustvaktException {
-        return clientDao.retrieveUserClients(username);
-    }
-
     public List<OAuth2UserClientDto> listUserClients (String username,
             String clientId, String clientSecret) throws KustvaktException {
         OAuth2Client client = authenticateClient(clientId, clientSecret);
@@ -359,9 +354,10 @@
                     "Only super client is allowed to list user clients.",
                     OAuth2Error.UNAUTHORIZED_CLIENT);
         }
-        List<OAuth2Client> userClients = retrieveUserClients(username);
+        List<OAuth2Client> userClients =
+                clientDao.retrieveUserClients(username);
         Collections.sort(userClients);
-        
+
         List<OAuth2UserClientDto> dtoList = new ArrayList<>(userClients.size());
         for (OAuth2Client uc : userClients) {
             if (uc.isSuper()) continue;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
index 02b190f..38e7474 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
@@ -229,10 +229,12 @@
     }
 
     /**
-     * Lists user clients having refresh tokens. This service is not
-     * part of the OAuth2 specification. It is intended to facilitate
-     * users revoking any suspicious and misused access or refresh
-     * tokens.
+     * Lists user clients having active refresh tokens (not revoked,
+     * not expired), except super clients.
+     * 
+     * This service is not part of the OAuth2 specification. It is
+     * intended to facilitate users revoking any suspicious and
+     * misused access or refresh tokens.
      * 
      * Only super clients are allowed to use this service. It requires
      * user and client authentications.
diff --git a/full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql b/full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql
index 01e5099..e11625b 100644
--- a/full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql
+++ b/full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql
@@ -34,20 +34,25 @@
 VALUES ("8bIDtZnH6NvRkW2Fq","third party client",null,
   "PUBLIC", 0, -2137275617,
   "https://third.party.client.com/redirect","system",
-  "This is a test nonsuper public client.");
+  "This is a test public client.");
 
   
 INSERT INTO oauth2_client_url(url,url_hashcode)
 VALUES("http://korap.ids-mannheim.de/public", 1360724310); 
   
---INSERT INTO oauth2_client(id,name,secret,type,super,url_id,
---  redirect_uri, registered_by, description) 
---VALUES ("iBr3LsTCxOj7D2o0A5m","test public client",null,
---  "PUBLIC", 1, 1360724310,
---  "https://korap.ids-mannheim.de/public/redirect","system", 
---  "This is a test super public client."); 
+INSERT INTO oauth2_client(id,name,secret,type,super,url_id,
+  redirect_uri, registered_by, description) 
+VALUES ("nW5qM63Rb2a7KdT9L","test public client",null,
+  "PUBLIC", 0, 1360724310,
+  "https://korap.ids-mannheim.de/public/redirect","system", 
+  "This is a test super public client."); 
 
 INSERT INTO oauth2_access_token(token,user_id,created_date, 
 expiry_date, user_auth_time)
 VALUES("fia0123ikBWn931470H8s5gRqx7Moc4p","marlin","2018-05-30 16:25:50", 
 "2018-05-31 16:25:50", "2018-05-30 16:23:10");
+
+INSERT INTO oauth2_refresh_token(token,user_id,user_auth_time, 
+created_date, expiry_date, client)
+VALUES("js9iQ4lw1Ri7fz06l0dXl8fCVp3Yn7vmq8","pearl","2017-05-30 16:25:50", 
+"2017-05-31 16:26:35", "1527784020000", "nW5qM63Rb2a7KdT9L");
diff --git a/full/src/main/resources/db/sqlite/V1.4__oauth2_tables.sql b/full/src/main/resources/db/sqlite/V1.4__oauth2_tables.sql
index fe0123c..863c31f 100644
--- a/full/src/main/resources/db/sqlite/V1.4__oauth2_tables.sql
+++ b/full/src/main/resources/db/sqlite/V1.4__oauth2_tables.sql
@@ -65,7 +65,7 @@
 	created_date TIMESTAMP NOT NULL,
 	expiry_date TIMESTAMP NULL,
 	is_revoked BOOLEAN DEFAULT 0,
-	client VARCHAR(100) DEFAULT NULL,
+	client VARCHAR(100) NOT NULL,
 	FOREIGN KEY (client)
 	   REFERENCES oauth2_client(id)
 );
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
index a87e83b..a373b72 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
@@ -442,6 +442,27 @@
                 node.at("/errors/0/1").asText());
     }
 
+    private void requestUserClientList () throws KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+        form.add("client_id", superClientId);
+        form.add("client_secret", clientSecret);
+
+        ClientResponse response = resource().path(API_VERSION).path("oauth2")
+                .path("client").path("list")
+                .header(Attributes.AUTHORIZATION, userAuthHeader)
+                .header(HttpHeaders.CONTENT_TYPE,
+                        ContentType.APPLICATION_FORM_URLENCODED)
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.OK.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertEquals(2, node.size());
+        assertEquals(confidentialClientId, node.at("/0/clientId").asText());
+        assertEquals(publicClientId, node.at("/1/clientId").asText());
+    }
+
     @Test
     public void testListUserClients () throws KustvaktException {
         String username = "pearl";
@@ -468,24 +489,21 @@
                 confidentialClientId, clientSecret, code);
         assertEquals(Status.OK.getStatusCode(), response.getStatus());
 
-        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
-        form.add("client_id", superClientId);
-        form.add("client_secret", clientSecret);
+        requestUserClientList();
+        testListClientWithMultipleRefreshTokens();
+    }
 
-        response = resource().path(API_VERSION).path("oauth2").path("client")
-                .path("list").header(Attributes.AUTHORIZATION, userAuthHeader)
-                .header(HttpHeaders.CONTENT_TYPE,
-                        ContentType.APPLICATION_FORM_URLENCODED)
-                .entity(form).post(ClientResponse.class);
+    private void testListClientWithMultipleRefreshTokens ()
+            throws KustvaktException {
+        // client 1
+        String code = requestAuthorizationCode(publicClientId, clientSecret,
+                null, userAuthHeader);
+        ClientResponse response = requestTokenWithAuthorizationCodeAndForm(
+                publicClientId, "", code);
 
         assertEquals(Status.OK.getStatusCode(), response.getStatus());
-        
-        String entity = response.getEntity(String.class);
-        JsonNode node = JsonUtils.readTree(entity);
-        
-        assertEquals(2, node.size());
-        assertEquals(confidentialClientId, node.at("/0/clientId").asText());
-        assertEquals(publicClientId, node.at("/1/clientId").asText());
+
+        requestUserClientList();
     }
 
 }