github中的Authorization callback URL
https://www.zhengjiajun.com/auth/github/callback
参考resume的代码进行设置
#config/initializer/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, Rails.application.credentials.dig(:development, :github_id),
Rails.application.credentials.dig(:development, :github_secret)
end
#user.rb
def find_by_omniauth(auth)
user = User.find_by_provider_and_nickname(auth["provider"], auth["info"]["nickname"])
user ? user : User.create_with_omniauth(auth)
end
def create_with_omniauth(auth)
create! do |user|
random_password = SecureRandom.hex(9)
user.provider = auth["provider"]
user.nickname = auth["info"]["nickname"]
user.password = random_password
user.password_confirmation = random_password
user.name_en = auth["info"]["nickname"] + "-" +RandomCode.generate_name_uuid
end
end
#sessions_controller.rb
def create
user = User.find_by_omniauth(auth)
log_in user
flash[:success] = t('github_login_successfully')
redirect_to edit_user_path(user)
end
#view
<a href="/auth/github">login</a>