djekl
3/16/2016 - 1:38 AM

Slack oAuth2.0 Round Trip

Slack oAuth2.0 Round Trip

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use GuzzleHttp\Client;

class SlackOAuthController extends Controller
{
    const SLACK_AUTH_URL = 'https://slack.com/oauth/authorize?client_id=%s&scope=%s&redirect_uri=%s';
    const SLACK_ACCESS_URL = 'https://slack.com/api/oauth.access';

    /**
     * SlackOAuthController constructor.
     * @param Client $http
     */
    public function __construct(Client $http)
    {
        $this->http = $http;
    }

    /**
     * Redirect to Slack authentication route
     * @route /slack/auth
     * @link https://api.slack.com/docs/oauth
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function auth()
    {
        return redirect( $this->authUrl() );
    }

    /**
     * Retrieve authentication token and
     * exchange for authorization token
     * @route /slack/token
     * @link https://api.slack.com/methods/oauth.access
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function access(Request $request)
    {
        $response = $this->http->post(static::SLACK_ACCESS_URL, [
            'form_params' => [
                'client_id' => env('SLACK_CLIENT'),
                'client_secret' => env('SLACK_SECRET'),
                'code' => $request->input('code'),
                'redirect_uri' => env('SLACK_REDIRECT'),
            ]
        ]);

        /**
         * JSON response:
         * ok: true,
         * access_token: "xoxp-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx",
         * scope: "identify,chat:write:bot,files:write:user",
         * team_name: "SomeTeam",
         * team_id: "T01234567"
         */
        $parsedResponse = json_decode($response->getBody());

        // Save to database, perhaps encrypt that access token
        return redirect('/dashboard');
    }

    /**
     * Build slack authentication URL
     * @link https://api.slack.com/docs/oauth-scopes
     * @return string
     */
    protected function authUrl()
    {
        return sprintf(static::SLACK_AUTH_URL,
            env('SLACK_CLIENT'),
            env('SLACK_SCOPES'),  // e.g. identify,chat:write:bot,files:write:user
            env('SLACK_REDIRECT') // e.g. https://example.com/slack/token
        );
    }
}