config/boot.rbに以下を追記する
require 'rails/commands/server' module Rails class Server def default_options super.merge({ :Port => 4000, }) end end end
require 'rails/commands/server' module Rails class Server def default_options super.merge({ :Port => 4000, }) end end end
rails3でmysqlを使おうとすると、gem mysql2 を要求された。
なので、config/database.ymlには以下みたいになるが、rinari-sql は "sql-<adapter名>" という名前の関数を探しにいくので、emacs側でsql-mysql2がないというエラーになる。
development: adapter: mysql2 database: foo host: localhost port: 3306 username: bar password: baz encoding: utf8 pool: 5 timeout: 5000
これを避けるには、以下のようにしてsql-mysql2にaliasをはるelispをかけばOK
(defalias 'sql-mysql2 'sql-mysql)
前回(http://taksatou.blogspot.com/2011/03/twitterfacebookrails.html) 、OAuthで認証するところまでできたので、今回はtwitterアカウントでログインするところを作ります。
omniauthのrailsチュートリアルビデオのpart2に大体対応してますが、ここでの内容はちょっと変えてます。
- http://railscasts.com/episodes/236-omniauth-part-2
以下のようにしてdeviseのセットアップとmigrationをします。
emailとpasswordはつかわないので消します。
rails g devise:install rails g devise user rails g migration AddOauthTokenAndOauthTokenSecretToAuthentications oauth_token:string oauth_token_secret:string rails g migration RemoveEmailAndEncryptedPasswordAndPasswordSaltFromUsers email:string encrypted_password:string password_salt:string rake db:migrate
class Authentication < ActiveRecord::Base belongs_to :user end
class User < ActiveRecord::Base has_many :authentications devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable def password_required? false end end
前回編集したAuthenticationsControllerをさらに以下のように編集します。
class AuthenticationsController < ApplicationController def create omniauth = request.env['omniauth.auth'] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication sign_in_and_redirect(:user, authentication.user) elsif current_user # 既にログインしてるけど、facebookとかの権限も追加するとき current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :oauth_token => omniauth['credentials']['token'], :oauth_token_secret => omniauth['credentials']['secret']) redirect_to authentications_url else # 新規ユーザのとき user = User.new user.authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'], :oauth_token => omniauth['credentials']['token'], :oauth_token_secret => omniauth['credentials']['secret']) user.save! sign_in_and_redirect(:user, user) end end
確認用にauthenticateのviewを以下のように編集します
<h1>Authentications</h1> <% if user_signed_in? %> Signed in as <%= current_user.id %> Not you ? <%= link_to "Sign out", destroy_user_session_path %> <% else %> <%= link_to "Sign in", "/auth/twitter" %> <% end %> <table> <tr> <th>User</th> <th>Provider</th> <th>Uid</th> </tr> <% if @authentications %> <% for authentication in @authentications %> <tr> <td><%= authentication.user_id %></td> <td><%= authentication.provider %></td> <td><%= authentication.uid %></td> <td><%= link_to "Destroy", authentication, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> <% end %> </table>
前回設定した内容にdevise用の設定も追加します
devise_for :users resources :authentications match '/auth/:provider/callback' => 'authentications#create' root :to => "authentications#index"
以上でセットアップはおわりです。
実際に http://localhost:3000/authentications にアクセスしてsign in をクリックしてうまくログインできれば成功です。
以下のようにすればコンソールでtwitterにポストの確認ができるはずです。
$ rails c Twitter.configure do |config| config.consumer_key = 'CONSUMER_KEY' config.consumer_secret = 'CONSUMER_SECRET' config.oauth_token = User.all[0].authentications[0].oauth_token config.oauth_token_secret = User.all[0].authentications[0].oauth_token_secret end Twitter.update 'hello, omniauth!'
OAuthをつかっていろんなサービスと連動したアプリケーションがつくりたくなったので調査。
railsでやるにはoauth_pluginとかwarden_oauthとか色々なプラグインがあるみたいだけど、omniauthがよさそうです。
rails初心者なので基本的にはomniauthのチュートリアルビデオに沿って作業します。
- https://github.com/intridea/omniauth
- http://railscasts.com/episodes/235-omniauth-part-1
自前でパスワードやメールアドレスは保持せずに、twitterやfacebookのアカウントを使ってログインできるようにするのが目標です。
ちなみにtwitter anywhereを使えば似たようなことはできそうですが、twitterに依存してしまうので今回はパス。
Contents
--
とりあえず以下を追記。nifty-generators, twitterはお好みで。deviseは後半で使います
gem 'devise' gem 'omniauth' gem 'nifty-generators', :group => :development gem 'twitter'
config/initializers/omniauth.rbを作成
Rails.application.config.middleware.use OmniAuth::Builder do privider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET' end
ここでセットするoauthアプリケーションは、twitter側で正しくcallback urlを設定しておく必要があります。
通常は http://yourhost.com/auth/twitter/callback のようなURLです。
そうしておかないと、twitterにリダイレクトされる前で 401 unauthorized となってはじかれます。
ここではnifty generatorをつかいます
rails g nifty:scaffold authentication user_id:integer provider:string uid:string index create destroy
できたAuthenticationsControllerのcreateを以下のように書き換えます。
class AuthenticationsController < ApplicationController def create render :text => request.env['omniauth.auth'].to_yaml end
request.env['omniauth.auth']の部分は過去のバージョンではrequest.env['rack.auth']なので、うまくいかない場合はバージョンを確認してください。
callback用に以下を追記します
match '/auth/:provider/callback' => 'authentications#create'
ここまでやって http://localhost:3000/auth/twitter にアクセスしてtwitterで認証すると、yamlで認証情報が取得できているのが確認できます。
以上でとりあえずOAuthでユーザ情報やcredentialをとることができました。
次回( http://taksatou.blogspot.com/2011/03/twitterfacebookoauthrailsomniauth.html )後半でtwitterでログインするところをつくります。