• Stars
    star
    358
  • Rank 118,855 (Top 3 %)
  • Language
    Ruby
  • Created almost 16 years ago
  • Updated about 15 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Standard authentication stack for Rails using Twitter to log in.

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.

More Repositories

1

acts-as-taggable-on

A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.
Ruby
4,972
star
2

seed-fu

Advanced seed data handling for Rails, combining the best practices of several methods together.
Ruby
1,221
star
3

subdomain-fu

A new plugin approach to attempting to solve the usage of subdomains in linking and routing in Rails projects.
Ruby
590
star
4

princely

A simple Rails wrapper for the PrinceXML PDF generation library.
Ruby
233
star
5

uberkit

The UberKit is a Rails plugin with a set of UI tools to ease common development.
Ruby
103
star
6

omniauth-jwt

An OmniAuth strategy that uses JSON Web Token for Single Sign-On
Ruby
99
star
7

mbleigh.github.com

My blog and website.
Ruby
72
star
8

mash

Mash is a Hash with the ability to read, write, and test for the presence of arbitrary attributes using method calls.
Ruby
61
star
9

ruby-github

A Ruby library for getting information from the GitHub API.
Ruby
58
star
10

canonical-url

Rails plugin to take advantage of the new Canonical URL support of search engines.
Ruby
50
star
11

pwas-on-firebase

Demos and related material for Google I/O Progressive Web Apps on Firebase talk.
HTML
50
star
12

colorist

A Ruby library built to handle the easy conversion and manipulation of colors with a special emphasis on W3C standards and CSS-style hex color notation.
Ruby
48
star
13

acts-as-readable

A simple plugin that allows a user to mark anything as 'read.' Common usage would include forum posts, news items, etc.
Ruby
44
star
14

escapable-amp

TypeScript
30
star
15

conf_ask

A simple demonstration app built to show off Grape
JavaScript
26
star
16

fetches

A Rails plugin to simplify the fetching and memoization of records for parameter-based finds.
Ruby
25
star
17

persistence-smoothie

The source code (and slides in the Downloads section) for my talk "Persistence Smoothie: Blending SQL and NoSQL"
Ruby
21
star
18

marky

A Markdown rendering wrapper for the EtherPad collaborative editor.
JavaScript
17
star
19

twisteners

Who's listening to you? Find out with this Twitter app coded live at RailsConf 2009.
JavaScript
17
star
20

relates-to

Rails Plugin to provide simple polymorphic relationships between models.
Ruby
16
star
21

github-unfuddle

A web hook that takes GitHub commits and turns them into Unfuddle changesets posting using the Unfuddle API.
Ruby
15
star
22

from_param

Rails plugin that adds a from_param class method to ActiveRecord::Base for simple URL-based fetching.
Ruby
14
star
23

web-components-in-action

Examples and exercises for Web Components in Action workshop from Fluent 2014
CSS
13
star
24

cors-talk-example

Ruby
12
star
25

needy-controllers

Include stylesheets and scripts in a before_filter-esque fashion, and set up simple memoized methods for record fetches.
Ruby
12
star
26

browserized-styles

Automatic inclusion of browser and OS-specific stylesheets with a simple naming convention.
Ruby
11
star
27

bootstrap-polymer

An implementation of Bootstrap 3 components in Polymer.
JavaScript
10
star
28

polishing-rubies

Polishing Rubies: A Guide to Ruby Open Source Development
9
star
29

omniauth-box

Box.net strategy for OmniAuth
Ruby
9
star
30

railsconf-tweetups

Twitter app to see who's going to what at RailsConf!
Ruby
9
star
31

twitterdispatch

A simple Twitter API wrapper that gets out of your way.
6
star
32

commitbit

A web-based tool to help abandoned GitHub repos transfer to new maintainers.
CSS
6
star
33

present-future-of-oauth

Slides and code for "The Present Future of OAuth" given at RailsConf 2010.
Ruby
5
star
34

pictle

Drawing with Wordles
TypeScript
5
star
35

hooktastic

Merb-based application to make webhooks super-easy.
Ruby
5
star
36

jquery-pageselect

A jQuery plugin to handle selection of text on the page (not in a textarea).
4
star
37

jquery.navigable

A jQuery plugin for simple keyboard navigation.
JavaScript
4
star
38

css3-for-sass

A set of mixins to apply CSS3 rules to SASS.
4
star
39

cors-talk

JavaScript
4
star
40

bleightiful

The WordPress theme I hastily crafted for my personal site.
PHP
3
star
41

wedding-website

My wedding website!
JavaScript
2
star
42

rails-is-the-new-rails

Slides for a talk given at Ruby Midwest 2011
JavaScript
2
star
43

open-source-marketing

JavaScript
2
star
44

partay

Source for Partay games (for now, just Phraseology).
TypeScript
2
star
45

nodelin

Noodlin' around with Node.js to prep for the KO
JavaScript
2
star
46

callable-run-demo

HTML
2
star
47

schemer

Create JSON Schemas from Go data structures
Go
2
star
48

tinypage

A simple demo of the Firebase Hosting REST API.
JavaScript
2
star
49

omniauth-from-the-ground-up

OmniAuth: From the Ground Up Talk Content
Ruby
2
star
50

codemirror-element

A drop-in web component for source code editing. Utilizes the CodeMirror library.
HTML
2
star
51

dotfiles

Vim Script
1
star
52

puppetry

Ruby
1
star
53

i-am-open-source

I Am Open Source And So Can You (Talk)
1
star
54

let-us-lunch

Ruby
1
star
55

fiberthecrossroads.org

JavaScript
1
star