I am building an app that already has an authentication system with has_secure_password but I would like to add Facebook and Twitter authentication as well through Omniauth however I don’t know the best strategy to do this.Should I create a separate Identity model and add them there.But how do I integrate that with my existing authentication?Here is what the authentication currently looks like
User.rb
class User < ActiveRecord::Base
before_create :create_remember_token
has_secure_password
validates :name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, uniqueness: true, format: {with: VALID_EMAIL_REGEX }
validates :last_name, presence: true
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
SessionsController
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to users_path(user), success: 'Başarılı bir şekilde giriş yapıldı!'
else
redirect_to root_path, danger: 'Giriş sırasında sorun oluştu lütfen bilgilerin doğruluğunu kontrol et'
end
end
def destroy
sign_out
redirect_to root_path, success: 'Başarılı bir şekilde çıkış yapıldı.'
end
end
SessionHelper
def sign_in(user)
remember_token = User.new_remember_token
if params[:remember_me]
cookies.permanent[:remember_token] = remember_token
else
cookies[:remember_token] = remember_token
end
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def signed_in?
!current_user.nil?
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
end