roo
roo

Reputation: 343

Get a user's API key for using in Slack

So I'm building a small Slack bot that I want multiple users to be able to use in different Slack teams. So far the workflow is like this:

  1. User signs up on website.
  2. User connects with an API provider and receives their OAuth credentials. The access token for each user is saved in the database.
  3. User adds Slack bot to their team.

With hardcoded API values the bot retrieves the desired data, but what is the best way for the bot to be able to get the appropriate data for each Slack team?

I obviously don't want a user to need to keep signing into the website etc, so how do I associate the slack team with the Laravel user and then pull the relevant API data?

For some example code, imagine that I have a Strava access token stored in my DB for a user and I want to call the API:

$botman->hears('runstats', function ($bot) {
    $payload = \Strava\Account::get(
      \Auth::user()->strava_id,
      array('api_key' => "here_is_a_secret_key")
  );

$bot->reply($payload->monthly_kms);

This works fine when I query from my web interface as I'm signed into my website and it spits back 123km as an example.

Obviously when I'm signed into Slack then there's no Auth::user instance and so it cannot find the relevant Strava ID. That's what I want to be able to retrieve for the relevant Slack user. I envisage it being installed in multiple Slack workspaces.

Upvotes: 1

Views: 665

Answers (1)

Erik Kalkoken
Erik Kalkoken

Reputation: 32827

You need to store the relation between a Slack user (with team ID, user ID) and his individual token for each API in your database.

So you have two options when adding new API tokens:

  • Ensure that the process of adding new tokens for API services is always started on Slack (e.g. with a slash command) and then forward the user to your webpage. Thus your app knows which user it is.
  • Let users log into your web-page with their Slack credentials (using Slack Sign-in).

Both options require that your Slack app has been previously installed to the relevant team of course.

Upvotes: 1

Related Questions