Browse Source

Small refactoring

pull/14074/head
Andrii Landiak 12 months ago
parent
commit
11199d347b
  1. 2
      application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
  2. 2
      application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationProvider.java
  3. 2
      application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
  4. 18
      application/src/test/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationProviderTest.java
  5. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/pat/ApiKeyService.java
  6. 12
      common/data/src/main/java/org/thingsboard/server/common/data/pat/ApiKey.java
  7. 2
      dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java
  8. 10
      dao/src/main/java/org/thingsboard/server/dao/model/sql/ApiKeyEntity.java
  9. 4
      dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyDao.java
  10. 10
      dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java
  11. 2
      dao/src/main/java/org/thingsboard/server/dao/sql/pat/ApiKeyRepository.java
  12. 4
      dao/src/main/java/org/thingsboard/server/dao/sql/pat/JpaApiKeyDao.java
  13. 2
      dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java
  14. 2
      dao/src/main/resources/sql/schema-entities-idx.sql
  15. 2
      dao/src/main/resources/sql/schema-entities.sql
  16. 12
      dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java

2
application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java

@ -74,7 +74,7 @@ public class ApiKeyController extends BaseController {
apiKeyInfo.setTenantId(securityUser.getTenantId());
checkEntity(apiKeyInfo.getId(), apiKeyInfo, Resource.API_KEY);
ApiKey savedApiKey = checkNotNull(apiKeyService.saveApiKey(securityUser.getTenantId(), apiKeyInfo));
savedApiKey.setHash(toUserApiKey(savedApiKey.getHash()));
savedApiKey.setValue(toUserApiKey(savedApiKey.getValue()));
return savedApiKey;
}

2
application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationProvider.java

@ -59,7 +59,7 @@ public class ApiKeyAuthenticationProvider implements org.springframework.securit
if (StringUtils.isEmpty(key)) {
throw new BadCredentialsException("Empty API key");
}
ApiKey apiKey = apiKeyService.findApiKeyByHash(key);
ApiKey apiKey = apiKeyService.findApiKeyByValue(key);
if (apiKey == null) {
throw new BadCredentialsException("User not found for the provided API key");
}

2
application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java

@ -42,7 +42,7 @@ public class ApiKeyControllerTest extends AbstractControllerTest {
public void testSaveApiKey() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("New API key description", true);
String apiKeyStr = doPost("/api/apiKey", apiKeyInfo, ApiKey.class).getHash();
String apiKeyStr = doPost("/api/apiKey", apiKeyInfo, ApiKey.class).getValue();
Assert.assertTrue(apiKeyStr.startsWith(API_KEY_HEADER_PREFIX));
PageData<ApiKeyInfo> pageData = doGetTypedWithPageLink("/api/apiKeys/" + tenantAdminUserId + "?", new TypeReference<>() {}, new PageLink(10, 0));

18
application/src/test/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationProviderTest.java

@ -83,14 +83,14 @@ public class ApiKeyAuthenticationProviderTest {
apiKey.setId(new ApiKeyId(UUID.randomUUID()));
apiKey.setTenantId(tenantId);
apiKey.setUserId(userId);
apiKey.setHash(TEST_API_KEY);
apiKey.setValue(TEST_API_KEY);
apiKey.setEnabled(true);
apiKey.setExpirationTime(0);
}
@Test
public void testSuccessfulAuthentication() {
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
when(userService.findUserById(tenantId, userId)).thenReturn(user);
when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(userCredentials);
@ -117,7 +117,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = BadCredentialsException.class)
public void testNonExistentApiKey() {
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(null);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(null);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
provider.authenticate(token);
@ -126,7 +126,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = DisabledException.class)
public void testDisabledApiKey() {
apiKey.setEnabled(false);
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
provider.authenticate(token);
@ -135,7 +135,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = CredentialsExpiredException.class)
public void testExpiredApiKey() {
apiKey.setExpirationTime(System.currentTimeMillis() - 10000); // Expired 10 seconds ago
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
provider.authenticate(token);
@ -143,7 +143,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = UsernameNotFoundException.class)
public void testNonExistentUser() {
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
when(userService.findUserById(tenantId, userId)).thenReturn(null);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
@ -152,7 +152,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = UsernameNotFoundException.class)
public void testNonExistentUserCredentials() {
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
when(userService.findUserById(tenantId, userId)).thenReturn(user);
when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(null);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
@ -163,7 +163,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = DisabledException.class)
public void testDisabledUser() {
userCredentials.setEnabled(false);
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
when(userService.findUserById(tenantId, userId)).thenReturn(user);
when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(userCredentials);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));
@ -174,7 +174,7 @@ public class ApiKeyAuthenticationProviderTest {
@Test(expected = InsufficientAuthenticationException.class)
public void testUserWithoutAuthority() {
user.setAuthority(null);
when(apiKeyService.findApiKeyByHash(TEST_API_KEY)).thenReturn(apiKey);
when(apiKeyService.findApiKeyByValue(TEST_API_KEY)).thenReturn(apiKey);
when(userService.findUserById(tenantId, userId)).thenReturn(user);
when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(userCredentials);
ApiKeyAuthenticationToken token = new ApiKeyAuthenticationToken(new RawApiKeyToken(TEST_API_KEY));

2
common/dao-api/src/main/java/org/thingsboard/server/dao/pat/ApiKeyService.java

@ -32,7 +32,7 @@ public interface ApiKeyService extends EntityDaoService {
void deleteByUserId(TenantId tenantId, UserId userId);
ApiKey findApiKeyByHash(String hash);
ApiKey findApiKeyByValue(String value);
ApiKey findApiKeyById(TenantId tenantId, ApiKeyId apiKeyId);

12
common/data/src/main/java/org/thingsboard/server/common/data/pat/ApiKey.java

@ -32,8 +32,8 @@ public class ApiKey extends ApiKeyInfo {
private static final long serialVersionUID = -2313196723950490263L;
@NoXss
@Schema(description = "Api key hash value", requiredMode = Schema.RequiredMode.REQUIRED)
private String hash;
@Schema(description = "Api key value", requiredMode = Schema.RequiredMode.REQUIRED)
private String value;
public ApiKey() {
super();
@ -45,17 +45,17 @@ public class ApiKey extends ApiKeyInfo {
public ApiKey(ApiKey apiKey) {
super(apiKey);
this.hash = apiKey.getHash();
this.value = apiKey.getValue();
}
public ApiKey(ApiKeyInfo apiKeyInfo) {
super(apiKeyInfo);
this.hash = null;
this.value = null;
}
public ApiKey(ApiKeyInfo apiKeyInfo, String hash) {
public ApiKey(ApiKeyInfo apiKeyInfo, String value) {
super(apiKeyInfo);
this.hash = hash;
this.value = value;
}
}

2
dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java

@ -766,7 +766,7 @@ public class ModelConstants {
public static final String API_KEY_TABLE_NAME = "api_key";
public static final String API_KEY_TENANT_ID_COLUMN_NAME = TENANT_ID_COLUMN;
public static final String API_KEY_USER_ID_COLUMN_NAME = USER_ID_PROPERTY;
public static final String API_KEY_HASH_COLUMN_NAME = "hash";
public static final String API_KEY_VALUE_COLUMN_NAME = "value";
public static final String API_KEY_EXPIRATION_TIME_COLUMN_NAME = "expiration_time";
public static final String API_KEY_ENABLED_COLUMN_NAME = "enabled";
public static final String API_KEY_DESCRIPTION_COLUMN_NAME = "description";

10
dao/src/main/java/org/thingsboard/server/dao/model/sql/ApiKeyEntity.java

@ -22,8 +22,8 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.pat.ApiKey;
import static org.thingsboard.server.dao.model.ModelConstants.API_KEY_HASH_COLUMN_NAME;
import static org.thingsboard.server.dao.model.ModelConstants.API_KEY_TABLE_NAME;
import static org.thingsboard.server.dao.model.ModelConstants.API_KEY_VALUE_COLUMN_NAME;
@Data
@EqualsAndHashCode(callSuper = true)
@ -31,8 +31,8 @@ import static org.thingsboard.server.dao.model.ModelConstants.API_KEY_TABLE_NAME
@Table(name = API_KEY_TABLE_NAME)
public class ApiKeyEntity extends AbstractApiKeyInfoEntity<ApiKey> {
@Column(name = API_KEY_HASH_COLUMN_NAME)
private String hash;
@Column(name = API_KEY_VALUE_COLUMN_NAME)
private String value;
public ApiKeyEntity() {
super();
@ -40,12 +40,12 @@ public class ApiKeyEntity extends AbstractApiKeyInfoEntity<ApiKey> {
public ApiKeyEntity(ApiKey apiKey) {
super(apiKey);
this.hash = apiKey.getHash();
this.value = apiKey.getValue();
}
@Override
public ApiKey toData() {
return new ApiKey(super.toApiKeyInfo(), hash);
return new ApiKey(super.toApiKeyInfo(), value);
}
}

4
dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyDao.java

@ -20,11 +20,9 @@ import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.pat.ApiKey;
import org.thingsboard.server.dao.Dao;
import java.util.Set;
public interface ApiKeyDao extends Dao<ApiKey> {
ApiKey findByHash(String hash);
ApiKey findByValue(String value);
void deleteByTenantId(TenantId tenantId);

10
dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java

@ -59,9 +59,9 @@ public class ApiKeyServiceImpl extends AbstractEntityService implements ApiKeySe
var old = apiKeyValidator.validate(apiKey, ApiKeyInfo::getTenantId);
if (old == null) {
String hash = generateApiKeySecret();
apiKey.setHash(hash);
apiKey.setValue(hash);
} else {
apiKey.setHash(old.getHash());
apiKey.setValue(old.getValue());
}
return apiKeyDao.save(tenantId, apiKey);
} catch (Exception e) {
@ -124,9 +124,9 @@ public class ApiKeyServiceImpl extends AbstractEntityService implements ApiKeySe
}
@Override
public ApiKey findApiKeyByHash(String hash) {
log.trace("Executing findApiKeyByHash [{}]", hash);
return apiKeyDao.findByHash(hash);
public ApiKey findApiKeyByValue(String value) {
log.trace("Executing findApiKeyByValue [{}]", value);
return apiKeyDao.findByValue(value);
}
private static String generateApiKeySecret() {

2
dao/src/main/java/org/thingsboard/server/dao/sql/pat/ApiKeyRepository.java

@ -26,7 +26,7 @@ import java.util.UUID;
public interface ApiKeyRepository extends JpaRepository<ApiKeyEntity, UUID> {
ApiKeyEntity findByHash(String hash);
ApiKeyEntity findByValue(String value);
@Transactional
@Modifying

4
dao/src/main/java/org/thingsboard/server/dao/sql/pat/JpaApiKeyDao.java

@ -41,8 +41,8 @@ public class JpaApiKeyDao extends JpaAbstractDao<ApiKeyEntity, ApiKey> implement
private ApiKeyRepository apiKeyRepository;
@Override
public ApiKey findByHash(String hash) {
return DaoUtil.getData(apiKeyRepository.findByHash(hash));
public ApiKey findByValue(String value) {
return DaoUtil.getData(apiKeyRepository.findByValue(value));
}
@Override

2
dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java

@ -179,7 +179,7 @@ public class TenantServiceImpl extends AbstractCachedEntityService<TenantId, Ten
EntityType.NOTIFICATION_REQUEST, EntityType.NOTIFICATION_RULE, EntityType.NOTIFICATION_TEMPLATE,
EntityType.NOTIFICATION_TARGET, EntityType.QUEUE_STATS, EntityType.CUSTOMER,
EntityType.DOMAIN, EntityType.MOBILE_APP_BUNDLE, EntityType.MOBILE_APP, EntityType.OAUTH2_CLIENT,
EntityType.AI_MODEL, EntityType.API_KEY
EntityType.AI_MODEL
);
}

2
dao/src/main/resources/sql/schema-entities-idx.sql

@ -116,4 +116,4 @@ CREATE INDEX IF NOT EXISTS idx_job_tenant_id ON job(tenant_id);
CREATE INDEX IF NOT EXISTS idx_ai_model_tenant_id ON ai_model(tenant_id);
CREATE INDEX IF NOT EXISTS idx_api_key_user_id ON api_key(user_id);
CREATE INDEX IF NOT EXISTS idx_api_key_value ON api_key(value);

2
dao/src/main/resources/sql/schema-entities.sql

@ -714,7 +714,7 @@ CREATE TABLE IF NOT EXISTS api_key (
created_time bigint NOT NULL,
tenant_id uuid,
user_id uuid,
hash varchar(255),
value varchar(255),
enabled boolean NOT NULL DEFAULT TRUE,
expiration_time bigint DEFAULT 0,
description varchar(1024),

12
dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java

@ -74,7 +74,7 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertEquals(tenantId, savedApiKey.getTenantId());
Assert.assertEquals(TEST_API_KEY_DESCRIPTION, savedApiKey.getDescription());
Assert.assertTrue(savedApiKey.isEnabled());
Assert.assertNotNull(savedApiKey.getHash());
Assert.assertNotNull(savedApiKey.getValue());
}
@Test
@ -87,7 +87,7 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertEquals(tenantId, savedApiKey.getTenantId());
Assert.assertNull(savedApiKey.getDescription());
Assert.assertTrue(savedApiKey.isEnabled());
Assert.assertNotNull(savedApiKey.getHash());
Assert.assertNotNull(savedApiKey.getValue());
}
@Test
@ -111,7 +111,7 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertNotNull(updatedApiKey);
Assert.assertEquals(savedApiKey.getId(), updatedApiKey.getId());
Assert.assertEquals(newDescription, updatedApiKey.getDescription());
Assert.assertEquals(savedApiKey.getHash(), updatedApiKey.getHash());
Assert.assertEquals(savedApiKey.getValue(), updatedApiKey.getValue());
}
@Test
@ -138,7 +138,7 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertEquals(savedApiKey.getId(), foundApiKey.getId());
Assert.assertEquals(savedApiKey.getDescription(), foundApiKey.getDescription());
Assert.assertEquals(savedApiKey.isEnabled(), foundApiKey.isEnabled());
Assert.assertEquals(savedApiKey.getHash(), foundApiKey.getHash());
Assert.assertEquals(savedApiKey.getValue(), foundApiKey.getValue());
}
@Test
@ -146,13 +146,13 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION);
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo);
ApiKey foundApiKey = apiKeyService.findApiKeyByHash(savedApiKey.getHash());
ApiKey foundApiKey = apiKeyService.findApiKeyByValue(savedApiKey.getValue());
Assert.assertNotNull(foundApiKey);
Assert.assertEquals(savedApiKey.getId(), foundApiKey.getId());
Assert.assertEquals(savedApiKey.getDescription(), foundApiKey.getDescription());
Assert.assertEquals(savedApiKey.isEnabled(), foundApiKey.isEnabled());
Assert.assertEquals(savedApiKey.getHash(), foundApiKey.getHash());
Assert.assertEquals(savedApiKey.getValue(), foundApiKey.getValue());
}
@Test

Loading…
Cancel
Save