Skip to content

Instantly share code, notes, and snippets.

@cigalecigales
Last active April 4, 2020 14:33
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 cigalecigales/aec7b700f52f69675e23 to your computer and use it in GitHub Desktop.
Save cigalecigales/aec7b700f52f69675e23 to your computer and use it in GitHub Desktop.
[*Rails*] deviseの使い方(rails4版) ref: https://qiita.com/cigalecigales/items/73d7bd7ec59a001ccd74
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
add_index :users, :unlock_token, unique: true
end
end
class AddColumnsToUsers < ActiveRecord::Migration
def change
add_column :users, :provider, :string
add_column :users, :uid, :string
add_column :users, :username, :string, default: "anonymous"
end
end
<!DOCTYPE html>
<html>
<head>
<title>DeviseQiita</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<header>
<nav>
<% if user_signed_in? %>
<strong><%= link_to current_user.username, pages_show_path %></strong>
<%= link_to 'プロフィール変更', edit_user_registration_path %>
<%= link_to 'ログアウト', destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to 'サインアップ', new_user_registration_path %>
<%= link_to 'ログイン', new_user_session_path %>
<% end %>
</nav>
</header>
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
<%= yield %>
</body>
</html>
class ApplicationController < ActionController::Base
(省略)...
def after_sign_in_path_for(resource)
pages_show_path
end
private
def sign_in_required
redirect_to new_user_session_url unless user_signed_in?
end
end
Devise::Mailer#confirmation_instructions: processed outbound mail in 715.1ms
Sent mail to aiueo@test.com (31.8ms)
Date: Thu, 19 Feb 2015 23:04:11 +0900
From: please-change-me-at-config-initializers-devise@example.com
Reply-To: please-change-me-at-config-initializers-devise@example.com
To: aiueo@test.com
Message-ID: <54e5ed5b8f624_5c4f3fdbda3b0c7c2258e@xxx-no-MacBook-Air.local.mail>
Subject: Confirmation instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Welcome aiueo@test.com!</p>
<p>You can confirm your account email through the link below:</p>
<p><a href="http://localhost:3000/users/confirmation?confirmation_token=kF2Fz-NGD-xh4jd5M4QF">Confirm my account</a></p>
Rails.application.configure do
# default url
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# mail setting
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "Gメールアドレス",
:password => "Gメールパスワード",
:authentication => :plain,
:enable_starttls_auto => true
}
end
Devise.setup do |config|
(省略)...
# timeout setting
config.timeout_in = 3.minutes
end
$ rails new devise
$ cd devise
$ rails g devise User
$ rails g migration add_columns_to_users provider uid username
$ rake db:migrate
$ bundle install
$ rails g controller omniauth_callbacks
{"provider"=>"twitter", "uid"=>"0123456789", "info"=>{"nickname"=>"manycicadas", "name"=>"芭蕉", "location"=>"関東", "image"=>"http://pbs.twimg.com/profile_images/483964583371997185/2ZqzhzKV_normal.png", "description"=>"デザイン系出身。プログラミングは初心者レベルを脱しませんがプロジェクトでJavaEEを使っているので勉強中です。でもRubyやRailsの勉強の方に熱が入っています。", "urls"=>{"Website"=>nil, "Twitter"=>"https://twitter.com/manycicadas"}}, "credentials"=>{"token"=>"0123456789-hQywfs78sQ9NnwpSkwiejf2Ij74sut7hKjEsF9", "secret"=>"sijIYUsiJslOhiwkYukshKKJG6skWbhbXCYji3sabla3O1"}}
$ rails g devise:install
create config/initializers/devise.rb
create config/locales/devise.en.yml
===============================================================================
Some setup you must do manually if you haven't yet:
1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:
root to: "home#index"
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:
config.assets.initialize_on_precompile = false
On config/application.rb forcing your application to not access the DB
or load models when precompiling your assets.
5. You can copy Devise views (for customization) to your app by running:
rails g devise:views
===============================================================================
$ rails g controller Pages index show
$ rails g devise:views
app/views/devise/shared/_links.html.erb (リンク用パーシャル)
app/views/devise/confirmations/new.html.erb (認証メールの再送信画面)
app/views/devise/passwords/edit.html.erb (パスワード変更画面)
app/views/devise/passwords/new.html.erb (パスワードを忘れた際、メールを送る画面)
app/views/devise/registrations/edit.html.erb (ユーザー情報変更画面)
app/views/devise/registrations/new.html.erb (ユーザー登録画面)
app/views/devise/sessions/new.html.erb (ログイン画面)
app/views/devise/unlocks/new.html.erb (ロック解除メール再送信画面)
app/views/devise/mailer/confirmation_instructions.html.erb (メール用アカウント認証文)
app/views/devise/mailer/reset_password_instructions.html.erb (メール用パスワードリセット文)
app/views/devise/mailer/unlock_instructions.html.erb (メール用ロック解除文)
source 'https://rubygems.org'
(省略)...
# Devise
gem 'devise'
gem 'omniauth-twitter'
<h1>ようこそ</h1>
<p>トップページです。</p>
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def twitter
@user = User.from_omniauth(request.env["omniauth.auth"].except("extra"))
if @user.persisted?
flash.notice = "ログインしました!"
sign_in_and_redirect @user
else
session["devise.user_attributes"] = @user.attributes
redirect_to new_user_registration_url
end
end
end
class PagesController < ApplicationController
before_action :sign_in_required, only: [:show]
(省略)...
end
Rails.application.routes.draw do
devise_for :users, controllers: { :omniauth_callbacks => "omniauth_callbacks" }
root 'pages#index'
get 'pages/show'
(省略)...
end
<h1>こんにちは、<%= current_user.username %>さん</h1>
<p>ユーザー用ページです。</p>
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable, :omniauthable, omniauth_providers: [:twitter]
def self.from_omniauth(auth)
where(provider: auth["provider"], uid: auth["uid"]).first_or_create do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.username = auth["info"]["nickname"]
end
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], without_protection: true) do |user|
user.attributes = params
user.valid?
end
else
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment