- Code: https://github.com/applegrain/oauth-example
- OAuth Protocol: http://tools.ietf.org/html/rfc6749#section-1.2
- Omniauth: https://github.com/intridea/omniauth
-
Create an app on github (make sure the callback url is http://localhost:3000/auth/github/callback)
-
Add an initializer, config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
end
-
Add key and secret. Make sure that you can access the keys in the rails console like this:
ENV["GITHUB_SECRET"]
ENV["GITHUB_KEY"]
-
Change login link in home.html.erb to “/auth/github”
-
Create callback route: routes.rb,
get '/auth/:provider/callback', to: 'sessions#create'
-
Create a sessions controller
- add a #create action in the sessions controller
def create @user = User.find_or_create_from_auth(request.env['omniauth.auth']) if @user session[:user_id] = @user.id redirect_to dashboard_path else redirect_to root_path end end
-
Create user model: nickname, email, provider, token, uid, image_url, token
-
In the user model, build the class method #find_or_create_from_auth that we referenced in sessions#create
def self.find_or_create_by_auth(auth)
user = User.find_or_create_by(provider: auth['provider'], uid: auth['uid'])
user.nickname = auth['info']['nickname']
user.name = auth['info']['name']
user.email = auth['info']['email']
user.image_url = auth['info']['image']
user.token = auth['credentials']['token']
user.save
user
end
- Create current user method in application controller
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def authorize!
redirect_to root_path unless current_user
end
-
Add destroy action in sessions controller
-
routes.rb: “delete '/logout', to: 'sessions#destroy'”
Nevermind, it appears that I had to wait like half a day for GitHub to start authorizing and responding to my requests after I registered a new app