Skip to content

Social sign‐ins using OmniAuth example

Mikkel Malmberg edited this page Dec 5, 2023 · 1 revision

Passwordless doesn't have social sign ins built in but you can build it yourself.

Here's an example setup to work with OmniAuth:

$ bin/rails g model Credential user:belongs_to provider uid:text data:jsonb
class Credential < ApplicationRecord
  validates :provider, presence: true
  validates :uid, presence: true

  belongs_to :user, required: true, validate: true
end
class OmniSessionsController < ApplicationController
  skip_before_action :authenticate_user!

  protect_from_forgery except: :create

  def create
    credential_attrs = {
      provider: auth_hash["provider"],
      uid: auth_hash["uid"]
    }

    if credential = Credential.find_by(credential_attrs)
      user = credential.user
    elsif user = User.where("lower(email) = ?", auth_hash["info"]["email"]).first
      credential = Credential.create!(user:, **credential_attrs)
      # optionally notify the user that someone signed in using a new service
    else
      user = User.create!(email: auth_hash["info"]["email"])
      credential = Credential.create!(user:, **credential_attrs)
    end

    sign_in(create_passwordless_session!(user))

    redirect_to(reset_passwordless_redirect_location!(User) || root_path)
  end

  private

  def auth_hash
    request.env["omniauth.auth"]
  end
end