Last active
October 18, 2017 22:28
-
-
Save kelby/6988736 to your computer and use it in GitHub Desktop.
使用omniauth时的controller,这与devise里的omniauthable模块差不多。但实现手法又有一点不同,选择哪个,看情况吧。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AuthenticationsController < Devise::OmniauthCallbacksController | |
before_action :create | |
def github | |
end | |
def create | |
puts "=== omniauth is: #{request.env["omniauth"]} ===" | |
puts "=== omniauth.auth is: #{request.env["omniauth.auth"]} ===" | |
omniauth = request.env["omniauth.auth"] | |
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) | |
if authentication | |
flash[:notice] = "成功登录." | |
sign_in_and_redirect(:user, authentication.user) | |
elsif current_user | |
current_user.authentications.create( | |
:provider => omniauth['provider'], | |
:uid => omniauth['uid'] , | |
:token => omniauth['credentials']['token'], | |
:secret => omniauth['credentials']['secret'] | |
) | |
redirect_to root_url, notice: "Authentication successful." | |
else | |
puts "=== will User.new" | |
user = User.new | |
user.authentications.build( | |
:provider => omniauth['provider'], | |
:uid => omniauth['uid'], | |
:token => omniauth['credentials']['token'], | |
:secret => omniauth['credentials']['secret'] | |
) | |
# 没有意义的开始 | |
user.email = omniauth[:info][:email] | |
user.password = SecureRandom.hex(10) | |
# 没有意义的结束 | |
if user.save | |
flash[:notice] = "成功登录. You password is: #{user.try(:password)}" | |
sign_in_and_redirect(:user, user) | |
else | |
puts "=== User.new and falture" | |
puts "=== user.errors #{user.errors.to_json}" | |
session[:omniauth] = omniauth.except('extra') | |
redirect_to new_user_registration_url | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment