A Rails engine that integrates OmniAuth (social authentication) with Clearance (email/password authentication). This allows users to sign in via OAuth providers (Twitter, Facebook, Google, etc.) or traditional email/password, with the ability to link multiple authentication methods to a single user account.
-
Ruby >= 3.0
-
Rails >= 7.0
-
Clearance >= 2.0
-
OmniAuth >= 2.0
Add this line to your application’s Gemfile:
gem 'clearance_omniauth'
And then execute:
$ bundle install
-
First, install Clearance if you haven’t already:
$ rails g clearance:install
-
Run the ClearanceOmniauth generator to copy migrations and create the OmniAuth initializer:
$ rails g clearance_omniauth:install This will: - Copy the authentications migration - Create config/initializers/omniauth.rb - Add authentication methods to your User model - Mount the engine in your routes
-
Run the migrations:
$ rails db:migrate
-
Add your OAuth provider gems to your Gemfile. For example:
gem 'omniauth-twitter2' gem 'omniauth-facebook' gem 'omniauth-google-oauth2' gem 'omniauth-github'
-
Configure your OAuth providers in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter2, ENV["TWITTER_CLIENT_ID"], ENV["TWITTER_CLIENT_SECRET"] provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"] provider :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"] end
You can configure redirect URLs in an initializer:
ClearanceOmniauth::Configuration.after_login_url = "/dashboard" ClearanceOmniauth::Configuration.login_failure_url = "/sign_in"
If you prefer to set things up manually:
-
Copy the migrations:
$ rake clearance_omniauth:install:migrations
-
Add to your User model:
has_many :authentications, class_name: "ClearanceOmniauth::Authentication", dependent: :destroy def apply_omniauth(omniauth) if email.blank? && omniauth["info"].present? self.email = omniauth["info"]["email"] end authentications.build(provider: omniauth["provider"], uid: omniauth["uid"]) end def password_required? return false if authentications.any? && password.blank? super end
-
Mount the engine in your routes (must be at /auth for OmniAuth):
mount ClearanceOmniauth::Engine => "/auth"
The engine provides default views for:
-
Authentication provider buttons
-
Managing linked authentications
You can override these views by creating files in your application:
-
app/views/clearance_omniauth/authentications/_auth_providers.html.erb
-
app/views/clearance_omniauth/authentications/index.html.erb
OmniAuth 2.x uses POST requests for OAuth callbacks by default for CSRF protection. This engine is configured to handle both GET and POST callbacks.
This project uses the MIT License.