-
-
Notifications
You must be signed in to change notification settings - Fork 40
OmniAuth
Janko Marohnić edited this page Nov 3, 2022
·
4 revisions
The rodauth-omniauth gem provides login and registration functionality with multiple providers using OmniAuth, together with persistence of external identities.
Let's assume we're building Facebook login, and we've already set up a Facebook OAuth 2.0 application for our project. We'll start by installing the necessary gems:
$ bundle add rodauth-omniauth omniauth-facebook
Let's save Facebook app key and secret in our project credentials:
$ rails credentials:edit
# ...
facebook:
app_id: "<YOUR_APP_ID>"
app_secret: "<YOUR_APP_SECRET>"
We'll also create the identities table required by rodauth-omniauth:
$ rails generate migration create_account_identities
$ rails db:migrate
# db/migrate/*_create_account_identities.rb
class CreateAccountIdentities < ActiveRecord::Migration
def change
create_table :account_identities do |t|
t.references :account, foreign_key: { on_delete: :cascade }
t.string :provider, null: false
t.string :uid, null: false
t.index [:provider, :uid], unique: true
end
end
end
Now we can register the facebook strategy in our Rodauth configuration:
# app/misc/rodauth_main.rb
class RodauthMain < Rodauth::Rails::Auth
configure do
enable :omniauth
omniauth_provider :facebook,
Rails.application.credentials.facebook[:app_id],
Rails.application.credentials.facebook[:app_secret],
scope: "email"
end
end
Finally, we can add the Facebook login button to our login form:
$ rails generate rodauth:views login
<!-- app/views/rodauth/_login_form_footer.html.erb -->
<!-- ... -->
<li>
<%= button_to "Login via Facebook", rodauth.omniauth_request_path(:facebook),
method: :post, data: { turbo: false }, class: "btn btn-link p-0" %>
</li>
<!-- ... -->