-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.rb
62 lines (53 loc) · 1.8 KB
/
auth.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# frozen_string_literal: true
SLACK_CONFIG = {
slack_client_id: ENV['SLACK_CLIENT_ID'],
slack_api_secret: ENV['SLACK_API_SECRET'],
slack_redirect_uri: ENV['SLACK_REDIRECT_URI'],
slack_verification_token: ENV['SLACK_VERIFICATION_TOKEN']
}.freeze
# Quick config check
if SLACK_CONFIG.any? { |_key, value| value.nil? }
error_msg = SLACK_CONFIG.select { |_k, v| v.nil? }.keys.join(", ").upcase
raise "Missing Slack config variables: #{error_msg}"
end
class Auth < Sinatra::Base
# landing page with Add to Slack button
get '/' do
status 200
erb :index, locals: { config: SLACK_CONFIG }
end
# OAuth flow
get '/finish_auth' do
client = Slack::Web::Client.new
# OAuth Step 3: Success or failure
begin
response = client.oauth_access(
{
client_id: SLACK_CONFIG[:slack_client_id],
client_secret: SLACK_CONFIG[:slack_api_secret],
redirect_uri: SLACK_CONFIG[:slack_redirect_uri],
code: params[:code] # (This is the OAuth code mentioned above)
}
)
STDERR.puts response unless ENV['RACK_ENV'] == 'test'
# Success! Let's store access_token for this team
team_id = response['team_id']
access_token = response['access_token']
team_name = response['team_name']
# if it's a returning team, let's update the token instead
if team = Team.find_by_external_id(team_id)
team.update(access_token: access_token, name: team_name)
else
Team.create(external_id: team_id, access_token: access_token, name: team_name)
end
redirect "/yay?team_name=#{team_name}"
rescue Slack::Web::Api::Error => e
status 403
body "Auth failed! Reason: #{e.message}<br/>"
end
end
get '/yay' do
status 200
erb :yay, locals: { team_name: params['team_name'] }
end
end