Implement Google OAuth2 authentication

This commit is contained in:
Eugene Burmakin 2025-10-26 15:50:47 +01:00
parent af71661e2b
commit 48e50c2ee8
3 changed files with 14 additions and 3 deletions

View file

@ -2,13 +2,22 @@
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def github def github
handle_auth('GitHub')
end
def google_oauth2
handle_auth('Google')
end
private
def handle_auth(provider)
@user = User.from_omniauth(request.env['omniauth.auth']) @user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted? if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'GitHub' flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: provider
sign_in_and_redirect @user, event: :authentication sign_in_and_redirect @user, event: :authentication
else else
session['devise.github_data'] = request.env['omniauth.auth'].except('extra')
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n") redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end end
end end

View file

@ -4,7 +4,7 @@ class User < ApplicationRecord # rubocop:disable Metrics/ClassLength
include UserFamily include UserFamily
devise :database_authenticatable, :registerable, devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :trackable, :recoverable, :rememberable, :validatable, :trackable,
:omniauthable, omniauth_providers: %i[github] :omniauthable, omniauth_providers: %i[github google_oauth2]
has_many :points, dependent: :destroy has_many :points, dependent: :destroy
has_many :imports, dependent: :destroy has_many :imports, dependent: :destroy

View file

@ -266,6 +266,8 @@ Devise.setup do |config|
# Add a new OmniAuth provider. Check the wiki for more information on setting # Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks. # up on your models and hooks.
config.omniauth :github, ENV['GITHUB_OAUTH_CLIENT_ID'], ENV['GITHUB_OAUTH_CLIENT_SECRET'], scope: 'user:email' config.omniauth :github, ENV['GITHUB_OAUTH_CLIENT_ID'], ENV['GITHUB_OAUTH_CLIENT_SECRET'], scope: 'user:email'
config.omniauth :google_oauth2, ENV['GOOGLE_OAUTH_CLIENT_ID'], ENV['GOOGLE_OAUTH_CLIENT_SECRET'],
scope: 'userinfo.email,userinfo.profile'
# ==> Warden configuration # ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or # If you want to use other strategies, that are not supported by Devise, or