merge-requests/598/head
Ace 4 years ago
commit 4b58b46d8b

@ -66,7 +66,6 @@
<phase>generate-resources</phase>
<configuration>
<nodeVersion>${node.version}</nodeVersion>
<npmVersion>${npm.version}</npmVersion>
</configuration>
</execution>
<execution>
@ -101,46 +100,6 @@
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.codehaus.mojo</groupId>-->
<!-- <artifactId>exec-maven-plugin</artifactId>-->
<!-- <version>1.5.0</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>npm install (initialize)</id>-->
<!-- <goals>-->
<!-- <goal>exec</goal>-->
<!-- </goals>-->
<!-- <phase>initialize</phase>-->
<!-- <configuration>-->
<!-- <workingDirectory>react-app</workingDirectory>-->
<!-- <executable>${npm.executable}</executable>-->
<!-- <arguments>-->
<!-- <argument>install</argument>-->
<!-- <argument>&#45;&#45;silent</argument>-->
<!-- </arguments>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- <execution>-->
<!-- <id>npm run build (compile)</id>-->
<!-- <goals>-->
<!-- <goal>exec</goal>-->
<!-- </goals>-->
<!-- <phase>compile</phase>-->
<!-- <configuration>-->
<!-- <workingDirectory>react-app</workingDirectory>-->
<!-- <executable>${npm.executable}</executable>-->
<!-- <arguments>-->
<!-- <argument>run</argument>-->
<!-- <argument>${npm.build.command}</argument>-->
<!-- </arguments>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- <configuration>-->
<!-- <workingDirectory>${npm.working.dir}</workingDirectory>-->
<!-- </configuration>-->
<!-- </plugin>-->
</plugins>
</build>
<profiles>

@ -69,7 +69,6 @@
<phase>generate-resources</phase>
<configuration>
<nodeVersion>${node.version}</nodeVersion>
<npmVersion>${npm.version}</npmVersion>
</configuration>
</execution>
<execution>

@ -2273,4 +2273,58 @@ public interface DeviceManagementService {
response = ErrorResponse.class)
})
Response getDeviceFilters();
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{clientId}/{clientSecret}/default-token")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the default token",
notes = "Getting the default access token by using given client ID and the client secret value.",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully returned the default token details.",
response = Policy.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the default token.",
response = ErrorResponse.class)
}
)
Response getDefaultToken(
@ApiParam(
name = "client ID",
value = "Client Id.",
required = true)
@PathParam("clientId")
String clientId,
@ApiParam(
name = "client secret",
value = "Client Secret",
required = true)
@PathParam("clientSecret")
String clientSecret
);
}

@ -38,11 +38,13 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceFilters;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -102,6 +104,10 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
@ -1328,4 +1334,21 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/{clientId}/{clientSecret}/default-token")
@Override
public Response getDefaultToken(@PathParam("clientId") String clientId, @PathParam("clientSecret") String clientSecret) {
JWTClientManagerService jwtClientManagerService = DeviceMgtAPIUtils.getJWTClientManagerService();
try {
JWTClient jwtClient = jwtClientManagerService.getJWTClient();
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(clientId, clientSecret,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(), "default");
return Response.status(Response.Status.OK).entity(accessTokenInfo).build();
} catch (JWTClientException e) {
String msg = "Error occurred while getting default access token by using given client Id and client secret.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -169,4 +169,13 @@ public final class DeviceManagementConstants {
public static final String DEVICE_INFO_PARAM = "device-info";
public static final String APP_USAGE_ENDPOINT = REPORTING_CONTEXT + "/app-usage";
}
public static final class Payload {
private Payload() {
throw new AssertionError();
}
public static final String DEVICE_INFO_DEVICE_NAME = "DEVICE_NAME";
public static final String DEVICE_INFO_IMEI = "IMEI";
public static final String DEVICE_INFO_IMSI = "IMSI";;
}
}

@ -134,6 +134,20 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceDetailsDAO.addDeviceProperties(injectableProps, device.getId(),
device.getEnrolmentInfo().getId());
}
if (deviceInfo.getDeviceDetailsMap().containsKey(DeviceManagementConstants
.Payload.DEVICE_INFO_DEVICE_NAME) &&
StringUtils.isNotEmpty(deviceInfo.getDeviceDetailsMap()
.get(DeviceManagementConstants.Payload.DEVICE_INFO_DEVICE_NAME))
&& !device.getName().equals(deviceInfo.getDeviceDetailsMap()
.get(DeviceManagementConstants.Payload.DEVICE_INFO_DEVICE_NAME))) {
String name = deviceInfo.getDeviceDetailsMap()
.get(DeviceManagementConstants.Payload.DEVICE_INFO_DEVICE_NAME);
log.info("Device identifier " + device.getDeviceIdentifier() + ", Device name " +
"changed by user from " + device.getName() + " to " + name);
device.setName(name);
}
deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId());
DeviceManagementDAOFactory.commitTransaction();
@ -142,8 +156,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
Object[] metaData = {device.getDeviceIdentifier(), device.getType()};
Object[] payload = new Object[]{
Calendar.getInstance().getTimeInMillis(),
deviceInfo.getDeviceDetailsMap().get("IMEI"),
deviceInfo.getDeviceDetailsMap().get("IMSI"),
deviceInfo.getDeviceDetailsMap().get(DeviceManagementConstants.Payload
.DEVICE_INFO_IMEI),
deviceInfo.getDeviceDetailsMap().get(DeviceManagementConstants.Payload
.DEVICE_INFO_IMSI),
deviceInfo.getDeviceModel(),
deviceInfo.getVendor(),
deviceInfo.getOsVersion(),

@ -0,0 +1,134 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.ui.request.interceptor;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.entgra.ui.request.interceptor.beans.AuthData;
import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@MultipartConfig
@WebServlet("/default-credentials")
public class DefaultTokenHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
HttpSession httpSession = req.getSession(false);
if (httpSession != null) {
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData defaultAuthData = (AuthData) httpSession
.getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY);
if (defaultAuthData != null) {
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken()));
return;
}
String clientId = authData.getClientId();
String clientSecret = authData.getClientSecret();
String iotsCorePort = System.getProperty("iot.core.https.port");
if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) {
iotsCorePort = System.getProperty("iot.core.http.port");
}
String tokenUrl =
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host")
+ HandlerConstants.COLON + iotsCorePort + "/api/device-mgt/v1.0/devices/" + clientId
+ "/" + clientSecret + "/default-token";
HttpGet defaultTokenRequest = new HttpGet(tokenUrl);
defaultTokenRequest
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
defaultTokenRequest
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get default token data.");
HandlerUtil.handleError(resp, tokenResultResponse);
return;
}
String tokenResult = tokenResultResponse.getData();
if (tokenResult == null) {
log.error("Invalid default token response is received.");
HandlerUtil.handleError(resp, tokenResultResponse);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult);
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
AuthData newDefaultAuthData = new AuthData();
newDefaultAuthData.setClientId(clientId);
newDefaultAuthData.setClientSecret(clientSecret);
String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString();
newDefaultAuthData.setAccessToken(defaultToken);
newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString());
newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString());
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
}
} else {
HandlerUtil.sendUnAuthorizeResponse(resp);
}
} catch (IOException e) {
log.error("Error occurred when processing GET request to get default token.", e);
}
}
/**
* Get Success Proxy Response
* @param responseString Response String
* @return {@link ProxyResponse}
*/
private ProxyResponse constructSuccessProxyResponse (String responseString) {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setData(responseString);
return proxyResponse;
}
}

@ -72,7 +72,6 @@ public class LoginHandler extends HttpServlet {
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
JsonParser jsonParser = new JsonParser();
ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
String executorResponse = uiConfigResponse.getExecutorResponse();
if (!StringUtils.isEmpty(executorResponse) && executorResponse
@ -88,6 +87,7 @@ public class LoginHandler extends HttpServlet {
HandlerUtil.handleError(resp, null);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
JsonObject uiConfigJsonObject = null;
if (uiConfigJsonElement.isJsonObject()) {

@ -18,7 +18,6 @@
package io.entgra.ui.request.interceptor;
import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@ -56,13 +56,13 @@ public class UserHandler extends HttpServlet {
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
@ -91,7 +91,7 @@ public class UserHandler extends HttpServlet {
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
ProxyResponse proxyResponse = new ProxyResponse();
@ -106,18 +106,4 @@ public class UserHandler extends HttpServlet {
log.error("Error occurred while parsing the response. ", e);
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
private void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(resp, proxyResponse);
}
}

@ -30,6 +30,7 @@ public class HandlerConstants {
public static final String TAGS_KEY = "tags";
public static final String APP_NAME_KEY = "applicationName";
public static final String SESSION_AUTH_DATA_KEY = "authInfo";
public static final String SESSION_DEFAULT_AUTH_DATA_KEY = "defaultAuthInfo";
public static final String UI_CONFIG_KEY = "ui-config";
public static final String PLATFORM = "platform";
public static final String USERNAME = "username";

@ -19,7 +19,6 @@
package io.entgra.ui.request.interceptor.util;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -35,9 +34,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@ -232,4 +229,17 @@ public class HandlerUtil {
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
public static void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
handleError(resp, proxyResponse);
}
}

@ -2249,8 +2249,7 @@
<googlecode.plist.version>1.21</googlecode.plist.version>
<net.dongliu.version>2.6.5</net.dongliu.version>
<frontend.mave.version>1.7.6</frontend.mave.version>
<node.version>v10.15.3</node.version>
<npm.version>6.9.0</npm.version>
<node.version>v12.18.1</node.version>
<maven.checkstyle.vesion>3.1.0</maven.checkstyle.vesion>

Loading…
Cancel
Save