35

Rails 与 Slack 整合指南 (1)

 5 years ago
source link: http://blog.xdite.net/posts/2018/06/17/rails-and-slack-integration-guide-1?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

整理一下之前的 Slack 整合笔记。接 Slack 还是有挺多坑的。这篇主要写登入整合。

整合 slack 主要靠三个 gem deviseomniauthomniauth-slack

安装 devise

  • bundle install devise
  • rails g devise:install
  • rails g devise user
  • rails g devise:views

把 devise 先跑起来,然后 view 也下载下来

安装 omniauth

  • bundle install omniauth
  • user model 挂上 omniauthable
xSUejc+

安装 omniauth-slack

  • bundle install omniauh-slack
  • 先去 https://api.slack.com/apps 申请 API KEY。里面只有两个会用到:
    • Client ID
    • Client Secret
HhVZXX+
  • 设定权限。记得要特别设 identity.email 才拿得到 email
config/initiailizers/devise.rb
config.omniauth :slack, ENV['SLACK_APP_ID'], ENV['SLACK_APP_SECRET'], scope: 'identity.basic,identity.email'   # 用 identity.email 能拿到 email

  config.omniauth :slack, ENV['SLACK_APP_ID'], ENV['SLACK_APP_SECRET'], scope: 'team:read,users:read'

设定 callbacks 网址

r2clK0+

记得要设 callbacks

Rails App 怎么接进来的资料

config/routes.rb
Rails.application.routes.draw do
  devise_for :users, :controllers => {  :omniauth_callbacks => "users/omniauth_callbacks"}
end
  • User has_many :team_users , has_many :teams, :through => :team_users

讲解细节

  • devise 与 omniauth-slack 生成的认证连结会是 https://localhost:3000/users/auth/slackcallback 。 也会从这里回来。
  • 另外造一个 users/omniauth_callbacks 的 controller 来收 callback
  • 做一个 User.find_or_create_for_slack 去解析 request.env["omniauth.auth"] 收进来的资料
  • 收进来的资料格式,omniauth-slack 这里有整理一份 https://github.com/kmrshntr/omniauth-slack
  • 不过还是要一直开著 Rails.logger.warn 去看一下打进来的资料。因为 scope 不对,会拿不到关键信息。
  • scope 列表在这: https://api.slack.com/docs/oauth-scopes
  • 主要有用的是 identity.basic,identity.email, team:read, users:read
  • authorization 记的表主要是 provider 与 slack 给的 uid

几个坑

  • 网上范例只给 identity.basic ,这是拿不到东西的。而且 slack 对拿 email 很严。搞了一晚上才确定 identity.email 才拿得到 email,非常蛋疼。
  • Rails 改版了,现在要从 request.env 才拿得到资料
  • slack 回传资料非常巢状,数错层就拉不到资料。有些资料要反覆调试 scope 才拿得到。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK