Skip to content

Instantly share code, notes, and snippets.

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
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)
# 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.
# 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 = => 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 = ""
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
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, 'ID', 'TOKEN', :scope => 'repo,gist'
# callback routes that go to authentications controller.
get "/auth/:provider/callback" => 'authentications#create'
get "/auth/failure" => "authentications#failure"
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