ben

OMÜ , Bilgisayar Mühendisliği, 13'

19 Ağustos 2015 Çarşamba

rails-devise-omniouth-google_oauth2

Google üzerinden  proje oluştrup apı ve secret keylerini elde edelim bunu için aşağıdaki adrese gidelim:



https://console.developers.google.com/start

create a projecc
project name: railsPlus

Proje oluştugunda ana sayfa ekranı gelecek, burdan olusturduğumuz projeyi seçelim. 

apis&auth=>ApıS=>Google+Apı=> enabled tıkla


Görünüm böyle olmalı:


apis&auth=> credentials=>add credential=>OAuth 2.0 client ID

HomePageUrl: http://localhost:3000/     =>Save

Wep Application=>configure consent screen




Gelen ekrandı ID ve Secret Keyleri oluştu. Gelelim Rails tarafına bunun için onceki yazıda bahsedilen devise modelinin oldugu program üzerinden devam edicem.

Öncelikle User modeline name ve image adlı string alanlar ekleyelim.

$ rails g migration AddNameToUser name: string
$ rails g migration AddImageToUser  image: string
$ rake db:migrate

Birde Normal kayıtlı kullanıcılara resim ekleyelim bunun için carrierview gemini kullanıcaz.

Gemfile=>  gem 'carrierview'

$rails generate uploader Avatar
$rails g migration AddAvatarToUser avatar: string
$rake db:migrate

User modeline:   mount_uploader :avatar, AvatarUploader

app/view/devise/registration/new.html.erb dosyalarına resim ekleme satırını ekleyelim:

  <div class="field">
      <%= f.file_field :avatar %>
  </div>


User Modelini hazırladığımıza gore Google kullanıcı girişine geçelim. gerekli gemi ekliyoruz:

*gem 'omniauth-google-oauth2'  
*gem 'omniauth' , '>= 1.0.0'

$bundle

$ rails g migration AddOmniauthToUsers provider:index uid:index
$ rake db:migrate



* initializers/devise.rb

  require "omniauth-google-oauth2"  config.omniauth :google_oauth2, "GoogledanalınanIdApı","GoogledanalınanSecretApı", scope: 'email', info_fields: 'email, name' ,:client_options => {:ssl => {:ca_file => '/usr/lib/ssl/certs/ca-certificates.crt'}}


* app/models/user.rb

 devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:google_oauth2]


 config/routes.rb

 devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }

* app/controllers/users/omniauth_callbacks_controller.rb bu dosyayı oluşturalım


 def google_oauth2
            # You need to implement the method below in your model (e.g. app/models/user.rb)
            @user = User.find_for_google_oauth2(request.env["omniauth.auth"])
            @user.image=request.env["omniauth.auth"].info.image
            if @user.persisted?
              sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
              set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
              # flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
              # sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
            else
              session["devise.google_data"] = request.env["omniauth.auth"]
              redirect_to new_user_registration_url
            end
      end



* app/models/user.rb

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]
        user.name = auth.info.name   # assuming the user model has a name
        user.image = auth.info.image # assuming the user model has an image

      end
end


  def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
        data = access_token.info
        user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
        if user
            return user
        else
            registered_user = User.where(:email => access_token.info.email).first
            if registered_user
                 return registered_user
             else
                 user = User.create(name: data["name"],
                provider:access_token.provider,
                email: data["email"],
                uid: access_token.uid ,
                password: Devise.friendly_token[0,20], )
           end
       end
  end


app/views/post/index.html

br
  =current_user.provider
br
  =current_user.email
br
  =current_user.name
br
 -if current_user.image!=nil
    = image_tag(current_user.image)
 -else
    =image_tag(current_user.avatar_url)


çalıştırıp bakalım:


Sign in with Google Outh2 ile giriş yapalım: