Use sorcery for logins
This gives us more flexibility and allows us to use password authentication later. Also we don't need to build the login functionality ourself.
This commit is contained in:
34
app/controllers/oauths_controller.rb
Normal file
34
app/controllers/oauths_controller.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
class OauthsController < ApplicationController
|
||||
|
||||
# Sends the user on a trip to the provider,
|
||||
# and after authorizing there back to the callback url.
|
||||
def oauth
|
||||
login_at(params[:provider])
|
||||
end
|
||||
|
||||
def callback
|
||||
provider = params[:provider]
|
||||
if @user = login_from(provider)
|
||||
redirect_to root_path, :notice => "Logged in from #{provider.titleize}!"
|
||||
else
|
||||
begin
|
||||
@user = create_from(provider)
|
||||
if authentication = @user.authentications.find_by(provider: provider)
|
||||
authentication.update({
|
||||
access_token: @access_token.token,
|
||||
refresh_token: @access_token.refresh_token,
|
||||
expires_at: Time.at(@access_token.expires_at)
|
||||
})
|
||||
end
|
||||
|
||||
reset_session
|
||||
auto_login(@user)
|
||||
redirect_to root_path, :notice => "Logged in from #{provider.titleize}!"
|
||||
rescue
|
||||
Rails.logger.error("Failed to login from #{provider}")
|
||||
redirect_to root_path, :alert => "Failed to login from #{provider.titleize}!"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
@@ -1,29 +1,7 @@
|
||||
require 'google/apis/oauth2_v2'
|
||||
class SessionsController < ApplicationController
|
||||
|
||||
def new
|
||||
reset_session
|
||||
redirect_to auth_client.authorization_uri.to_s
|
||||
end
|
||||
|
||||
def auth
|
||||
reset_session
|
||||
if params[:error]
|
||||
flash[:error] = 'Login failed'
|
||||
redirect_to root_url
|
||||
else
|
||||
auth_client.code = params[:code]
|
||||
auth_client.fetch_access_token!
|
||||
|
||||
@user, @authentication = User.find_by_oauth_info(auth_client)
|
||||
if @user.persisted? && @authentication.persisted?
|
||||
session[:user_id] = @user.id.to_s
|
||||
redirect_to forms_url
|
||||
else
|
||||
flash[:error] = 'Login failed'
|
||||
redirect_to root_url
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@@ -31,18 +9,4 @@ class SessionsController < ApplicationController
|
||||
redirect_to root_url
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def auth_client
|
||||
@auth_client ||= CLIENT_SECRETS.to_authorization.tap do |c|
|
||||
c.update!(
|
||||
scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/spreadsheets',
|
||||
redirect_uri: auth_url,
|
||||
additional_parameters: {
|
||||
'access_type' => 'offline', # offline access
|
||||
'include_granted_scopes' => 'true' # incremental auth
|
||||
}
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user