669 changed files with 5324 additions and 60566 deletions
@ -0,0 +1,90 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.PathVariable; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestMethod; |
||||
|
import org.springframework.web.bind.annotation.RequestParam; |
||||
|
import org.springframework.web.bind.annotation.ResponseBody; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.thingsboard.server.common.data.Resource; |
||||
|
import org.thingsboard.server.common.data.ResourceType; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.page.PageLink; |
||||
|
import org.thingsboard.server.dao.resource.ResourceService; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
|
||||
|
@Slf4j |
||||
|
@RestController |
||||
|
@TbCoreComponent |
||||
|
@RequestMapping("/api") |
||||
|
public class ResourceController extends BaseController { |
||||
|
|
||||
|
private final ResourceService resourceService; |
||||
|
|
||||
|
public ResourceController(ResourceService resourceService) { |
||||
|
this.resourceService = resourceService; |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") |
||||
|
@RequestMapping(value = "/resource", method = RequestMethod.POST) |
||||
|
@ResponseBody |
||||
|
public Resource saveResource(Resource resource) throws ThingsboardException { |
||||
|
try { |
||||
|
resource.setTenantId(getTenantId()); |
||||
|
Resource savedResource = checkNotNull(resourceService.saveResource(resource)); |
||||
|
tbClusterService.onResourceChange(savedResource, null); |
||||
|
return savedResource; |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") |
||||
|
@RequestMapping(value = "/resource", method = RequestMethod.GET) |
||||
|
@ResponseBody |
||||
|
public PageData<Resource> getResources(@RequestParam(required = false) boolean system, |
||||
|
@RequestParam int pageSize, |
||||
|
@RequestParam int page, |
||||
|
@RequestParam(required = false) String sortProperty, |
||||
|
@RequestParam(required = false) String sortOrder) throws ThingsboardException { |
||||
|
try { |
||||
|
PageLink pageLink = createPageLink(pageSize, page, null, sortProperty, sortOrder); |
||||
|
return checkNotNull(resourceService.findResourcesByTenantId(system ? TenantId.SYS_TENANT_ID : getTenantId(), pageLink)); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") |
||||
|
@RequestMapping(value = "/resource/{resourceType}/{resourceId}", method = RequestMethod.DELETE) |
||||
|
@ResponseBody |
||||
|
public void deleteResource(@PathVariable("resourceType") ResourceType resourceType, |
||||
|
@PathVariable("resourceId") String resourceId) throws ThingsboardException { |
||||
|
try { |
||||
|
Resource resource = checkNotNull(resourceService.getResource(getTenantId(), resourceType, resourceId)); |
||||
|
resourceService.deleteResource(getTenantId(), resourceType, resourceId); |
||||
|
tbClusterService.onResourceDeleted(resource, null); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,85 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.security.auth; |
||||
|
|
||||
|
import io.jsonwebtoken.Claims; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.cache.Cache; |
||||
|
import org.springframework.cache.CacheManager; |
||||
|
import org.springframework.context.event.EventListener; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.thingsboard.server.common.data.CacheConstants; |
||||
|
import org.thingsboard.server.common.data.id.UserId; |
||||
|
import org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent; |
||||
|
import org.thingsboard.server.common.data.security.model.JwtToken; |
||||
|
import org.thingsboard.server.config.JwtSettings; |
||||
|
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; |
||||
|
|
||||
|
import javax.annotation.PostConstruct; |
||||
|
import java.util.Optional; |
||||
|
|
||||
|
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
||||
|
import static java.util.concurrent.TimeUnit.SECONDS; |
||||
|
|
||||
|
@Service |
||||
|
@RequiredArgsConstructor |
||||
|
public class TokenOutdatingService { |
||||
|
private final CacheManager cacheManager; |
||||
|
private final JwtTokenFactory tokenFactory; |
||||
|
private final JwtSettings jwtSettings; |
||||
|
private Cache tokenOutdatageTimeCache; |
||||
|
|
||||
|
@PostConstruct |
||||
|
protected void initCache() { |
||||
|
tokenOutdatageTimeCache = cacheManager.getCache(CacheConstants.TOKEN_OUTDATAGE_TIME_CACHE); |
||||
|
} |
||||
|
|
||||
|
@EventListener(classes = UserAuthDataChangedEvent.class) |
||||
|
public void onUserAuthDataChanged(UserAuthDataChangedEvent userAuthDataChangedEvent) { |
||||
|
outdateOldUserTokens(userAuthDataChangedEvent.getUserId()); |
||||
|
} |
||||
|
|
||||
|
public boolean isOutdated(JwtToken token, UserId userId) { |
||||
|
Claims claims = tokenFactory.parseTokenClaims(token).getBody(); |
||||
|
long issueTime = claims.getIssuedAt().getTime(); |
||||
|
|
||||
|
return Optional.ofNullable(tokenOutdatageTimeCache.get(toKey(userId), Long.class)) |
||||
|
.map(outdatageTime -> { |
||||
|
if (System.currentTimeMillis() - outdatageTime <= SECONDS.toMillis(jwtSettings.getRefreshTokenExpTime())) { |
||||
|
return MILLISECONDS.toSeconds(issueTime) < MILLISECONDS.toSeconds(outdatageTime); |
||||
|
} else { |
||||
|
/* |
||||
|
* Means that since the outdating has passed more than |
||||
|
* the lifetime of refresh token (the longest lived) |
||||
|
* and there is no need to store outdatage time anymore |
||||
|
* as all the tokens issued before the outdatage time |
||||
|
* are now expired by themselves |
||||
|
* */ |
||||
|
tokenOutdatageTimeCache.evict(toKey(userId)); |
||||
|
return false; |
||||
|
} |
||||
|
}) |
||||
|
.orElse(false); |
||||
|
} |
||||
|
|
||||
|
public void outdateOldUserTokens(UserId userId) { |
||||
|
tokenOutdatageTimeCache.put(toKey(userId), System.currentTimeMillis()); |
||||
|
} |
||||
|
|
||||
|
private String toKey(UserId userId) { |
||||
|
return userId.getId().toString(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,72 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import org.springframework.util.SerializationUtils; |
||||
|
import javax.servlet.http.Cookie; |
||||
|
import javax.servlet.http.HttpServletRequest; |
||||
|
import javax.servlet.http.HttpServletResponse; |
||||
|
import java.util.Base64; |
||||
|
import java.util.Optional; |
||||
|
|
||||
|
public class CookieUtils { |
||||
|
|
||||
|
public static Optional<Cookie> getCookie(HttpServletRequest request, String name) { |
||||
|
Cookie[] cookies = request.getCookies(); |
||||
|
|
||||
|
if (cookies != null && cookies.length > 0) { |
||||
|
for (Cookie cookie : cookies) { |
||||
|
if (cookie.getName().equals(name)) { |
||||
|
return Optional.of(cookie); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return Optional.empty(); |
||||
|
} |
||||
|
|
||||
|
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { |
||||
|
Cookie cookie = new Cookie(name, value); |
||||
|
cookie.setPath("/"); |
||||
|
cookie.setHttpOnly(true); |
||||
|
cookie.setMaxAge(maxAge); |
||||
|
response.addCookie(cookie); |
||||
|
} |
||||
|
|
||||
|
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { |
||||
|
Cookie[] cookies = request.getCookies(); |
||||
|
if (cookies != null && cookies.length > 0) { |
||||
|
for (Cookie cookie: cookies) { |
||||
|
if (cookie.getName().equals(name)) { |
||||
|
cookie.setValue(""); |
||||
|
cookie.setPath("/"); |
||||
|
cookie.setMaxAge(0); |
||||
|
response.addCookie(cookie); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public static String serialize(Object object) { |
||||
|
return Base64.getUrlEncoder() |
||||
|
.encodeToString(SerializationUtils.serialize(object)); |
||||
|
} |
||||
|
|
||||
|
public static <T> T deserialize(Cookie cookie, Class<T> cls) { |
||||
|
return cls.cast(SerializationUtils.deserialize( |
||||
|
Base64.getUrlDecoder().decode(cookie.getValue()))); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,55 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; |
||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
import javax.servlet.http.HttpServletRequest; |
||||
|
import javax.servlet.http.HttpServletResponse; |
||||
|
|
||||
|
@Component |
||||
|
public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> { |
||||
|
public static final String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request"; |
||||
|
private static final int cookieExpireSeconds = 180; |
||||
|
|
||||
|
@Override |
||||
|
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { |
||||
|
return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME) |
||||
|
.map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class)) |
||||
|
.orElse(null); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { |
||||
|
if (authorizationRequest == null) { |
||||
|
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); |
||||
|
return; |
||||
|
} |
||||
|
CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds); |
||||
|
} |
||||
|
|
||||
|
@SuppressWarnings("deprecation") |
||||
|
@Override |
||||
|
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) { |
||||
|
return this.loadAuthorizationRequest(request); |
||||
|
} |
||||
|
|
||||
|
public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) { |
||||
|
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,315 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.subscription; |
||||
|
|
||||
|
import com.google.common.util.concurrent.Futures; |
||||
|
import com.google.common.util.concurrent.ListenableFuture; |
||||
|
import com.google.common.util.concurrent.MoreExecutors; |
||||
|
import lombok.Data; |
||||
|
import lombok.Getter; |
||||
|
import lombok.Setter; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.EntityId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.id.UserId; |
||||
|
import org.thingsboard.server.common.data.kv.AttributeKvEntry; |
||||
|
import org.thingsboard.server.common.data.query.ComplexFilterPredicate; |
||||
|
import org.thingsboard.server.common.data.query.DynamicValue; |
||||
|
import org.thingsboard.server.common.data.query.DynamicValueSourceType; |
||||
|
import org.thingsboard.server.common.data.query.EntityCountQuery; |
||||
|
import org.thingsboard.server.common.data.query.EntityKeyType; |
||||
|
import org.thingsboard.server.common.data.query.FilterPredicateType; |
||||
|
import org.thingsboard.server.common.data.query.KeyFilter; |
||||
|
import org.thingsboard.server.common.data.query.KeyFilterPredicate; |
||||
|
import org.thingsboard.server.common.data.query.SimpleKeyFilterPredicate; |
||||
|
import org.thingsboard.server.common.data.query.TsValue; |
||||
|
import org.thingsboard.server.dao.attributes.AttributesService; |
||||
|
import org.thingsboard.server.dao.entity.EntityService; |
||||
|
import org.thingsboard.server.service.telemetry.TelemetryWebSocketService; |
||||
|
import org.thingsboard.server.service.telemetry.TelemetryWebSocketSessionRef; |
||||
|
import org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate; |
||||
|
|
||||
|
import java.util.ArrayList; |
||||
|
import java.util.HashMap; |
||||
|
import java.util.List; |
||||
|
import java.util.Map; |
||||
|
import java.util.Optional; |
||||
|
import java.util.Set; |
||||
|
import java.util.concurrent.ConcurrentHashMap; |
||||
|
import java.util.concurrent.ExecutionException; |
||||
|
import java.util.concurrent.ScheduledFuture; |
||||
|
|
||||
|
@Slf4j |
||||
|
@Data |
||||
|
public abstract class TbAbstractSubCtx<T extends EntityCountQuery> { |
||||
|
|
||||
|
protected final String serviceId; |
||||
|
protected final SubscriptionServiceStatistics stats; |
||||
|
protected final TelemetryWebSocketService wsService; |
||||
|
protected final EntityService entityService; |
||||
|
protected final TbLocalSubscriptionService localSubscriptionService; |
||||
|
protected final AttributesService attributesService; |
||||
|
protected final TelemetryWebSocketSessionRef sessionRef; |
||||
|
protected final int cmdId; |
||||
|
protected final Set<Integer> subToDynamicValueKeySet; |
||||
|
@Getter |
||||
|
protected final Map<DynamicValueKey, List<DynamicValue>> dynamicValues; |
||||
|
@Getter |
||||
|
@Setter |
||||
|
protected T query; |
||||
|
@Setter |
||||
|
protected volatile ScheduledFuture<?> refreshTask; |
||||
|
|
||||
|
public TbAbstractSubCtx(String serviceId, TelemetryWebSocketService wsService, |
||||
|
EntityService entityService, TbLocalSubscriptionService localSubscriptionService, |
||||
|
AttributesService attributesService, SubscriptionServiceStatistics stats, |
||||
|
TelemetryWebSocketSessionRef sessionRef, int cmdId) { |
||||
|
this.serviceId = serviceId; |
||||
|
this.wsService = wsService; |
||||
|
this.entityService = entityService; |
||||
|
this.localSubscriptionService = localSubscriptionService; |
||||
|
this.attributesService = attributesService; |
||||
|
this.stats = stats; |
||||
|
this.sessionRef = sessionRef; |
||||
|
this.cmdId = cmdId; |
||||
|
this.subToDynamicValueKeySet = ConcurrentHashMap.newKeySet(); |
||||
|
this.dynamicValues = new ConcurrentHashMap<>(); |
||||
|
} |
||||
|
|
||||
|
public void setAndResolveQuery(T query) { |
||||
|
dynamicValues.clear(); |
||||
|
this.query = query; |
||||
|
if (query != null && query.getKeyFilters() != null) { |
||||
|
for (KeyFilter filter : query.getKeyFilters()) { |
||||
|
registerDynamicValues(filter.getPredicate()); |
||||
|
} |
||||
|
} |
||||
|
resolve(getTenantId(), getCustomerId(), getUserId()); |
||||
|
} |
||||
|
|
||||
|
public void resolve(TenantId tenantId, CustomerId customerId, UserId userId) { |
||||
|
List<ListenableFuture<DynamicValueKeySub>> futures = new ArrayList<>(); |
||||
|
for (DynamicValueKey key : dynamicValues.keySet()) { |
||||
|
switch (key.getSourceType()) { |
||||
|
case CURRENT_TENANT: |
||||
|
futures.add(resolveEntityValue(tenantId, tenantId, key)); |
||||
|
break; |
||||
|
case CURRENT_CUSTOMER: |
||||
|
if (customerId != null && !customerId.isNullUid()) { |
||||
|
futures.add(resolveEntityValue(tenantId, customerId, key)); |
||||
|
} |
||||
|
break; |
||||
|
case CURRENT_USER: |
||||
|
if (userId != null && !userId.isNullUid()) { |
||||
|
futures.add(resolveEntityValue(tenantId, userId, key)); |
||||
|
} |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
try { |
||||
|
Map<EntityId, Map<String, DynamicValueKeySub>> tmpSubMap = new HashMap<>(); |
||||
|
for (DynamicValueKeySub sub : Futures.successfulAsList(futures).get()) { |
||||
|
tmpSubMap.computeIfAbsent(sub.getEntityId(), tmp -> new HashMap<>()).put(sub.getKey().getSourceAttribute(), sub); |
||||
|
} |
||||
|
for (EntityId entityId : tmpSubMap.keySet()) { |
||||
|
Map<String, Long> keyStates = new HashMap<>(); |
||||
|
Map<String, DynamicValueKeySub> dynamicValueKeySubMap = tmpSubMap.get(entityId); |
||||
|
dynamicValueKeySubMap.forEach((k, v) -> keyStates.put(k, v.getLastUpdateTs())); |
||||
|
int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet(); |
||||
|
TbAttributeSubscription sub = TbAttributeSubscription.builder() |
||||
|
.serviceId(serviceId) |
||||
|
.sessionId(sessionRef.getSessionId()) |
||||
|
.subscriptionId(subIdx) |
||||
|
.tenantId(sessionRef.getSecurityCtx().getTenantId()) |
||||
|
.entityId(entityId) |
||||
|
.updateConsumer((s, subscriptionUpdate) -> dynamicValueSubUpdate(s, subscriptionUpdate, dynamicValueKeySubMap)) |
||||
|
.allKeys(false) |
||||
|
.keyStates(keyStates) |
||||
|
.scope(TbAttributeSubscriptionScope.SERVER_SCOPE) |
||||
|
.build(); |
||||
|
subToDynamicValueKeySet.add(subIdx); |
||||
|
localSubscriptionService.addSubscription(sub); |
||||
|
} |
||||
|
} catch (InterruptedException | ExecutionException e) { |
||||
|
log.info("[{}][{}][{}] Failed to resolve dynamic values: {}", tenantId, customerId, userId, dynamicValues.keySet()); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
private void dynamicValueSubUpdate(String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, |
||||
|
Map<String, DynamicValueKeySub> dynamicValueKeySubMap) { |
||||
|
Map<String, TsValue> latestUpdate = new HashMap<>(); |
||||
|
subscriptionUpdate.getData().forEach((k, v) -> { |
||||
|
Object[] data = (Object[]) v.get(0); |
||||
|
latestUpdate.put(k, new TsValue((Long) data[0], (String) data[1])); |
||||
|
}); |
||||
|
|
||||
|
boolean invalidateFilter = false; |
||||
|
for (Map.Entry<String, TsValue> entry : latestUpdate.entrySet()) { |
||||
|
String k = entry.getKey(); |
||||
|
TsValue tsValue = entry.getValue(); |
||||
|
DynamicValueKeySub sub = dynamicValueKeySubMap.get(k); |
||||
|
if (sub.updateValue(tsValue)) { |
||||
|
invalidateFilter = true; |
||||
|
updateDynamicValuesByKey(sub, tsValue); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (invalidateFilter) { |
||||
|
update(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public abstract void fetchData(); |
||||
|
|
||||
|
protected abstract void update(); |
||||
|
|
||||
|
public void clearSubscriptions() { |
||||
|
clearDynamicValueSubscriptions(); |
||||
|
} |
||||
|
|
||||
|
@Data |
||||
|
private static class DynamicValueKeySub { |
||||
|
private final DynamicValueKey key; |
||||
|
private final EntityId entityId; |
||||
|
private long lastUpdateTs; |
||||
|
private String lastUpdateValue; |
||||
|
|
||||
|
boolean updateValue(TsValue value) { |
||||
|
if (value.getTs() > lastUpdateTs && (lastUpdateValue == null || !lastUpdateValue.equals(value.getValue()))) { |
||||
|
this.lastUpdateTs = value.getTs(); |
||||
|
this.lastUpdateValue = value.getValue(); |
||||
|
return true; |
||||
|
} else { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private ListenableFuture<DynamicValueKeySub> resolveEntityValue(TenantId tenantId, EntityId entityId, DynamicValueKey key) { |
||||
|
ListenableFuture<Optional<AttributeKvEntry>> entry = attributesService.find(tenantId, entityId, |
||||
|
TbAttributeSubscriptionScope.SERVER_SCOPE.name(), key.getSourceAttribute()); |
||||
|
return Futures.transform(entry, attributeOpt -> { |
||||
|
DynamicValueKeySub sub = new DynamicValueKeySub(key, entityId); |
||||
|
if (attributeOpt.isPresent()) { |
||||
|
AttributeKvEntry attribute = attributeOpt.get(); |
||||
|
sub.setLastUpdateTs(attribute.getLastUpdateTs()); |
||||
|
sub.setLastUpdateValue(attribute.getValueAsString()); |
||||
|
updateDynamicValuesByKey(sub, new TsValue(attribute.getLastUpdateTs(), attribute.getValueAsString())); |
||||
|
} |
||||
|
return sub; |
||||
|
}, MoreExecutors.directExecutor()); |
||||
|
} |
||||
|
|
||||
|
@SuppressWarnings("unchecked") |
||||
|
protected void updateDynamicValuesByKey(DynamicValueKeySub sub, TsValue tsValue) { |
||||
|
DynamicValueKey dvk = sub.getKey(); |
||||
|
switch (dvk.getPredicateType()) { |
||||
|
case STRING: |
||||
|
dynamicValues.get(dvk).forEach(dynamicValue -> dynamicValue.setResolvedValue(tsValue.getValue())); |
||||
|
break; |
||||
|
case NUMERIC: |
||||
|
try { |
||||
|
Double dValue = Double.parseDouble(tsValue.getValue()); |
||||
|
dynamicValues.get(dvk).forEach(dynamicValue -> dynamicValue.setResolvedValue(dValue)); |
||||
|
} catch (NumberFormatException e) { |
||||
|
dynamicValues.get(dvk).forEach(dynamicValue -> dynamicValue.setResolvedValue(null)); |
||||
|
} |
||||
|
break; |
||||
|
case BOOLEAN: |
||||
|
Boolean bValue = Boolean.parseBoolean(tsValue.getValue()); |
||||
|
dynamicValues.get(dvk).forEach(dynamicValue -> dynamicValue.setResolvedValue(bValue)); |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@SuppressWarnings("unchecked") |
||||
|
private void registerDynamicValues(KeyFilterPredicate predicate) { |
||||
|
switch (predicate.getType()) { |
||||
|
case STRING: |
||||
|
case NUMERIC: |
||||
|
case BOOLEAN: |
||||
|
Optional<DynamicValue> value = getDynamicValueFromSimplePredicate((SimpleKeyFilterPredicate) predicate); |
||||
|
if (value.isPresent()) { |
||||
|
DynamicValue dynamicValue = value.get(); |
||||
|
DynamicValueKey key = new DynamicValueKey( |
||||
|
predicate.getType(), |
||||
|
dynamicValue.getSourceType(), |
||||
|
dynamicValue.getSourceAttribute()); |
||||
|
dynamicValues.computeIfAbsent(key, tmp -> new ArrayList<>()).add(dynamicValue); |
||||
|
} |
||||
|
break; |
||||
|
case COMPLEX: |
||||
|
((ComplexFilterPredicate) predicate).getPredicates().forEach(this::registerDynamicValues); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private Optional<DynamicValue<T>> getDynamicValueFromSimplePredicate(SimpleKeyFilterPredicate<T> predicate) { |
||||
|
if (predicate.getValue().getUserValue() == null) { |
||||
|
return Optional.ofNullable(predicate.getValue().getDynamicValue()); |
||||
|
} else { |
||||
|
return Optional.empty(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public String getSessionId() { |
||||
|
return sessionRef.getSessionId(); |
||||
|
} |
||||
|
|
||||
|
public TenantId getTenantId() { |
||||
|
return sessionRef.getSecurityCtx().getTenantId(); |
||||
|
} |
||||
|
|
||||
|
public CustomerId getCustomerId() { |
||||
|
return sessionRef.getSecurityCtx().getCustomerId(); |
||||
|
} |
||||
|
|
||||
|
public UserId getUserId() { |
||||
|
return sessionRef.getSecurityCtx().getId(); |
||||
|
} |
||||
|
|
||||
|
protected void clearDynamicValueSubscriptions() { |
||||
|
if (subToDynamicValueKeySet != null) { |
||||
|
for (Integer subId : subToDynamicValueKeySet) { |
||||
|
localSubscriptionService.cancelSubscription(sessionRef.getSessionId(), subId); |
||||
|
} |
||||
|
subToDynamicValueKeySet.clear(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public void setRefreshTask(ScheduledFuture<?> task) { |
||||
|
this.refreshTask = task; |
||||
|
} |
||||
|
|
||||
|
public void cancelTasks() { |
||||
|
if (this.refreshTask != null) { |
||||
|
log.trace("[{}][{}] Canceling old refresh task", sessionRef.getSessionId(), cmdId); |
||||
|
this.refreshTask.cancel(true); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Data |
||||
|
public static class DynamicValueKey { |
||||
|
@Getter |
||||
|
private final FilterPredicateType predicateType; |
||||
|
@Getter |
||||
|
private final DynamicValueSourceType sourceType; |
||||
|
@Getter |
||||
|
private final String sourceAttribute; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,55 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.subscription; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.thingsboard.server.common.data.query.EntityCountQuery; |
||||
|
import org.thingsboard.server.common.data.query.EntityKeyType; |
||||
|
import org.thingsboard.server.dao.attributes.AttributesService; |
||||
|
import org.thingsboard.server.dao.entity.EntityService; |
||||
|
import org.thingsboard.server.service.telemetry.TelemetryWebSocketService; |
||||
|
import org.thingsboard.server.service.telemetry.TelemetryWebSocketSessionRef; |
||||
|
import org.thingsboard.server.service.telemetry.cmd.v2.EntityCountUpdate; |
||||
|
import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate; |
||||
|
import org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate; |
||||
|
|
||||
|
@Slf4j |
||||
|
public class TbEntityCountSubCtx extends TbAbstractSubCtx<EntityCountQuery> { |
||||
|
|
||||
|
private volatile int result; |
||||
|
|
||||
|
public TbEntityCountSubCtx(String serviceId, TelemetryWebSocketService wsService, EntityService entityService, |
||||
|
TbLocalSubscriptionService localSubscriptionService, AttributesService attributesService, |
||||
|
SubscriptionServiceStatistics stats, TelemetryWebSocketSessionRef sessionRef, int cmdId) { |
||||
|
super(serviceId, wsService, entityService, localSubscriptionService, attributesService, stats, sessionRef, cmdId); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void fetchData() { |
||||
|
result = (int) entityService.countEntitiesByQuery(getTenantId(), getCustomerId(), query); |
||||
|
wsService.sendWsMsg(sessionRef.getSessionId(), new EntityCountUpdate(cmdId, result)); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
protected void update() { |
||||
|
int newCount = (int) entityService.countEntitiesByQuery(getTenantId(), getCustomerId(), query); |
||||
|
if (newCount != result) { |
||||
|
result = newCount; |
||||
|
wsService.sendWsMsg(sessionRef.getSessionId(), new EntityCountUpdate(cmdId, result)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,33 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.telemetry.cmd.v2; |
||||
|
|
||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||
|
import lombok.AllArgsConstructor; |
||||
|
import lombok.Data; |
||||
|
|
||||
|
@Data |
||||
|
@AllArgsConstructor |
||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||
|
public abstract class CmdUpdate { |
||||
|
|
||||
|
private final int cmdId; |
||||
|
private final int errorCode; |
||||
|
private final String errorMsg; |
||||
|
|
||||
|
public abstract CmdUpdateType getCmdUpdateType(); |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,35 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.telemetry.cmd.v2; |
||||
|
|
||||
|
import com.fasterxml.jackson.annotation.JsonCreator; |
||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||
|
import lombok.Getter; |
||||
|
import org.thingsboard.server.common.data.query.EntityCountQuery; |
||||
|
import org.thingsboard.server.common.data.query.EntityDataQuery; |
||||
|
|
||||
|
public class EntityCountCmd extends DataCmd { |
||||
|
|
||||
|
@Getter |
||||
|
private final EntityCountQuery query; |
||||
|
|
||||
|
@JsonCreator |
||||
|
public EntityCountCmd(@JsonProperty("cmdId") int cmdId, |
||||
|
@JsonProperty("query") EntityCountQuery query) { |
||||
|
super(cmdId); |
||||
|
this.query = query; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,25 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.telemetry.cmd.v2; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
|
||||
|
@Data |
||||
|
public class EntityCountUnsubscribeCmd implements UnsubscribeCmd { |
||||
|
|
||||
|
private final int cmdId; |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,57 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.telemetry.cmd.v2; |
||||
|
|
||||
|
import com.fasterxml.jackson.annotation.JsonCreator; |
||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||
|
import lombok.Getter; |
||||
|
import lombok.ToString; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.query.EntityData; |
||||
|
import org.thingsboard.server.service.telemetry.sub.SubscriptionErrorCode; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
@ToString |
||||
|
public class EntityCountUpdate extends CmdUpdate { |
||||
|
|
||||
|
@Getter |
||||
|
private int count; |
||||
|
|
||||
|
public EntityCountUpdate(int cmdId, int count) { |
||||
|
super(cmdId, SubscriptionErrorCode.NO_ERROR.getCode(), null); |
||||
|
this.count = count; |
||||
|
} |
||||
|
|
||||
|
public EntityCountUpdate(int cmdId, int errorCode, String errorMsg) { |
||||
|
super(cmdId, errorCode, errorMsg); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public CmdUpdateType getCmdUpdateType() { |
||||
|
return CmdUpdateType.COUNT_DATA; |
||||
|
} |
||||
|
|
||||
|
@JsonCreator |
||||
|
public EntityCountUpdate(@JsonProperty("cmdId") int cmdId, |
||||
|
@JsonProperty("count") int count, |
||||
|
@JsonProperty("errorCode") int errorCode, |
||||
|
@JsonProperty("errorMsg") String errorMsg) { |
||||
|
super(cmdId, errorCode, errorMsg); |
||||
|
this.count = count; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,184 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.security.auth; |
||||
|
|
||||
|
import org.junit.jupiter.api.BeforeEach; |
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.springframework.cache.concurrent.ConcurrentMapCacheManager; |
||||
|
import org.springframework.security.authentication.CredentialsExpiredException; |
||||
|
import org.thingsboard.server.common.data.CacheConstants; |
||||
|
import org.thingsboard.server.common.data.User; |
||||
|
import org.thingsboard.server.common.data.id.UserId; |
||||
|
import org.thingsboard.server.common.data.security.Authority; |
||||
|
import org.thingsboard.server.common.data.security.UserCredentials; |
||||
|
import org.thingsboard.server.common.data.security.model.JwtToken; |
||||
|
import org.thingsboard.server.config.JwtSettings; |
||||
|
import org.thingsboard.server.dao.customer.CustomerService; |
||||
|
import org.thingsboard.server.dao.user.UserService; |
||||
|
import org.thingsboard.server.service.security.auth.jwt.JwtAuthenticationProvider; |
||||
|
import org.thingsboard.server.service.security.auth.jwt.RefreshTokenAuthenticationProvider; |
||||
|
import org.thingsboard.server.service.security.exception.JwtExpiredTokenException; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
import org.thingsboard.server.service.security.model.UserPrincipal; |
||||
|
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; |
||||
|
import org.thingsboard.server.service.security.model.token.RawAccessJwtToken; |
||||
|
|
||||
|
import java.util.UUID; |
||||
|
|
||||
|
import static java.util.concurrent.TimeUnit.DAYS; |
||||
|
import static java.util.concurrent.TimeUnit.MINUTES; |
||||
|
import static java.util.concurrent.TimeUnit.SECONDS; |
||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; |
||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull; |
||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
import static org.mockito.ArgumentMatchers.any; |
||||
|
import static org.mockito.ArgumentMatchers.eq; |
||||
|
import static org.mockito.Mockito.mock; |
||||
|
import static org.mockito.Mockito.when; |
||||
|
|
||||
|
public class TokenOutdatingTest { |
||||
|
private JwtAuthenticationProvider accessTokenAuthenticationProvider; |
||||
|
private RefreshTokenAuthenticationProvider refreshTokenAuthenticationProvider; |
||||
|
|
||||
|
private TokenOutdatingService tokenOutdatingService; |
||||
|
private ConcurrentMapCacheManager cacheManager; |
||||
|
private JwtTokenFactory tokenFactory; |
||||
|
private JwtSettings jwtSettings; |
||||
|
|
||||
|
private UserId userId; |
||||
|
|
||||
|
@BeforeEach |
||||
|
public void setUp() { |
||||
|
jwtSettings = new JwtSettings(); |
||||
|
jwtSettings.setTokenIssuer("test.io"); |
||||
|
jwtSettings.setTokenExpirationTime((int) MINUTES.toSeconds(10)); |
||||
|
jwtSettings.setRefreshTokenExpTime((int) DAYS.toSeconds(7)); |
||||
|
jwtSettings.setTokenSigningKey("secret"); |
||||
|
tokenFactory = new JwtTokenFactory(jwtSettings); |
||||
|
|
||||
|
cacheManager = new ConcurrentMapCacheManager(); |
||||
|
tokenOutdatingService = new TokenOutdatingService(cacheManager, tokenFactory, jwtSettings); |
||||
|
tokenOutdatingService.initCache(); |
||||
|
|
||||
|
userId = new UserId(UUID.randomUUID()); |
||||
|
|
||||
|
UserService userService = mock(UserService.class); |
||||
|
|
||||
|
User user = new User(); |
||||
|
user.setId(userId); |
||||
|
user.setAuthority(Authority.TENANT_ADMIN); |
||||
|
user.setEmail("email"); |
||||
|
when(userService.findUserById(any(), eq(userId))).thenReturn(user); |
||||
|
|
||||
|
UserCredentials userCredentials = new UserCredentials(); |
||||
|
userCredentials.setEnabled(true); |
||||
|
when(userService.findUserCredentialsByUserId(any(), eq(userId))).thenReturn(userCredentials); |
||||
|
|
||||
|
accessTokenAuthenticationProvider = new JwtAuthenticationProvider(tokenFactory, tokenOutdatingService); |
||||
|
refreshTokenAuthenticationProvider = new RefreshTokenAuthenticationProvider(tokenFactory, userService, mock(CustomerService.class), tokenOutdatingService); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testOutdateOldUserTokens() throws Exception { |
||||
|
JwtToken jwtToken = createAccessJwtToken(userId); |
||||
|
|
||||
|
SECONDS.sleep(1); // need to wait before outdating so that outdatage time is strictly after token issue time
|
||||
|
tokenOutdatingService.outdateOldUserTokens(userId); |
||||
|
assertTrue(tokenOutdatingService.isOutdated(jwtToken, userId)); |
||||
|
|
||||
|
SECONDS.sleep(1); |
||||
|
|
||||
|
JwtToken newJwtToken = tokenFactory.createAccessJwtToken(createMockSecurityUser(userId)); |
||||
|
assertFalse(tokenOutdatingService.isOutdated(newJwtToken, userId)); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testAuthenticateWithOutdatedAccessToken() throws InterruptedException { |
||||
|
RawAccessJwtToken accessJwtToken = getRawJwtToken(createAccessJwtToken(userId)); |
||||
|
|
||||
|
assertDoesNotThrow(() -> { |
||||
|
accessTokenAuthenticationProvider.authenticate(new JwtAuthenticationToken(accessJwtToken)); |
||||
|
}); |
||||
|
|
||||
|
SECONDS.sleep(1); |
||||
|
tokenOutdatingService.outdateOldUserTokens(userId); |
||||
|
|
||||
|
assertThrows(JwtExpiredTokenException.class, () -> { |
||||
|
accessTokenAuthenticationProvider.authenticate(new JwtAuthenticationToken(accessJwtToken)); |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testAuthenticateWithOutdatedRefreshToken() throws InterruptedException { |
||||
|
RawAccessJwtToken refreshJwtToken = getRawJwtToken(createRefreshJwtToken(userId)); |
||||
|
|
||||
|
assertDoesNotThrow(() -> { |
||||
|
refreshTokenAuthenticationProvider.authenticate(new RefreshAuthenticationToken(refreshJwtToken)); |
||||
|
}); |
||||
|
|
||||
|
SECONDS.sleep(1); |
||||
|
tokenOutdatingService.outdateOldUserTokens(userId); |
||||
|
|
||||
|
assertThrows(CredentialsExpiredException.class, () -> { |
||||
|
refreshTokenAuthenticationProvider.authenticate(new RefreshAuthenticationToken(refreshJwtToken)); |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testTokensOutdatageTimeRemovalFromCache() throws Exception { |
||||
|
JwtToken jwtToken = createAccessJwtToken(userId); |
||||
|
|
||||
|
SECONDS.sleep(1); |
||||
|
tokenOutdatingService.outdateOldUserTokens(userId); |
||||
|
|
||||
|
int refreshTokenExpirationTime = 5; |
||||
|
jwtSettings.setRefreshTokenExpTime(refreshTokenExpirationTime); |
||||
|
|
||||
|
SECONDS.sleep(refreshTokenExpirationTime - 2); |
||||
|
|
||||
|
assertTrue(tokenOutdatingService.isOutdated(jwtToken, userId)); |
||||
|
assertNotNull(cacheManager.getCache(CacheConstants.TOKEN_OUTDATAGE_TIME_CACHE).get(userId.getId().toString())); |
||||
|
|
||||
|
SECONDS.sleep(3); |
||||
|
|
||||
|
assertFalse(tokenOutdatingService.isOutdated(jwtToken, userId)); |
||||
|
assertNull(cacheManager.getCache(CacheConstants.TOKEN_OUTDATAGE_TIME_CACHE).get(userId.getId().toString())); |
||||
|
} |
||||
|
|
||||
|
private JwtToken createAccessJwtToken(UserId userId) { |
||||
|
return tokenFactory.createAccessJwtToken(createMockSecurityUser(userId)); |
||||
|
} |
||||
|
|
||||
|
private JwtToken createRefreshJwtToken(UserId userId) { |
||||
|
return tokenFactory.createRefreshToken(createMockSecurityUser(userId)); |
||||
|
} |
||||
|
|
||||
|
private RawAccessJwtToken getRawJwtToken(JwtToken token) { |
||||
|
return new RawAccessJwtToken(token.getToken()); |
||||
|
} |
||||
|
|
||||
|
private SecurityUser createMockSecurityUser(UserId userId) { |
||||
|
SecurityUser securityUser = new SecurityUser(); |
||||
|
securityUser.setEmail("email"); |
||||
|
securityUser.setUserPrincipal(new UserPrincipal(UserPrincipal.Type.USER_NAME, securityUser.getEmail())); |
||||
|
securityUser.setAuthority(Authority.CUSTOMER_USER); |
||||
|
securityUser.setId(userId); |
||||
|
return securityUser; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,39 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.dao.resource; |
||||
|
|
||||
|
import org.thingsboard.server.common.data.Resource; |
||||
|
import org.thingsboard.server.common.data.ResourceType; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.page.PageLink; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
|
||||
|
public interface ResourceService { |
||||
|
Resource saveResource(Resource resource); |
||||
|
|
||||
|
Resource getResource(TenantId tenantId, ResourceType resourceType, String resourceId); |
||||
|
|
||||
|
PageData<Resource> findResourcesByTenantId(TenantId tenantId, PageLink pageLink); |
||||
|
|
||||
|
List<Resource> findResourcesByTenantIdResourceType(TenantId tenantId, ResourceType resourceType); |
||||
|
|
||||
|
void deleteResource(TenantId tenantId, ResourceType resourceType, String resourceId); |
||||
|
|
||||
|
void deleteResourcesByTenantId(TenantId tenantId); |
||||
|
} |
||||
@ -0,0 +1,41 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
|
||||
|
import java.io.Serializable; |
||||
|
|
||||
|
@Data |
||||
|
public class Resource implements HasTenantId, Serializable { |
||||
|
|
||||
|
private static final long serialVersionUID = 7379609705527272306L; |
||||
|
|
||||
|
private TenantId tenantId; |
||||
|
private ResourceType resourceType; |
||||
|
private String resourceId; |
||||
|
private String value; |
||||
|
|
||||
|
@Override |
||||
|
public String toString() { |
||||
|
return "Resource{" + |
||||
|
"tenantId=" + tenantId + |
||||
|
", resourceType=" + resourceType + |
||||
|
", resourceId='" + resourceId + '\'' + |
||||
|
'}'; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,20 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data; |
||||
|
|
||||
|
public enum ResourceType { |
||||
|
LWM2M_MODEL, JKS, PKCS_12 |
||||
|
} |
||||
@ -0,0 +1,30 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.device.profile; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
import org.thingsboard.server.common.data.query.EntityKeyValueType; |
||||
|
import org.thingsboard.server.common.data.query.KeyFilterPredicate; |
||||
|
|
||||
|
@Data |
||||
|
public class AlarmConditionFilter { |
||||
|
|
||||
|
private AlarmConditionFilterKey key; |
||||
|
private EntityKeyValueType valueType; |
||||
|
private Object value; |
||||
|
private KeyFilterPredicate predicate; |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,26 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.device.profile; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
|
||||
|
@Data |
||||
|
public class AlarmConditionFilterKey { |
||||
|
|
||||
|
private final AlarmConditionKeyType type; |
||||
|
private final String key; |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,23 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.device.profile; |
||||
|
|
||||
|
public enum AlarmConditionKeyType { |
||||
|
ATTRIBUTE, |
||||
|
TIME_SERIES, |
||||
|
ENTITY_FIELD, |
||||
|
CONSTANT |
||||
|
} |
||||
@ -0,0 +1,30 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.query; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
import org.thingsboard.server.common.data.EntityType; |
||||
|
|
||||
|
@Data |
||||
|
public class EntityTypeFilter implements EntityFilter { |
||||
|
@Override |
||||
|
public EntityFilterType getType() { |
||||
|
return EntityFilterType.ENTITY_TYPE; |
||||
|
} |
||||
|
|
||||
|
private EntityType entityType; |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,30 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.security.event; |
||||
|
|
||||
|
import org.thingsboard.server.common.data.id.UserId; |
||||
|
|
||||
|
public class UserAuthDataChangedEvent { |
||||
|
private final UserId userId; |
||||
|
|
||||
|
public UserAuthDataChangedEvent(UserId userId) { |
||||
|
this.userId = userId; |
||||
|
} |
||||
|
|
||||
|
public UserId getUserId() { |
||||
|
return userId; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,37 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.transport.resource; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
import org.thingsboard.server.common.data.HasTenantId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
|
||||
|
@Data |
||||
|
public class Resource implements HasTenantId { |
||||
|
private TenantId tenantId; |
||||
|
private ResourceType resourceType; |
||||
|
private String resourceId; |
||||
|
private String value; |
||||
|
|
||||
|
@Override |
||||
|
public String toString() { |
||||
|
return "Resource{" + |
||||
|
"tenantId=" + tenantId + |
||||
|
", resourceType=" + resourceType + |
||||
|
", resourceId='" + resourceId + '\'' + |
||||
|
'}'; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,20 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2021 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.common.data.transport.resource; |
||||
|
|
||||
|
public enum ResourceType { |
||||
|
LWM2M_MODEL, JKS, PKCS_12 |
||||
|
} |
||||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue