Post tweet using omniauth-twitter and twitter Rails 3

Let’s get started

Before you must do install ‘devise’, First start adding this gem to your Gemfile:

  gem 'omniauth-twitter'
  gem 'twitter'

tell OmniAuth about this provider. For a Rails app :

config/initializers/devise.rb

Devise.setup do |config|
  require "omniauth-twitter"
  config.omniauth :twitter, "CONSUMER_KEY", "CONSUMER_SECRET"

  require 'devise/orm/active_record'
end

Replace CONSUMER_KEY and CONSUMER_SECRET with the appropriate values you obtained from
dev.twitter.com earlier and setting your apps in twitter like this

dev_twitter

Create new controller in your Rails apps

apps/controller/users/omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def twitter
    @user = User.find_for_twitter_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: "Twitter"
      sign_in_and_redirect @user, event: :authentication
    else
      session["devise.twitter_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end  
end

config/routes.rb

 devise_for :users, :controllers => { omniauth_callbacks: "users/omniauth_callbacks" }

And your model user.rb

class User < ActiveRecord::Base  
  CONSUMER_KEY = 'WHAT_IS_YOUR_CONSUMER_KEY'
  CONSUMER_SECRET = 'WHAT_IS_YOUR_CONSUMER_SECRET'
  OPTIONS = {site: "http://api.twitter.com", request_endpoint: "http://api.twitter.com"}
  
  devise:omniauthable

  def self.find_for_twitter_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    if user = User.where(username: data.screen_name).first
      user
    else # Create a user with a stub password.
      User.create!(full_name: data.name, username: data.screen_name, provider: access_token.provider,
        token: access_token.credentials.token, token_secret: access_token.credentials.secret,
        password: Devise.friendly_token[0,20])
    end
  end

  def post_tweets(message)
    Twitter.configure do |config|
      config.consumer_key = User::CONSUMER_KEY
      config.consumer_secret = User::CONSUMER_SECRET
      config.oauth_token = self.authentication_token
      config.oauth_token_secret = self.authentication_token_secret
    end
    client = Twitter::Client.new
    begin
      client.update(message)
      return true
    rescue Exception => e
      self.errors.add(:oauth_token, "Unable to send to twitter: #{e.to_s}")
      return false
    end
  end
end

Let’s try….

class HomeController < ApplicationController
  def index
    current_user.post("post by gem 'twitter'")
  end
end

how to parsing HTML with Nokogiri

Installation

Installation is very easy. Just add to your Gemfile.

gem "nokogiri"

Learn how to Generate HTML.

Quick start to parsing HTML

Parsing HTML is easy, and you can take advantage of CSS selectors or XPath queries to find things in your document:

require 'open-uri'
require 'nokogiri'

# Perform a google search
doc = Nokogiri::HTML(open('http://google.com/search?q=tenderlove'))

# Print out each link using a CSS selector
doc.css('h3.r > a.l').each do |link|
  puts link.content
end

Here is an example parsing some HTML and searching it using a combination of CSS selectors and XPath selectors:

require 'nokogiri'

doc = Nokogiri::HTML.parse(<<-eohtml)
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <h1>This is an awesome document</h1>
    <p>
      I am a paragraph
        <a href="http://google.ca">I am a link</a>
    </p>
  </body>
</html>
eohtml

####
# Search for nodes by css
doc.css('p > a').each do |a_tag|
  puts a_tag.content
end

####
# Search for nodes by xpath
doc.xpath('//p/a').each do |a_tag|
  puts a_tag.content
end

####
# Or mix and match.
doc.search('//p/a', 'p > a').each do |a_tag|
  puts a_tag.content
end

###
# Find attributes and their values
doc.search('a').first['href']

Set Up SSH Keys

We use SSH keys to establish a secure connection between your computer and GitHub. Setting them up is fairly easy, but does involve a number of steps.

To make sure you generate a brand new key, you need to check if one already exists. First, you need to open an app called Terminal.
1. First, check for existing ssh keys on your computer:

cd ~/.ssh

2. Backup and remove existing SSH keys. Since there is already an SSH directory you’ll want to back the old one up and remove it:

$ ls
$ mkdir key_backup
$ cp id_rsa* key_backup
$ rm id_rsa*

3. Generate a new SSH key. To generate a new SSH key, enter the code below. We want the default settings so when asked to enter a file in which to save the key, just press enter.

$ ssh-keygen -t rsa -C "your_email@youremail.com"

Now you need to enter a passphrase.

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Nokogiri Rails 3

Nokogiri is a simple HTML / XML parser with much of its interface borrowed from Hpricot. It uses libxml2 to parse and search, so it is very fast.

Installation

Installation is very easy. Just use the following command and add to your Gemfile

gem "nokogiri"

Quick start to parsing HTML

Parsing HTML is easy, and you can take advantage of CSS selectors or XPath queries to find things in your document:

require 'open-uri'
require 'nokogiri'

# Perform a google search
doc = Nokogiri::HTML(open('http://google.com/search?q=tenderlove'))

# Print out each link using a CSS selector
doc.css('h3.r > a.l').each do |link|
  puts link.content
end

Here is an example parsing some HTML and searching it using a combination of CSS selectors and XPath selectors:

require 'nokogiri'

doc = Nokogiri::HTML.parse(<<-eohtml)
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <h1>This is an awesome document</h1>
    <p>
      I am a paragraph
        <a href="http://google.ca">I am a link</a>
    </p>
  </body>
</html>
eohtml

####
# Search for nodes by css
doc.css('p > a').each do |a_tag|
  puts a_tag.content
end

####
# Search for nodes by xpath
doc.xpath('//p/a').each do |a_tag|
  puts a_tag.content
end

####
# Or mix and match.
doc.search('//p/a', 'p > a').each do |a_tag|
  puts a_tag.content
end

###
# Find attributes and their values
doc.search('a').first['href']

Generate

require 'rubygems'
require 'nokogiri'

@builder = Nokogiri::HTML::Builder.new do |doc|
  doc.html {
    doc.head {
      doc.script {
        doc.text "alert('hello world');"
      }
      doc.style {
        doc.text "div#thing { background: red; }"
      }
      doc.title "Awesome Page" 
    }
    doc.body {
      doc.div.rad.thing! {
        doc.h1 "This is an h1"
        doc.text "This is a div with class 'rad' and id 'thing'"

        doc.div( :some_attribute => 'foo' ) {
          doc.p "This is an awesome paragraph!"
        }
      }
    }
  }
end

puts @builder.to_html

Is there an easy way to create html partials e.g. menu instead of a full HTML document?
The only workaround I’ve found is to use inner_html:

require 'rubygems'
require 'nokogiri'

@builder = Nokogiri::HTML::Builder.new do |doc|
  doc.ul {
    doc.li 'hello'
  }
end

puts @builder.doc.inner_html 
# <ul><li>hello</li></ul>

Facebook Apps Using Koala

Installation

add this in your Gemfile

gem "koala"

Configuration file

If you’re using the OAuth class (or even the RealtimeUpdates class) it gets a little redundant always passing in your Facebook application ID and secret to create new instances of the OAuth class. To fix that, we’ll create a configuration file with your Facebook application ID and secret and extend Koala to always use those given values.

First we’ll put a YAML file into the config directory:

# config/facebook.yml
development:
  app_id: YOUR APP ID
  secret_key: YOUR SECRET
test:
  ...
production:
  ...

Now you can add a ruby file to read the configuration file and extend Koala when Rails is initialized in the config/initializers directory:

# config/initializers/koala.rb
# Monkey-patch in Facebook config so Koala knows to 
# automatically use Facebook settings from here if none are given

module Facebook
  CONFIG = YAML.load_file(Rails.root.join("config/facebook.yml"))[Rails.env]
  APP_ID = CONFIG['app_id']
  SECRET = CONFIG['secret_key']
end

Koala::Facebook::OAuth.class_eval do
  def initialize_with_default_settings(*args)
    case args.size
      when 0, 1
        raise "application id and/or secret are not specified in the config" unless Facebook::APP_ID && Facebook::SECRET
        initialize_without_default_settings(Facebook::APP_ID.to_s, Facebook::SECRET.to_s, args.first)
      when 2, 3
        initialize_without_default_settings(*args) 
    end
  end 

  alias_method_chain :initialize, :default_settings 
end

This overrides OAuth#initialize to take any number of arguments. If OAuth.new gets zero or one parameter, we’ll use our configuration file’s values, otherwise we’ll initialize the OAuth object using the old initializer.

Now creating an OAuth instance is as easy as

Koala::Facebook::OAuth.new
OR
Koala::Facebook::OAuth.new(oauth_callback_url)

Authentication
Facebook Connect website
Javascript-based Authentication

Koala’s OAuth class allows easy verification and parsing of the cookies Facebook passes to your application, whether it be a website or Facebook iframe application. As a side note, make sure you’re using the new Facebook JavaScript SDK since the cookie format differs from the older Facebook Connect scripts.

One way to get the cookie data is to setup a before_filter and assign a local variable to store the information:

# app/controller/foo_controller.rb
before_filter :parse_facebook_cookies

def parse_facebook_cookies
  @facebook_cookies ||= Koala::Facebook::OAuth.new(YOUR_APP_ID, YOUR_SECRET).get_user_info_from_cookie(cookies)

  # If you've setup a configuration file as shown above then you can just do
  # @facebook_cookies ||= Koala::Facebook::OAuth.new.get_user_info_from_cookie(cookies)
end

def index
  ...
  @access_token = @facebook_cookies["access_token"]
  @graph = Koala::Facebook::GraphAPI.new(@access_token)
  ...
end

Of course you can add a callback_url when creating the OAuth object, depending on how you’re handling authentication.

If you won’t necessarily need the data from the Facebook cookies on every request, a method in ApplicationController is probably good enough:

# app/controllers/application_controller.rb
def facebook_cookies
    @facebook_cookies ||= Koala::Facebook::OAuth.new(YOUR_APP_ID, YOUR_SECRET).get_user_info_from_cookie(cookies)
end

# app/controllers/foo_controller.rb
def index
  ...
  @access_token = facebook_cookies['access_token']
  @graph = Koala::Facebook::GraphAPI.new(@access_token)
  ...
end

Authentication via redirects

Note: I’ve never actually implemented Facebook authorization using redirects, but this is what I’ve gathered from the Facebook documentaiton. Let us know if this example actually doesn’t work! – Chris

OAuth supports an authentication flow based on redirects, which is outlined on the official Facebook developers site

To authorize a Facebook user present them with a link to the Facebook authentication page. With Koala this might look like:

<%# app/views/welcome.html.erb %>
...
  <%= link_to 'Login', Koala::Facebook::OAuth.new.url_for_oauth_code(:callback => oauth_redirect_url) %>
...

Where oauth_redirect_url is the URL to an action which will handle the rest of the authentication flow.

Assuming oauth_redirect_url points to the OAuthController#redirect action, you can finish off authentication with the following bit of code:

# app/controllers/oauth_controller
def redirect
  session[:access_token] = Koala::Facebook::OAuth.new(oauth_redirect_url).get_access_token(params[:code]) if params[:code]

  redirect_to session[:access_token] ? success_path : failure_path
end

This will store the access_token string in session[:access_token]. Obviously, you can store this value whatever way seems fit given your application/
IFrame Applications on Facebook.com

Using Koala with an iframe application is very similar to using it with an external Facebook Connect application. You can use the Javascript-based authentication methods to authenticate the user and start using the Graph or REST API; Facebook also provides parameters on tab load, which you could associate with the user as well.

Storing Facebook User IDs

As you may or may not be aware, Facebook UIDs are so large that they should be stored in most databases as big ints rather than plain ints. Therefore, if you wish to store a Facebook UID in your database, your migration should be of the form:

add_column :users, :facebook_id, :bigint

Graph API

The Graph API is the simple, slick new interface to Facebook’s data. Using it with Koala is quite straightforward:

@graph = Koala::Facebook::API.new(oauth_access_token)
# in 1.1 or earlier, use GraphAPI instead of API

profile = @graph.get_object("me")
friends = @graph.get_connections("me", "friends")
@graph.put_object("me", "feed", :message => "I am writing on my wall!")

# three-part queries are easy too!
@graph.get_connection("me", "mutualfriends/#{friend_id}")

# you can even use the new Timeline API
# see https://developers.facebook.com/docs/beta/opengraph/tutorial/
@graph.put_connections("me", "namespace:action", :object => object_url)

PHP SDK & Graph API base Facebook Connect Tutorial

First download the php sdk libary from here . Now copy the facebook.php from /src/ to your project dir.
Create a file named fbmain.php. And copy below code to this file.

<?php
    $fbconfig['appid' ]  = "your application id";
    $fbconfig['api'   ]  = "your application api key";
    $fbconfig['secret']  = "your application secret key";

    try{
        include_once "facebook.php";
    }
    catch(Exception $o){
        echo '<pre>';
        print_r($o);
        echo '</pre>';
    }
    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
    ));

    // We may or may not have this data based on a $_GET or $_COOKIE based session.
    // If we get a session here, it means we found a correctly signed session using
    // the Application Secret only Facebook and the Application know. We dont know
    // if it is still valid until we make an API call using the session. A session
    // can become invalid if it has already expired (should not be getting the
    // session back in this case) or if the user logged out of Facebook.
    $session = $facebook->getSession();

    $fbme = null;
    // Session based graph API call.
    if ($session) {
      try {
        $uid = $facebook->getUser();
        $fbme = $facebook->api('/me');
      } catch (FacebookApiException $e) {
          d($e);
      }
    }

    function d($d){
        echo '<pre>';
        print_r($d);
        echo '</pre>';
    }
?>

First update $fbconfig array by your application’s id, api key and secret key. In the code you’ll see I included facebook.php by include_once. If your server has no curl extension and json extension, you’ll see error message. Until you don’t install curl and json extension this sdk will not work.

$session = $facebook->getSession();

This method returns session information of user. It may be empty if user yet not logged in your site or user’s session is invalid. To check user’s session validity you’ve to first call an api, if user’s session is valid then the api will return result.

So if $fbme is not null that means user successfully logged in via facebook and user’s session is valid. So before calling any api use conditional logic like if ($fbme) { then call api}.

I also defined a method named d() to dump data quickly.
Now create another file named index.php and copy below code and checkout my description at the end.

<?php
    include_once "fbmain.php";
    $config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/php/index.php";

    //if user is logged in and session is valid.
    if ($fbme){
        //Retriving movies those are user like using graph api
        try{
            $movies = $facebook->api('/me/movies');
        }
        catch(Exception $o){
            d($o);
        }

        //Calling users.getinfo legacy api call example
        try{
            $param  =   array(
                'method'  => 'users.getinfo',
                'uids'    => $fbme['id'],
                'fields'  => 'name,current_location,profile_url',
                'callback'=> ''
            );
            $userInfo   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }

        //update user's status using graph api
        if (isset($_POST['tt'])){
            try {
                $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $_POST['tt'], 'cb' => ''));
            } catch (FacebookApiException $e) {
                d($e);
            }
        }

        //fql query example using legacy method call and passing parameter
        try{
            //get user id
            $uid    = $facebook->getUser();
            //or you can use $uid = $fbme['id'];

            $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $uid;
            $param  =   array(
                'method'    => 'fql.query',
                'query'     => $fql,
                'callback'  => ''
            );
            $fqlResult   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }
    }
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</title>
    </head>
<body>
    <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '<?=$fbconfig['appid' ]?>', status: true, cookie: true, xfbml: true});

                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());

            function login(){
                document.location.href = "<?=$config['baseurl']?>";
            }
            function logout(){
                document.location.href = "<?=$config['baseurl']?>";
            }
</script>
<style type="text/css">
    .box{
        margin: 5px;
        border: 1px solid #60729b;
        padding: 5px;
        width: 500px;
        height: 200px;
        overflow:auto;
        background-color: #e6ebf8;
    }
</style>

    <h3>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</h3>
    <?php if (!$fbme) { ?>
        You've to login using FB Login Button to see api calling result.
    <?php } ?>
    <p>
        <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
    </p>

    <!-- all time check if user session is valid or not -->
    <?php if ($fbme){ ?>
    <table border="0" cellspacing="3" cellpadding="3">
        <tr>
            <td>
                <!-- Data retrived from user profile are shown here -->
                <div class="box">
                    <b>User Information using Graph API</b>
                    <?php d($fbme); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>User likes these movies | using graph api</b>
                     <?php d($movies); ?>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="box">
                    <b>User Information by Calling Legacy API method "users.getinfo"</b>
                    <?php d($userInfo); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>FQL Query Example by calling Legacy API method "fql.query"</b>
                    <?php d($fqlResult); ?>
                </div>
            </td>
        </tr>
    </table>
    <div class="box">
        <form name="" action="<?=$config['baseurl']?>" method="post">
            <label for="tt">Status update using Graph API</label>
            <br />
            <textarea id="tt" name="tt" cols="50" rows="5">Write your status here and click 'submit'</textarea>
            <br />
            <input type="submit" value="Update My Status" />
        </form>
        <?php if (isset($statusUpdate)) { ?>
            <br />
            <b style="color: red">Status Updated Successfully! Status id is <?=$statusUpdate['id']?></b>
         <?php } ?>
    </div>
    <?php } ?>

    </body>
</html>

The code is very easy to understand. First part contains php logic, api call and collection of data. Next part is html/javascript to view data (javascript for fbconnect authentication).

Please change

$config[‘baseurl’] = “http://thinkdiff.net/demo/newfbconnect1/php/index.php&#8221;;

And set baseurl to your project url. And never forget to set your facebook application Connect URL. It would be your project url.

In index.php I used javascript based fbconnect authentication and fbml tag to show login button and logout button. If you don’t want to use javascript for this purpose, you can generate login/logout links using php code.

Generate login/logout button using this php code

<?php if ($fbme) { ?>
    <a href="<?=$logoutUrl?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
    </a>
    <?php else: ?>
    <a href="<?=$loginUrl?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
    </a>
    <?php } ?>

So user will see php generated login and logout button.

In the facebook.php sdk the getLoginUrl() function is defined as

/ * The parameters:
   * - next: the url to go to after a successful login
   * - cancel_url: the url to go to after the user cancels
   * - req_perms: comma separated list of requested extended perms
   * - display: can be "page" (default, full page) or "popup"
   *
   * @param Array $params provide custom parameters */
public function getLoginUrl($params=array()){....}

So if you want that your user approve additional permissions at the first time then generate the url by providing some parameters

$loginUrl = $facebook->getLoginUrl(
     array('req_perms' => 'email,read_stream')
);

1. How to check valid session of user, if user successfully logged in

I already discussed it in the STEP 1. So I think you already have learned how to check valid session of user. Just remember to use if ($fbme) {call api}

2. How to call graph api

Its very simple. For http://graph.facebook.com/me  you’ve to use

$fbme = $facebook->api('/me');

3. How to call legacy api

This is almost same as of graph api calling.

$param  =   array(
   'method'  => 'users.getinfo',
   'uids'       => $fbme['id'],
   'fields'     => 'name,current_location,profile_url',
   'callback'  => ''
);
$userInfo   =   $facebook->api($param);

So $facebook->api() is used to call both graph api and old legacy api. If you check the api() method in facebook.php sdk you’ll see

public function api() {
   $args = func_get_args();
   if (is_array($args[0])) {
     return $this->_restserver($args[0]);
   } else {
     return call_user_func_array(array($this, '_graph'), $args);
   }
 }

That means if 1st argument is array then the api will call the old restserver.php otherwise it will call the new graph server.

4. How to update status dynamically using graph api

try {
      $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> 'sample status message', 'cb' => ''));
} catch (FacebookApiException $e) {
      d($e);
}

in facebook.php you’ll see

function _graph($path, $method='GET', $params=array()) {...}

So the first parameter is for graph path in here https://graph.facebook.com/me/feed, 2nd parameter defines HTTP post or get parameter and 3rd parameter defines array that contains necessary values. So ‘message’ is the message we want as status and ‘cb’ is the callback function which I set to null. Here http://developers.facebook.com/docs/api you’ll see all the information about graph api and their parameters, like
Method Description Arguments
/PROFILE_ID/feed write to the given profile’s feed/wall message, picture, link, name,description

So to call any graph api just check the manual if you need to pass additional parameters or not.

Another example to retrieve user favorite movie names (https://graph.facebook.com/me/movies) use

$movies = $facebook->api('/me/movies');
$fql    =   "select name, hometown_location, sex, pic_square from user where uid=xxxxxxxxxxxxxxx";
$param  =   array(
       'method'     => 'fql.query',
        'query'     => $fql,
      'callback'    => ''
);
$fqlResult   =   $facebook->api($param);

Simple authentication with Warden

There are a lot of Ruby authentication libraries out there, which can do about everything like sending confirmation emails and resetting passwords. I didn’t really want that. My plan was to write a little application that could authenticate using Github credentials (more on Github authentication in “Authenticating via Github with Guestlist”).

This meant I didn’t need email confirmations, password reset functionality or even registration. Also, I didn’t want to log in using an email address and password or check my own database to see if the user exists. So, no Authlogic or Clearance for me. I had to go find a more low-level solution.

It didn’t take long before I found Warden, a “General Rack Authentication Framework”.

“Warden is rack based middleware, designed to provide a mechanism for authentication in Ruby web applications. It is a common mechanism that fits into the Rack Machinery to offer powerful options for authentication.”

Remember: it does not do registration, confirmation and the like. If you want anything like that, use Devise, a Rails authentication system based on Warden. @rbates also did a great Railscast on Devise.

“Warden uses the concept of cascading strategies to determine if a request should be authenticated. Warden will try strategies one after another until either one succeeds, no Strategies are found relevant or a strategy fails.”

An example of a strategy would be a user logging in with his username and password:

Warden::Strategies.add(:my_strategy) do

  def valid?
    params[:username] && params[:password]
  end

  def authenticate!
    u = User.find_by_username_and_password(
      params[:username],
      params[:password] # you should encrypt this. 😉
    )

    u.nil? ? fail!("Couldn't log in") : success!(u)
  end
end

The valid? method checks if the strategy is valid. In the example above it will return false when the username and password aren’t both in the params. In that case it will fail without even having to try and find the user.

authenticate! calls fail! with a message when the authentication failed. If the authentication passes, it’ll pass the User instance to success!. Pretty simple.

I’m not going into any specific stuff here, but if you’re using Rails you might want to check out rails_warden_mongoid_example. It’s a pretty simple and understandable application that shows you how to use Warden. Also, be sure to read the wiki, it has pretty good setup and example pages and there’s a lot more cool stuff in there.