Instantly share code, notes, and snippets.

View twitter-rails.sh
$ rails generate controller Sessions
View index.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Twitter連携</title>
</head>
<body>
<h1>Twitter連携</h1>
<% if flash[:notice] %>
<p><%= flash[:notice] %></p>
<% end %>
View sessions_controller.rb
class SessionsController < ApplicationController
def create
# request.env['omniauth.auth']にユーザのTwitter認証情報が格納されている
user_data = request.env['omniauth.auth']
session[:nickname] = user_data[:info][:nickname]
redirect_to root_path, notice: 'ログインしました'
end
end
View routes.rb
Rails.application.routes.draw do
root 'homes#index'
get '/homes/', to: 'homes#index'
get '/auth/:provider/callback', to: 'sessions#create'
end
View omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, "API_KEY", "API_SECRET"
end
View twitter-auth.sh
$ rails new rails-auth-app
$ cd rails-auth-app
View twitter-auth.sh
https://ドメイン/auth/twitter/callback
http://ドメイン/auth/twitter/callback
View twitter-auth.sh
http://127.0.0.1:3000/auth/twitter/callback
http://localhost:3000/auth/twitter/callback