Search code examples
javascriptnode.jsoauthslackslack-api

Slack Bot with Bolt for JavaScript and OAuth 2.0 to share the app with other workspaces


I made it to add an app with an Add to Slack Button using Bolt for Javascript. The Slack commands don't work yet, because I don't have a database with auth tokens yet. I planned to implement that but realized that I never see the console log.

So from my understanding the console.log("authorizeFn") should work

const { App, ExpressReceiver } = require("@slack/bolt");;

const expressReceiver = new ExpressReceiver({
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  endpoints: "/events"
});

const authorizeFn = async ({ teamId }) => {
  //Implement query of database looking for teamId, getting auth token... 

  console.log("authorizeFn") //This one never logs???
};

const app = new App({
  authorize: authorizeFn,
  receiver: expressReceiver
});

const app_express = expressReceiver.app;

It should check with every event if the user is authorized, correct?

The code goes on like that

/* Page with add button, can be implemented in website instead */
app_express.get("/auth/add", (req, res, next) => {
  res.write(
    '<a href="https:/...'
  );
  res.end();
});
app_express.get("/auth/direct", (req, res, next) => {
  res.redirect(
    "https://slack...."
  );
  res.end();
});
/* Thanks for installing! */
app_express.get("/auth/thanks", (req, res, next) => {
  res.write("Thanks for installing!");
  res.end();
});

/* oauth callback function */
app_express.get("/auth/callback", (req, res, next) => {
  let code = req.query.code;

  let state = req.query.state;

  return app.client.oauth.v2
    .access({
      client_id: process.env.SLACK_CLIENT_ID,
      client_secret: process.env.SLACK_CLIENT_SECRET,
      code: code
    })
    .then(async result => {
      console.log(result);
      // save result of oauth.access call somewhere, like in a database.

      res.redirect(process.env.BASE_DOMAIN + "/auth/thanks");
      res.end();
    })
    .catch(error => {
      throw error;
    });
});

console.log(result); logs something useful, which looke like teamIds, Users and a token


Solution

  • it had to be

    const expressReceiver = new ExpressReceiver({
      signingSecret: process.env.SLACK_SIGNING_SECRET,
      endpoints: "/slack/events"
    });
    

    in my case. Not:

      endpoints: "/events"