Code Monkey home page Code Monkey logo

twitter-auth's Introduction

TwitterAuth

TwitterAuth aims to provide a complete authentication and API access solution for creating Twitter applications in Rails. It provides a generator and all of the necessary components to use Twitter as the sole authentication provider for an application using either Twitter's OAuth or HTTP Basic authentication strategies.

Installation

You can include TwitterAuth as a gem in your project like so:

config.gem 'twitter-auth', :lib => 'twitter_auth'

Or you can install it as a traditional Rails plugin:

script/plugin install git://github.com/mbleigh/twitter-auth.git

Note that because TwitterAuth utilizes Rails Engines functionality introduced in Rails 2.3, it will not work with earlier versions of Rails.

NOTE: TwitterAuth requires Rails version 2.3 or later because it makes extensive use of the new support for Rails Engines. Previous versions of Rails are not supported.

Usage

To utilize TwitterAuth in your application you will need to run the generator:

script/generate twitter_auth [--oauth (default) | --basic]

This will generate a migration as well as set up the stubs needed to use the Rails Engines controllers and models set up by TwitterAuth. It will also create a User class that inherits from TwitterUser, abstracting away all of the Twitter authentication functionality and leaving you a blank slate to work with for your application.

Finally, it will create a configuration file in config/twitter_auth.yml in which you should input your OAuth consumer key and secret (if using the OAuth strategy) as well as a custom callback for development (the oauth_callback option is where Twitter will send the browser after authentication is complete. If you leave it blank Twitter will send it to the URL set up when you registered your application).

Sign in with Twitter

Twitter recently implemented a convenience layer on top of OAuth called Sign in with Twitter. TwitterAuth makes use of this by default in newly generated applications by setting the authorize_path in twitter_auth.yml.

If you already have an application utilizing TwitterAuth that you would like to utilize the new system, simply add this line to your twitter_auth.yml in each environment:

authorize_path: "/oauth/authenticate"

Usage Basics

If you need more information about how to use OAuth with Twitter, please visit Twitter's OAuth FAQ.

TwitterAuth borrows heavily from Restful Authentication for its API because it's simple and well-known. Here are some of the familiar methods that are available:

  • login_required: a before filter that can be added to a controller to require that a user logs in before he/she can view the page.
  • current_user: returns the logged in user if one exists, otherwise returns nil.
  • logged_in?: true if logged in, false otherwise.
  • redirect_back_or_default(url): redirects to the location where store_location was last called or the specified default URL.
  • store_location: store the current URL for returning to when a redirect_back_or_default is called.
  • authorized?: override this to add fine-grained access control for when login_required is already called.

Accessing the Twitter API

Obviously if you're using Twitter as an authentication strategy you probably have interest in accessing Twitter API information as well. Because I wasn't really satisfied with either of the popular Twitter API Ruby libraries (Twitter4R and Twitter) and also because neither support OAuth (yet), I decided to go with a simple, dependency-free API implementation.

The User class will have a twitter method that provides a generic dispatcher with HTTP verb commands available (get, put, post, and delete). These are automatically initialized to the base_url you specified in the twitter_auth.yml file, so you need only specify a path. Additionally, it will automatically append a .json extension and parse the JSON if you don't provide (it returns strings for XML because, well, I don't like XML and don't feel like parsing it).

# This code will work with the OAuth and Basic strategies alike.
user = User.find_by_login('mbleigh')

user.twitter.get('/account/verify_credentials')
# => {'screen_name' => 'mbleigh', 'name' => 'Michael Bleigh' ... }

user.twitter.post('/statuses/update.json', 'status' => 'This is my status.')
# => {"user"=>{"login" => "mbleigh" ... }, "text"=>"This is my status.", "id"=>1234567890 ... }

If Twitter returns something other than a 200 response code, TwitterAuth will catch it and try to raise a salient error message. The exception class is TwitterAuth::Dispatcher::Error if you're in the mood to catch it.

This area of the code is still a little raw, but hopefully will evolve to be a little more user-friendly as TwitterAuth matures. In the meantime, it's a perfectly workable foundation library, and the fact that it works the same with OAuth and HTTP Basic makes it all the better!

Customizing TwitterAuth

There are a number of hooks to extend the functionality of TwitterAuth. Here is a brief description of each of them.

Controller Methods

TwitterAuth provides some default controller methods that may be overridden in your ApplicationController to behave differently.

  • authentication_failed(message): called when Twitter authorization has failed during the process. By default, simply redirects to the site root and sets the flash[:error].
  • authentication_succeeded(message=default): called when Twitter authorization has completed successfully. By default, simply redirects to the site root and sets the flash[:notice].
  • access_denied: what happens when the login_required before filter fails. By default it stores the current location to return to and redirects to the login process.

Tips and Tricks

Resources

Copyright

TwitterAuth is Copyright (c) 2009 Michael Bleigh and Intridea, Inc., released under the MIT License.

TwitterAuth is not affiliated with Twitter, Inc.

twitter-auth's People

Contributors

chancancode avatar tomk32 avatar zapnap avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

twitter-auth's Issues

undefined method `downcase'

Hello.

When I try to call
current_user.twitter.get 'friendships/destroy', {:id => user_id}
or this way
current_user.twitter.get "friendships/destroy?id=#{user_id}"

I catch 'undefined method downcase' for :id:Symbol' or 'undefined methoddowncase' for nil:NilClass'

Catch the exception while twitter service is under maintaince.

Sometimes twitter is under maintaince and as a result the app can't request the oauth token. We need to do something instead of directly raising the exception to the top, such as catch the exception in the SessionsController#new,

rescue Exception => e
authentication_failed("We're currently experiencing issues with Twitter's OAuth Service. Please try later.") and return

OauthUser.identify_or_create_from_access_token won't work for strings

Despite the error message from the first line of OauthUser.identify_or_create_from_access_token (oauth_user.rb line 14) said "Must authenticate with an OAuth::AccessToken or the string access token and secret." - it actually won't work for Strings. The next line will cause a NoMethodError / String#get.

My use case for using string tokens and secrets:
My app has an "app user" and I need to parse the timeline of this app user. I saved the app user's token and secret in twitter_auth.yml and I need to be able to create an OauthUser based on these credentials.

Abnormal file size of debug.log in 'spec' folder

Hi there, I'm a window git user. I have just installed your twitter-auth gem, I'm so glad that I found a really nice one.
Two things that frustrated me at first, let me tell you what:
first, the gem costed me more than a half hour to complete, I found out that the file size of 'C:\ruby\lib\ruby\gems\1.8\gems\twitter-auth-0.1.17\spec\debug.log' is over 208M. It must be a slip of mind, please clean up the file ASAP.
second, 'script/plugin install git://github.com/mbleigh/twitter-auth.git' can do nothing at present, is it the same reason related to the first one?

use twitter_id as id in users table

is it possible to change the migration to look like this:
create_table :users. :id => false do |t|
t.integer :id, :limit => 8 # force column to bigint in mysql
...
end
add_index :users, :id, :unique => true

if this is possible, then we can have the id in the users table match the id we get from twitter.
we'd have to change the GenericUser model a bit to handle this, but i think it should work.

Refactor to Mixin

Make the TwitterAuth functionality a mixin instead of a superclass, so that TwitterAuth can be more configurable and added in a less strict manner.

Example:

```
class User < ActiveRecord::Base
twitter_authenticated :via => :oauth
end
```

how to not set the remember_for field?

Twitter does not itself set an expiration date/time for the access_token.
However, twitter-auth seems to set it at 10 days default.

describe '.from_remember_token' do
before do
@user = Factory(:twitter_oauth_user, :remember_token => 'abcdef', :remember_token_expires_at => (Time.now + 10.days))
end

If my app requires users to store their access_token and get there statuses regularly, how do I do that?

Support Multiple Services

Support Twitter-Compatible APIs alongside Twitter in the same application (Laconi.ca, Present.ly).

Cannot log out

How do you log out of Twitter Auth? Once you are authorized it automatically seems to remember the user via the cookie. How do you remove this and/or log out?

Arguments for get() and post() are not being passed through to Twitter's API

Assuming twitter_user is an instance of User and authenticated via OAuth,

opts = {}
opts['count'] = '200'
opts['since_id'] = twitter_user.since_id unless twitter_user.since_id.blank?
tweets = twitter_user.twitter.get('/statuses/friends_timeline', opts)

opts are not passed through, and tweets contains the last 20 tweets for this method, without regard for since_id

Looking through the dispatcher code, it would seem that this should be working, but I can't seem to reproduce.

Utilize TwitterDispatch

Pull the dispatcher functionality into a submodule’d version of mbleigh/twitterdispatch so that the actual accessing of Twitter is separated.

Integrate Grackle

I've decided that Grackle is close enough to my lightweight and "not too much magic" approach to API access that it should be the default way people access Twitter through TwitterAuth. I will be bringing in Grackle as a dependency and utilizing it instead of the current dispatcher. I will also, however, be wrapping it up so that everything still works the same and providing the same HTTP verb methods as currently. You'll just also be able to do something like this:

user.twitter.statuses.replies?(:since_id => 123)

Is this gem still being maintained?

Hi,
Excuse my ignorance. I notice things havent been updated lately...
Is this gem still being maintained?

Moreover, is this gem compatible with rails 3?

Import Twitter IDs as well

It would be nice if the twitter user id was stored in the users table. I realize that the current implementation using the TWITTER_ATTRIBUTES array won’t work because twitter returns ‘id’ back and that would collide with the id column already in the users table. Perhaps this could be caught and written to a twitter_user_id field?

I would assume that because the twitter user id isn’t stored in the users table, if a user comes to your site and generates data, then goes to twitter and changes their twitter username (which twitter allows them to do) then comes back to your site, all of their data is no longer associated with their account (because the only thing you have to go by is the username rather than the underlying id).

Can't call User#twitter from User class

I'm having a strange problem. If I call current_user.twitter.get('statuses/friends_timeline') from a controller, it works as expected. However, if I do this:

controller

current_user.timeline

User

def timeline
  twitter.get('statuses/friends_timeline')
end

...I get a NoMethodError: can't call downcase on NilClass. After a bit of debugging, it seems that when the OAuth module generates a signature, for some reason, it's not setting the hostname properly (so it's still nil, so it doesn't respond to downcase), with the result that request-uri is something like http::80/statuses/friends_timeline.

But it's baffling to me that it works in one case and not in the other, because I don't see any functional difference in how the methods are being called in the two cases. This is particularly frustrating since I'm trying to put logic in the model, not the controller, and TwitterAuth is preventing me from doing so.

Please help.

Support Sign-In with Twitter on OAuth 1.0a

Some changes were made to the twitter oauth api very recently to support OAuth 1.0a see http://groups.google.com/group/twitter-development-talk/browse_thread/thread/472500cfe9e7cdb9

The symptom is that instead of being sent back to my oauth_callback url from twitter I am shown a PIN number.

The easiest way to resolve this is to edit the session_controller.

  1. Make sure you have oauth 0.3.5
  2. Add the oauth_callback url to the consumer.get_request_token call in session_controller.new
    @request_token = TwitterAuth.consumer.get_request_token(:oauth_callback => TwitterAuth.oauth_callback)
  3. Add the oauth_verifier to get_access_token method in session_controller.oauth_callback
    @access_token = @request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])

Obviously there are a few other changes needed for elegance but these are the minimum needed.

need separate table to store users in db

So I think twitter-auth is great. However I have run into one issue trying to cache twitter data in the database. I find that I have to have a separate twitter_user table to store user information about friends and followers. If I try and drop it into the users table created by twitter-auth I get validation errors like 'login required'. This means my current db caching of twitter data is a little un-DRY. I wonder if it might be valuable to extract the twitter user data available over the wire to a separate table, and then have the data needed for oauth in a separate table?

Issues w/ Login on Localhost

I've got everything up and running smoothly on my live server but I can't seem to get login to work in development mode on localhost. I get the following error when visiting /login

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Is there something special I'm supposed to do to get this to work in development mode?

how to config twitterauth.yml to work in a real server

Hi, twitter-auth works only on localhost? i have an app with this gem in local host works fine, but when in try it in a server the connection with twitter it's not working , i think i'm doing something wrong on my twitterauth.yml.. help please!!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.