{"id":4686,"date":"2013-10-19T19:41:18","date_gmt":"2013-10-20T03:41:18","guid":{"rendered":"https:\/\/www.ultrasaurus.com\/?p=4686"},"modified":"2013-10-19T19:41:18","modified_gmt":"2013-10-20T03:41:18","slug":"rails-4-twitter-omniauth-with-mongodb","status":"publish","type":"post","link":"https:\/\/www.ultrasaurus.com\/2013\/10\/rails-4-twitter-omniauth-with-mongodb\/","title":{"rendered":"rails 4 twitter omniauth with mongodb"},"content":{"rendered":"
If you are brand new to MongoDB and Rails 4, take a quick look at my very basic rails 4 mongodb tutorial<\/a> before diving into this one.<\/p>\n Gems: mongoid<\/a>, omniauth<\/a>, figaro<\/a><\/p>\n Make sure you have Rails 4 (rails -v). We’ll make a Rails app skipping test-unit (-T), since I prefer RSpec, and omitting ActiveRecord (-O) since we’ll be using MongoDB.<\/p>\n Add the following to the Gemfile<\/p>\n Now some auto-code generation for quick setup:<\/p>\n I’ve decided to use figaro which allows me to easily configure my API keys without committing them to my source repo, which is very helpful when posting open source code. We need to set up the app for an API key in order to auth with Twitter. <\/p>\n Sign in using your regular Twitter account at: https:\/\/dev.twitter.com\/<\/a><\/p>\n Then in the upper-right, select “my applications” Click “Create a new application” and fill in the form. I called my app blue-parakeet for uniqueness — you’ll have to make up your own name. Read and Accept the Terms, then click “Create Your Twitter Application”<\/p>\n Now you have a “key” and “secret” (called “consumer key” and “consumer secret”) which you will need to configure your rails app.<\/p>\n Edit config\/application.yml<\/strong><\/p>\n Edit config\/initializers\/omniauth.rb<\/strong><\/p>\n Now Omniauth is already setup to auth with twitter. Let’s run the server. Install mongo with Then run Rails server:<\/p>\n Go to http:\/\/localhost:3000\/auth\/twitter<\/a> and you’ll be presented with twitter auth However, when we authenticate, we get an error, since we have’t configured our routes yet: Next step is a sessions controller and a route for the OAuth callback. We’ll make a placeholder create action that just reports the auth info we get back from Twitter.<\/p>\n On the command line:<\/p>\n Edit the newly created file, app\/controllers\/sessions_controller.rb<\/strong><\/p>\n add the following to config\/routes.rb<\/strong><\/p>\n Now go to http:\/\/localhost:3000\/auth\/twitter<\/a> — after authenticating with Twitter, you will see the user info that Twitter sends to the app from the authentication request (see docs for explanation of each field<\/a>). The general stuff which is more consistent across providers is in the ‘info’ section, and most of the interesting twitter-specific info is in the “extra” section: For this app, we’ll use a simple user model, just to show that there’s no magic here — we’re only using Twitter auth not storing our own passwords, so we don’t really need the full features of the lovely Devise gem.<\/p>\n Add to app\/models\/user.rb<\/strong><\/p>\n With Rails 4 the recommended pattern to lock down model attributes that we don’t want changed from form submits (or malicious attacks) is in the controller. In app\/controllers\/users_controller.rb<\/strong> change:<\/p>\n to:<\/p>\n and then remove the corresponding fields from app\/views\/users\/_form.html.erb<\/strong><\/p>\n Finally, the real create action for the sessions controller, plus a destroy action for the \/signout url we defined earlier:<\/p>\n With this app, we’ve got a basic understanding to Twitter OAuth using Rails 4 and the OmniAuth gem. We didn’t actually do anything specific to MongoDB and no testing yet. It is important to understand the technology we’re working with before testing or even writing production code.<\/p>\n Special thanks to Daniel Kehoe<\/a> of RailsApps. His Rails 3 OmniAuth Mongoid<\/a> tutorial provided a helpful foundation.<\/p>\n","protected":false},"excerpt":{"rendered":" If you are brand new to MongoDB and Rails 4, take a quick look at my very basic rails 4 mongodb tutorial before diving into this one. Gems: mongoid, omniauth, figaro Let’s get started Make sure you have Rails 4 (rails -v). We’ll make a Rails app skipping test-unit (-T), since I prefer RSpec, and… Continue reading Let’s get started<\/h2>\n
\nrails new parakeet -T -O\ncd parakeet\n<\/pre>\n
\ngem \"mongoid\", git: 'git:\/\/github.com\/mongoid\/mongoid.git'\ngem \"omniauth-twitter\"\ngem \"figaro\" # key configuration using ENV \n<\/pre>\n
\nrails g mongoid:config\n# create config\/mongoid.yml\n\nrails generate figaro:install\n# create config\/application.yml\n# append .gitignore\n<\/pre>\n
Get Developer Key from Twitter<\/h2>\n
\n<\/p>\n
\n
\nMake sure you put in a callback URL, even though you won’t use it for development (since omniauth tells twitter the callback URL to override this setting) — if you don’t supply one you will get a 401 unauthorized error.<\/p>\nUsing Figaro gem for Configuring API keys<\/h2>\n
\n# config via Figaro gem, see: https:\/\/github.com\/laserlemon\/figaro\n# rake figaro:heroku to push these to Heroku\nTWITTER_KEY: ABCLConsumerKeyCopiedFromTwitterDevPortal\nTWITTER_SECRET: XYZConsumerSecretCopiedFromTwitterDevPortal\n<\/pre>\n
Configuring Omniauth<\/h2>\n
\nRails.application.config.middleware.use OmniAuth::Builder do\n provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']\nend\n<\/pre>\n
brew install mongodb<\/code> if you haven’t already. Also, if you don’t have mongo set up to run automatically at startup, then run Mongo:<\/p>\n
\nmongod\n<\/pre>\n
\nrails s\n<\/pre>\n
\n<\/p>\n
\n<\/p>\n
Create a Sessions Controller, Add Routes<\/h2>\n
\nrails generate controller sessions\n<\/pre>\n
\nrequire 'json'\nclass SessionsController request.env[\"omniauth.auth\"]\n end\nend\n<\/pre>\n
\nget '\/auth\/:provider\/callback' => 'sessions#create'\nget '\/auth\/failure' => 'sessions#failure'\nget '\/signout' => 'sessions#destroy', :as => :signout\nroot :to => redirect(\"\/auth\/twitter\") # for convenience\n<\/pre>\n
\n<\/img><\/p>\n
User Registration<\/h2>\n
\nrails generate scaffold user provider:string uid:string name:string\n<\/pre>\n
\n def self.create_with_omniauth(auth)\n create! do |user|\n user.provider = auth['provider']\n user.uid = auth['uid']\n if auth['info']\n user.name = auth['info']['name'] || \"\"\n end\n end\n end\n<\/pre>\n
\n def user_params\n params.require(:user).permit(:provider, :uid, :name)\n end\n<\/pre>\n
\n def user_params\n params.require(:user).permit(:name)\n end\n<\/pre>\n
\n def create\n auth = request.env[\"omniauth.auth\"]\n user = User.where(:provider => auth['provider'],\n :uid => auth['uid']).first || User.create_with_omniauth(auth)\n session[:user_id] = user.id\n redirect_to user_path(user), :notice => \"Signed in!\"\n end\n\n def destroy\n reset_session\n redirect_to root_url\n end\n<\/pre>\n