* Code: https://github.com/applegrain/oauth-example * OAuth Protocol: http://tools.ietf.org/html/rfc6749#section-1.2 * Omniauth: https://github.com/intridea/omniauth # Implement OAuth in your Rails application: 1. Create an app on github (make sure the callback url is http://localhost:3000/auth/github/callback) 2. Add an initializer, config/initializers/omniauth.rb ``` Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end ``` 3. Add key and secret. Make sure that you can access the keys in the rails console like this: * `ENV["GITHUB_SECRET"]` * `ENV["GITHUB_KEY"]` 4. Change login link in home.html.erb to “/auth/github” 5. Create callback route: routes.rb, `get '/auth/:provider/callback', to: 'sessions#create'` 6. Create a sessions controller * add a #create action in the sessions controller ```rb 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 ``` 7. Create user model: nickname, email, provider, token, uid, image_url, token 8. 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 ``` 9. 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 ``` 10. Add destroy action in sessions controller 11. routes.rb: “delete '/logout', to: 'sessions#destroy'”