Skip to content
This repository has been archived by the owner on Dec 4, 2023. It is now read-only.

Middleware TranscriptLogger #52

Merged
merged 4 commits into from
Jul 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions libraries/bot-connector/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,6 @@
<artifactId>botbuilder-schema</artifactId>
<version>4.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.ea.async</groupId>
<artifactId>ea-async</artifactId>
<version>1.1.1</version>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,21 @@
package com.microsoft.bot.connector.authentication;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.rest.credentials.ServiceClientCredentials;

import okhttp3.*;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import rx.Completable;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.ea.async.Async.await;
import static com.microsoft.bot.connector.authentication.AuthenticationConstants.ToChannelFromBotLoginUrl;
import static com.microsoft.bot.connector.authentication.AuthenticationConstants.ToChannelFromBotOAuthScope;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.stream.Collectors.joining;

public class MicrosoftAppCredentials implements ServiceClientCredentials {
private String appId;
Expand All @@ -50,7 +38,6 @@ public class MicrosoftAppCredentials implements ServiceClientCredentials {
public final String OAuthScope = AuthenticationConstants.ToChannelFromBotOAuthScope;



public String getTokenCacheKey() {
return String.format("%s-cache", this.appId);
}
Expand All @@ -61,15 +48,18 @@ public MicrosoftAppCredentials(String appId, String appPassword) {
this.client = new OkHttpClient.Builder().build();
this.mapper = new ObjectMapper().findAndRegisterModules();
}

public static final MicrosoftAppCredentials Empty = new MicrosoftAppCredentials(null, null);

public String microsoftAppId() {
return this.appId;
}

public MicrosoftAppCredentials withMicrosoftAppId(String appId) {
this.appId = appId;
return this;
}

public String getToken(Request request) throws IOException {
if (System.currentTimeMillis() < expiredTime) {
return currentToken;
Expand All @@ -93,18 +83,14 @@ public String getToken(Request request) throws IOException {
}



private boolean ShouldSetToken(String url)
{
if (isTrustedServiceUrl(url))
{
private boolean ShouldSetToken(String url) {
if (isTrustedServiceUrl(url)) {
return true;
}
return false;
}



@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.interceptors().add(new MicrosoftAppCredentialsInterceptor(this));
Expand Down Expand Up @@ -134,7 +120,8 @@ public static void trustServiceUrl(String serviceUrl, LocalDateTime expirationTi
try {
URL url = new URL(serviceUrl);
trustServiceUrl(url, expirationTime);
} catch (MalformedURLException e) { }
} catch (MalformedURLException e) {
}
}

public static void trustServiceUrl(URL serviceUrl, LocalDateTime expirationTime) {
Expand All @@ -153,6 +140,7 @@ public static boolean isTrustedServiceUrl(String serviceUrl) {
public static boolean isTrustedServiceUrl(URL url) {
return !trustHostNames.getOrDefault(url.getHost(), LocalDateTime.MIN).isBefore(LocalDateTime.now().minusMinutes(5));
}

public static boolean isTrustedServiceUrl(HttpUrl url) {
return !trustHostNames.getOrDefault(url.host(), LocalDateTime.MIN).isBefore(LocalDateTime.now().minusMinutes(5));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,43 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.bot.connector.ConnectorClient;
import com.microsoft.bot.connector.UserAgent;
import com.microsoft.bot.connector.implementation.ConnectorClientImpl;
import com.microsoft.bot.schema.TokenExchangeState;
import com.microsoft.bot.schema.models.Activity;
import com.microsoft.bot.schema.models.ConversationReference;
import com.microsoft.bot.schema.models.TokenResponse;
import com.microsoft.rest.ServiceClient;

import okhttp3.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.ea.async.Async.await;
import static com.microsoft.bot.connector.authentication.MicrosoftAppCredentials.JSON;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.stream.Collectors.joining;


/**
* Service client to handle requests to the botframework api service.
*
* <p>
* Uses the MicrosoftInterceptor class to add Authorization header from idp.
*
*/
public class OAuthClient extends ServiceClient {
private final ConnectorClientImpl client;
Expand All @@ -59,16 +59,17 @@ public OAuthClient(ConnectorClientImpl client, String uri) throws URISyntaxExcep
if (client == null)
throw new IllegalArgumentException("client");
this.client = client;
this.uri = uri + (uri.endsWith("/")? "" : "/");
this.uri = uri + (uri.endsWith("/") ? "" : "/");
this.mapper = new ObjectMapper();
}

/**
* Get User Token for given user and connection.
* @param userId
* @param connectionName
*
* @param userId
* @param connectionName
* @param magicCode
* @return CompletableFuture< TokenResponse > on success; otherwise null.
* @return CompletableFuture< TokenResponse > on success; otherwise null.
*/
public CompletableFuture<TokenResponse> GetUserTokenAsync(String userId, String connectionName, String magicCode) throws IOException, URISyntaxException, ExecutionException, InterruptedException {
return GetUserTokenAsync(userId, connectionName, magicCode, null);
Expand All @@ -90,14 +91,13 @@ protected URI MakeUri(String uri, HashMap<String, String> queryStrings) throws U
}

/**
Get User Token for given user and connection.

@param userId
@param connectionName
@param magicCode
@param customHeaders

@return CompletableFuture< TokenResponse > on success; null otherwise.
* Get User Token for given user and connection.
*
* @param userId
* @param connectionName
* @param magicCode
* @param customHeaders
* @return CompletableFuture< TokenResponse > on success; null otherwise.
*/
public CompletableFuture<TokenResponse> GetUserTokenAsync(String userId, String connectionName, String magicCode, Map<String, ArrayList<String>> customHeaders) throws IllegalArgumentException {
if (StringUtils.isEmpty(userId)) {
Expand All @@ -109,7 +109,7 @@ public CompletableFuture<TokenResponse> GetUserTokenAsync(String userId, String

return CompletableFuture.supplyAsync(() -> {
// Construct URL
HashMap <String, String> qstrings = new HashMap<>();
HashMap<String, String> qstrings = new HashMap<>();
qstrings.put("userId", userId);
qstrings.put("connectionName", connectionName);
if (!StringUtils.isBlank(magicCode)) {
Expand Down Expand Up @@ -146,17 +146,14 @@ public CompletableFuture<TokenResponse> GetUserTokenAsync(String userId, String
int statusCode = response.code();
if (statusCode == HTTP_OK) {
return this.mapper.readValue(response.body().string(), TokenResponse.class);
}
else if (statusCode == HTTP_NOT_FOUND) {
} else if (statusCode == HTTP_NOT_FOUND) {
return null;
}
else {
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
} finally {
if (response != null)
response.body().close();
}
Expand All @@ -166,7 +163,8 @@ else if (statusCode == HTTP_NOT_FOUND) {

/**
* Signs Out the User for the given ConnectionName.
* @param userId
*
* @param userId
* @param connectionName
* @return True on successful sign-out; False otherwise.
*/
Expand All @@ -182,7 +180,7 @@ public CompletableFuture<Boolean> SignOutUserAsync(String userId, String connect
String invocationId = null;

// Construct URL
HashMap <String, String> qstrings = new HashMap<>();
HashMap<String, String> qstrings = new HashMap<>();
qstrings.put("userId", userId);
qstrings.put("connectionName", connectionName);
String strUri = String.format("%sapi/usertoken/SignOut", this.uri);
Expand Down Expand Up @@ -226,10 +224,10 @@ public CompletableFuture<Boolean> SignOutUserAsync(String userId, String connect
}



/**
* Gets the Link to be sent to the user for signin into the given ConnectionName
* @param activity
*
* @param activity
* @param connectionName
* @return Sign in link on success; null otherwise.
*/
Expand Down Expand Up @@ -294,13 +292,13 @@ public CompletableFuture<String> GetSignInLinkAsync(Activity activity, String co
/**
* Send a dummy OAuth card when the bot is being used on the emulator for testing without fetching a real token.
*
* @param emulateOAuthCards
* @param emulateOAuthCards
* @return CompletableFuture with no result code
*/
public CompletableFuture SendEmulateOAuthCardsAsync(Boolean emulateOAuthCards) throws URISyntaxException, IOException {

// Construct URL
HashMap <String, String> qstrings = new HashMap<>();
HashMap<String, String> qstrings = new HashMap<>();
qstrings.put("emulate", emulateOAuthCards.toString());
String strUri = String.format("%sapi/usertoken/emulateOAuthCards", this.uri);
URI tokenUrl = MakeUri(strUri, qstrings);
Expand All @@ -310,7 +308,7 @@ public CompletableFuture SendEmulateOAuthCardsAsync(Boolean emulateOAuthCards) t

return CompletableFuture.runAsync(() -> {
// Construct dummy body
RequestBody body = RequestBody.create(JSON, "{}" );
RequestBody body = RequestBody.create(JSON, "{}");

// Set Credentials and make call
MicrosoftAppCredentials appCredentials = (MicrosoftAppCredentials) client.restClient().credentials();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import okhttp3.OkHttpClient;
import okhttp3.Response;

import static com.ea.async.Async.await;

import static java.util.concurrent.CompletableFuture.completedFuture;

public class BotAccessTokenStub extends MicrosoftAppCredentials {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.ea.async.Async.await;

import static java.util.concurrent.CompletableFuture.completedFuture;


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import java.util.concurrent.ExecutionException;
import java.util.function.Function;

import static com.ea.async.Async.await;
import static java.util.concurrent.CompletableFuture.completedFuture;


Expand Down Expand Up @@ -102,7 +101,7 @@ public void UseClientFor(Function<ConnectorClient, CompletableFuture<Void>> doTe
this.UseClientFor(doTest, className, "");
}
public void UseClientFor(Function<ConnectorClient, CompletableFuture<Void>> doTest, String className, String methodName) {
await(doTest.apply(this.connector));
doTest.apply(this.connector).join();
}


Expand Down
Loading