Skip to content

Instantly share code, notes, and snippets.

@mattboldt
Last active April 21, 2017 16:59
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mattboldt/7865054 to your computer and use it in GitHub Desktop.
OmniAuth & Octokit.
class AuthenticationsController < ApplicationController
# This is the callback method from OmniAuth's GitHub authentication.
# following http://railscasts.com/episodes/236-omniauth-part-2
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
sign_in_and_redirect(:user, authentication.user)
end
# lots more code goes here, but you get the point.
# It authenticates and I can grab the OAuth token from omniauth['credentials']['token']
# calling a custom method that will later be in the controller, but is instead here to test.
save_update_to_github
end
# This should look very familiar.
def save_update_to_github
# since this is here, I can grab the token directly. Otherwise I'd get it from the DB.
token = request.env["omniauth.auth"]["credentials"]["token"]
github = Octokit::Client.new(:oauth_token => token)
repo = 'mattboldt/blogtest'
ref = 'heads/master'
sha_latest_commit = github.ref(repo, ref).object.sha
sha_base_tree = github.commit(repo, sha_latest_commit).commit.tree.sha
file_name = "test.md"
blob_sha = github.create_blob(repo, Base64.encode64("some placeholder code, will be a @post param later."), "base64")
sha_new_tree = github.create_tree(repo,
[ { :path => file_name,
:mode => "100644",
:type => "blob",
:sha => blob_sha } ],
{:base_tree => sha_base_tree }).sha
commit_message = "Committed via Octokit!"
sha_new_commit = github.create_commit(repo, commit_message, sha_new_tree, sha_latest_commit).sha
updated_ref = github.update_ref(repo, ref, sha_new_commit)
puts updated_ref
end
end
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, 'ID', 'TOKEN', :scope => 'repo,gist'
end
# callback routes that go to authentications controller.
get "/auth/:provider/callback" => 'authentications#create'
get "/auth/failure" => "authentications#failure"
@siebertm
Copy link

Thanks for the writeup!
I noticed though, that for the current version of octokit (4.7.0), you'll have to use access_token: token instead of oauth_token.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment