How to devise (for authentication)
gem 'devise
bundle install
rails generate devise:install
config/initializers/devise.rb
rails g devise User
rake routes
rake db:migrate
rails g controller Home
home#index
with viewsconfig/routes.rb
, add root 'home#index'
before_action :authenticate_user!
above index action
ApplicationController
to keep code dry
instead of adding to every controller<%= link_to("Sign Out", destroy_user_session_path, :method => 'delete') %>
user
model migration Rails (5.x.x)rails g migration AddUserRefToTableName user:references
(where TableName
refers to the table that belongs_to a user
)def change
add_reference :posts, :user, foreign_key: true, index: true
# add_foreign_key :posts, :users
end
add_foreign_key
part, error when migratingusers
table
add_foreign_key
is used to ensure referential integrityforeign_key
to the user_id
column of the posts
tableid
column of the users
tablebefore_action :authenticate_user!
: authenticates the user to be able to access
certain pages
User
, say Person
, just replace _user
with _person
, generically _modelname
user_signed_in
: verifies if a user is signed incurrent_user
: to find the currently signed in useruser_root_path
if it
exists, otherwise, the default root_path
will be usedafter_sign_in_path
and after_sign_out_path
users
table contains a field for encrypted_password
database_authenticatable
, password
is also used as an attr_reader
and setter
method:# Generates a hashed password based on the given value.
# For legacy reasons, we use `encrypted_password` to store
# the hashed password.
def password=(new_password)
@password = new_password
self.encrypted_password = password_digest(@password) if @password.present?
end
password
in you DB seeding and encrypted_password
will also be set!user.rb
:devise :omniauthable, :omniauth_providers => [:facebook]
website/users/auth/facebook/callback
<%= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path %>
devise_for :users, :controllers => { :omniauth_callbacks => 'users/omniauth_callbacks' }
app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
sign_in_and_redirect @user
end
end
# in the User model:
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
sign_in_and_redirect
method, unfortunately doesn't tell devise where to redirect:# in ApplicationController
def after_sign_in_path_for(resource)
request.env['omniauth.origin'] || root_path
end
rails g devise:views
views/devise
to better customize forms