티스토리 뷰
Devise gem 사용하기 2
Facebook 연동하기 설명서
결과 github
https://github.com/likesoomti/facebook-devise-rails
Get Started
1. Gemfile 설치
gem 'omniauth'
gem 'omniauth-facebook'
2. Gem 적용 하기
terminal
$ bundle install
3. SNS 모델을 저장할 테이블 만들기
terminal
$ rails g model sns_user user:references provider:string uid:string
결과창
Running via Spring preloader in process 20174
invoke active_record
create db/migrate/20171113045119_create_sns_users.rb
create app/models/sns_user.rb
invoke test_unit
create test/models/sns_user_test.rb
create test/fixtures/sns_users.yml
모델 저장하기
terminal
$ rails db:migrate
4. ominauth 설정
config/initializers/devise.rb
config.omniauth :facebook, ENV["Facebook_Key"], ENV["Facebook_Secret"]
(참고) 키 관리하기
FACEBOOK_KEY
, FACEBOOK_SECRET
은
- https://developers.facebook.com/
에서 프로젝트 생성한 뒤 받을 수 있습니다. git에 key,secret을 올리게 되면 다른 사람들이 다 볼 수 있어 보안성이 떨어집니다. 이때 Rails에서 제공하는Secret.yml
이나Figaro gem
을 사용하여 키 관리를 할 수 있습니다.
Secret.yml reference
example
Secrets.yml
development:
facebook_app_id: 11234325
facebook_app_secret: 75fbbcdfqewteqwtwte
use
Rails.application.secrets.facebook_app_id
Figaro gem
5.routes 설정
config/routes.rb
# before
# devise_for :users
# after ++ add
devise_for :users, :controllers => { omniauth_callbacks: 'user/omniauth_callbacks'}
6. Button 만들기
facebook 버튼 만들기. 뷰는 알아서 shared/_links 에서 넣어줘서 고칠필요 없습니다 확인 차원에 넣어보았습니다
app/views/devise/shared/_links.html.erb
<%- if controller_name != 'sessions' %>
<%= link_to "Log in", new_session_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
<%= link_to "Sign up", new_registration_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
<%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
<%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
<%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.omniauthable? %>
<%- resource_class.omniauth_providers.each do |provider| %>
<%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %><br />
<% end -%>
<% end -%>
6. Controller 설정
app/controllers/user/omniauth_callbacks_controller.rb
class User::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# 프로바이더 값을 가져온다
# 클래스를 이름마다 생성
# user 값과 auth 값을 보내줌
# 페이스북 경로
def facebook
# User 모델에 설정된 find_for_oauth 호출
@user = User.find_for_oauth(request.env["omniauth.auth"], current_user)
# 유저 값이 존재하면 로그인
if @user.persisted?
sign_in_and_redirect @user, event: :authentication
else
# 아니라면 유저 등록 페이지
session["devise.facebook_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
# 로그인 이후 경로 설정
def after_sign_in_path_for(resource)
@user = User.find(current_user.id)
if @user.persisted?
sign_add_path
else
main_path
end
end
end
5. 모델 설정
app/models/user.rb
# before
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# after
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
# self.find_for_oauth(SNS 토큰, current_user)
def self.find_for_oauth(auth, signed_in_resource = nil)
sns_user = SnsUser.find_for_oauth(auth)
user = signed_in_resource ? signed_in_resource :
sns_user.user
# 유저가 없으면 이메일 찾아 유저 값있는지 확인
if user.nil?
email = auth.info.email
user = User.where(:email => email).first
# 유저이메일에 해당하는 아이디가 없으면 하나 db에 만들어놓는다.
unless self.where(email: auth.info.email).exists?
# 유저가 그럼에도 없음 값을 넣어준다
if user.nil?
user = User.new
user.email = auth.info.email
user.profile_image = auth.info.image
user.password = Devise.friendly_token[0,20]
user.save!
end
end
end
if sns_user.user != user
sns_user.user = user
sns_user.save!
end
user
end
app/models/sns_user.rb
sample
class SnsUser < ApplicationRecord
belongs_to :user
# add
# 유효성 설정
validates_presence_of :uid, :provider
validates_uniqueness_of :uid, :scope => :provider
# uid 값 넣어주기
def self.find_for_oauth(auth)
find_or_create_by(uid: auth.uid, provider: auth.provider)
end
end
facebook developer
URL을 읽어들일 수 없음: 앱 도메인에 포함되어 있지 않은 URL입니다. 이 URL을 읽어들이려면 앱 설정에서 앱 도메인 필드에 앱의 모든 도메인과 서브 도메인을 추가하세요.
페이스북 로그인 설정
유효한 OAuth 리디렉션 URI 에 도메인 설정
포함(embed)된 브라우저 OAuth 로그인
OAuth 클라이언트 로그인을 위해 브라우저 제어 리디렉션 URL을 활성화합니다 버튼 설정!
2018년 페이스북 3월
HTTPS를 실행하세요.
이 설정에는 OAuth 리디렉션용 HTTPS 및 JavaScript SDK를 사용하여 액세스 토큰을 가져오는 페이지가 필요합니다. 2018년 3월 현재 새로 만든 모든 앱에는 기본적으로 이 설정이 포함되며, 2019년 3월까지 모든 기존 앱을 HTTPS URL만 사용하도록 마이그레이션해야 합니다. 대부분의 주요 클라우드 앱 호스트는 앱에 대한 TLS 인증서를 무료로 자동 구성해줍니다. 앱을 자체 호스트하거나 호스팅 서비스에서 기본적으로 HTTPS를 제공하지 않는 경우 Let's Encrypt에서 도메인에 대한 무료 인증서를 얻을 수 있습니다.
strict 모드 강제 활성화
원래는 strict모드를 활성화 / 비활성화 할 수 있었는데, 정책 변경으로 https 와 strict 모드가 강제 설정이 된 것 같다.
solve
위를 고대로 따라했다면,
페이스북 로그인 > 설정 > 유효한 OAuth 리디렉션 url 에
https://도메인/users/auth/facebook/callback
을 추가한다
/auth/facebook 만 쳤다가 한시간 또 삽질했당 나같은 사람 없길 ㅠㅠ!
'Ruby On Rails' 카테고리의 다른 글
ActiveRecord::Enum 활용해보기 (0) | 2017.12.04 |
---|---|
[ROR] Rails - kaminari gem을 사용한 무한 스크롤 만들기 (0) | 2017.11.24 |
[ROR] Rails Scaffold (2) | 2017.11.19 |
[Error] comparison of String with 0 failed (1) | 2017.11.13 |
[gem] Devise 사용하기 (0) | 2017.11.11 |
- Total
- Today
- Yesterday
- [Error] comparison of String with 0 failed
- git 쉽게 이해하기
- git 이란
- 네이버 카페 크롤링
- Devise
- facebook로그인
- commmit
- 어느 시점에 모든 기록이 끝나면 푸시 를 하게되고
- Ruby
- 구글 오라클
- window 레일즈 설치
- 저렇게 제목만 복제되는게 아니라 저 맨 위에 나왔던 사진처럼 메세지로 남아서 기록되게 됩니다. 저는 내컴퓨터에 서 깃헙 에 보낼 파일들에 "최종 프로젝트 라이더 친구들 이름 제거^^" 라고
- 내 깃 주소에서 프로젝트를 만드는 경우 보여주는 명령어입니다. 이에 대한 개념을 알고있어야지 커밋과 푸시를 제대로 이해할 수 있습니다. 그걸 예전에 ppt 로 간단히 택배에 비유하여 설명
- 이에 대한 개념 설명이 필요할 것 같아서 정리를 해봅니다. 깃에 대한 간단한 설명 제가 쉽게 이해한 깃은 내 컴퓨터에있는 파일들을 인터넷에 쉽게 올리기 위한 수단 입니다. 보통 우리가
- git이라는 상자를 통해 보내준다! 라고 생각하시면 더 쉬울까요..? git add git add 는 제가 github에 보낼 파일들을 상자에 넣는 역할입니다 . 을 쓰면 모든 파일을 넣어주는데요
- devise gem
- 보통 프로젝트를 협업할시에는 내 컴퓨터에 사양과 친구의 사양이 달라 보내지 말아야할 파일들이 몇개 있습니다. 그게 없다면 그냥 쉽게 . 을 통해 다 넣어주시면 됩니다. 택배로 설명하면
- 변경된 기록을 남겨주는데요 이것을 커밋 이라고합니다. 이 커밋들이 쌓여서
- devise-facebook
- 이제 제 컴퓨터에서 깃헙 프로젝트에 저는 내컴퓨터에 서 깃헙 에 택배를 보낼때는 어디로 보낼지 주소가 필요하겠죠? 프로젝트는 고유의 주소를 갖고있는데 그 주소를 적어주는 겁니다. 이
- rubyonrails
- 저는 내컴퓨터에 서 깃헙 에 보낼 파일들을 상자에 부랴부랴 쌓은거에요 git commit git commit 은 테이프 칠을 한 것이라고 생각하면됩니다. 보통 git commit -m '깃헙 내용을 쉽게 정리해봤다' 이
- Rails
- 버전? 을 관리하게 만들어주는 친구입니다. 너무 어려우면 내 컴퓨터 에 있는 프로젝트(=폴더) github 에 택배처럼 보내야하는데
- 이후에는 이 부분 없이 add commit -m push 를 사용하면 됩니다. 깃 내용 추가 및 수정 하기
- git 기본 명령어 쉽게 이해해보기 소스트리를 이용한 깃헙 프로젝트 생성하기를 만들다가
- 레일즈 설치
- 하나의 파일을 인터넷에 공유하고 같이 기록을 남겨 편리하게 해결할 수 있습니다. 위 사진처럼 제가 폴더에 내용을 추가하거나
- 푸시를 하면 제 깃주소 안에 저장되게 됩니다! 이부분을 헷갈려 하시는 분들이있는데요. 여러 명령어들과 함께 택배로 이해해 봅시다 택배로 비유해서 이해해보자 내 컴퓨터에서 프로젝
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |