Skip to content

Instantly share code, notes, and snippets.

@yoppi
Created May 15, 2014 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoppi/8494ac5e7b31bdbe8c9a to your computer and use it in GitHub Desktop.
Save yoppi/8494ac5e7b31bdbe8c9a to your computer and use it in GitHub Desktop.
Twitter OAuth
class AuthController < ApplicationController
OAUTH_SITE = "https://api.twitter.com"
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token";
AUTHORIZE_URL = "https://api.twitter.com/oauth/authenticate";
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
CONSUMER_KEY = "xxx"
CONSUMER_SECRET = "xxx"
before_action :consumer, only: [:twitter]
def twitter
if session[:access_token]
redirect_to news_index_url
return
end
request_token = @consumer.get_request_token(oauth_callback: CALLBACK_URL)
session[:request_token] = request_token
redirect_to request_token.authorize_url
end
def callback
request_token = session[:request_token]
unless request_token
redirect_to news_index_url
return
end
access_token = request_token.get_access_token(oauth_verifier: params[:oauth_verifier])
session[:access_token] = access_token
# 初回ユーザ登録
User.where(twitter_id: access_token.params[:user_id]).first_or_create
redirect_to news_index_url
end
def logout
reset_session
redirect_to news_index_url
end
private
def consumer
@consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, {
site: OAUTH_SITE,
request_token_path: "/oauth/request_token",
authorize_path: "/oauth/authenticate",
access_token_path: "/oauth/access_token",
}
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment