Skip to content

Commit

Permalink
Add botScopes and requestUserScopes to context object
Browse files Browse the repository at this point in the history
  • Loading branch information
seratch committed Apr 26, 2023
1 parent f02885e commit 22366d7
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 9 deletions.
14 changes: 13 additions & 1 deletion bolt-servlet/src/test/java/samples/OAuthSample.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.slack.api.bolt.App;
import com.slack.api.bolt.AppConfig;
import com.slack.api.model.event.AppMentionEvent;
import com.slack.api.model.event.MessageEvent;
import util.ResourceLoader;
import util.TestSlackAppServer;

Expand All @@ -13,6 +14,7 @@ public class OAuthSample {

public static void main(String[] args) throws Exception {
AppConfig config = ResourceLoader.loadAppConfig("appConfig_oauth.json");
config.setAlwaysRequestUserTokenNeeded(true);
config.setTokenRotationExpirationMillis(1000 * 60 * 60 * 24 * 365); // for testing
App app = new App(config).asOAuthApp(true)
// Enable built-in tokens_revoked / app_uninstalled event handlers
Expand All @@ -23,6 +25,8 @@ public static void main(String[] args) throws Exception {
// app.event(AppUninstalledEvent.class, app.defaultAppUninstalledEventHandler());

app.event(AppMentionEvent.class, (req, ctx) -> {
ctx.logger.info("bot scopes: {}", ctx.getBotScopes());
ctx.logger.info("user scopes: {}", ctx.getRequestUserScopes());
app.executorService().submit(() -> {
try {
ctx.say("Hi there, <@" + req.getEvent().getUser() + ">!");
Expand All @@ -33,7 +37,15 @@ public static void main(String[] args) throws Exception {
return ctx.ack();
});

app.command("/token-rotation-modal", (req, ctx) -> ctx.ack("Hi!"));
app.event(MessageEvent.class, (payload, ctx) -> {
return ctx.ack();
});

app.command("/token-rotation-test", (req, ctx) -> {
ctx.logger.info("bot scopes: {}", ctx.getBotScopes());
ctx.logger.info("user scopes: {}", ctx.getRequestUserScopes());
return ctx.ack("Hi!");
});

app.oauthCallbackError((req, resp) -> {
req.getContext().logger.error("query string: {}", req.getQueryString());
Expand Down
9 changes: 9 additions & 0 deletions bolt/src/main/java/com/slack/api/bolt/context/Context.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
Expand Down Expand Up @@ -52,6 +53,10 @@ public abstract class Context {
* A bot token associated with this request. The format must be starting with `xoxb-`.
*/
protected String botToken;
/**
* The scopes associated to the botToken
*/
protected List<String> botScopes;
/**
* bot_id associated with this request.
*/
Expand All @@ -69,6 +74,10 @@ public abstract class Context {
* The user token that is associated with the request user ID.
*/
protected String requestUserToken;
/**
* The scopes associated to the requestUserToken
*/
protected List<String> requestUserScopes;

protected final Map<String, String> additionalValues = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
import com.slack.api.model.block.LayoutBlock;
import com.slack.api.token_rotation.RefreshedToken;
import com.slack.api.token_rotation.TokenRotator;
import com.slack.api.util.thread.ExecutorServiceFactory;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -238,7 +238,16 @@ public Response apply(Request req, Response resp, MiddlewareChain chain) throws
AuthTestResponse authTestResponse = callAuthTest(token, config, context.client());
if (authTestResponse.isOk()) {
context.setBotToken(botToken);
Map<String, List<String>> botHeaders = authTestResponse.getHttpResponseHeaders();
List<String> botScopesHeader = botHeaders != null ? botHeaders.get("x-oauth-scopes") : null;
context.setBotScopes(botScopesHeader != null ? Arrays.asList(botScopesHeader.get(0).split(",")) : null);
context.setRequestUserToken(userToken);
if (userToken != null && token != userToken) {
AuthTestResponse userAuthTestResponse = callAuthTest(userToken, config, context.client());
Map<String, List<String>> userHeaders = userAuthTestResponse.getHttpResponseHeaders();
List<String> userScopesHeader = userHeaders != null ? userHeaders.get("x-oauth-scopes") : null;
context.setRequestUserScopes(userScopesHeader != null ? Arrays.asList(userScopesHeader.get(0).split(",")) : null);
}
if (!authTestResponse.isEnterpriseInstall()) {
context.setTeamId(authTestResponse.getTeamId());
// As the team_id here is the org's ID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

Expand Down Expand Up @@ -57,11 +60,13 @@ public Response apply(Request req, Response resp, MiddlewareChain chain) throws
}

Context context = req.getContext();
AuthTestResponse authResult = callAuthTest(appConfig, context.client());
String botToken = context.getBotToken() != null ? context.getBotToken() : appConfig.getSingleTeamBotToken();
AuthTestResponse authResult = callAuthTest(botToken, appConfig, context.client());
if (authResult.isOk()) {
if (context.getBotToken() == null) {
context.setBotToken(appConfig.getSingleTeamBotToken());
}
context.setBotToken(botToken);
Map<String, List<String>> botHeaders = authResult.getHttpResponseHeaders();
List<String> botScopesHeader = botHeaders != null ? botHeaders.get("x-oauth-scopes") : null;
context.setBotScopes(botScopesHeader != null ? Arrays.asList(botScopesHeader.get(0).split(",")) : null);
context.setBotUserId(authResult.getUserId());
context.setTeamId(authResult.getTeamId());
context.setEnterpriseId(authResult.getEnterpriseId());
Expand All @@ -79,7 +84,12 @@ public Response apply(Request req, Response resp, MiddlewareChain chain) throws
context.getRequestUserId()
);
if (installer != null) {
context.setRequestUserToken(installer.getInstallerUserAccessToken());
String userToken = installer.getInstallerUserAccessToken();
context.setRequestUserToken(userToken);
AuthTestResponse userAuthTestResponse = callAuthTest(userToken, appConfig, context.client());
Map<String, List<String>> userHeaders = userAuthTestResponse.getHttpResponseHeaders();
List<String> userScopesHeader = userHeaders != null ? userHeaders.get("x-oauth-scopes") : null;
context.setRequestUserScopes(userScopesHeader != null ? Arrays.asList(userScopesHeader.get(0).split(",")) : null);
}
}
}
Expand All @@ -96,7 +106,7 @@ public Response apply(Request req, Response resp, MiddlewareChain chain) throws
}
}

protected AuthTestResponse callAuthTest(AppConfig config, MethodsClient client) throws IOException, SlackApiException {
protected AuthTestResponse callAuthTest(String token, AppConfig config, MethodsClient client) throws IOException, SlackApiException {
if (cachedAuthTestResponse.isPresent()) {
boolean permanentCacheEnabled = config.getAuthTestCacheExpirationMillis() < 0;
if (permanentCacheEnabled) {
Expand All @@ -108,7 +118,7 @@ protected AuthTestResponse callAuthTest(AppConfig config, MethodsClient client)
return cachedAuthTestResponse.get();
}
}
AuthTestResponse response = client.authTest(r -> r.token(config.getSingleTeamBotToken()));
AuthTestResponse response = client.authTest(r -> r.token(token));
cachedAuthTestResponse = Optional.of(response); // response here is non-null for sure
lastCachedMillis.set(System.currentTimeMillis());
return response;
Expand Down

0 comments on commit 22366d7

Please sign in to comment.