Skip to content

Instantly share code, notes, and snippets.

@simeonwillbanks
Created June 1, 2011 17:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simeonwillbanks/1002780 to your computer and use it in GitHub Desktop.
Save simeonwillbanks/1002780 to your computer and use it in GitHub Desktop.
#omniauth #oauth OmniAuth oa-identity

oa-identity strategy walkthrough

github links

README
Model Example

lp31 app links

Login (Name form field expects email address)
Register

lp31 files

# config/application.rb
config.middleware.use OmniAuth::Builder do
  # Strategy user User model instead of default Identity model
  provider :identity, :model => User, :fields => [:first_name, :last_name, :email]
end
# app/models/user.rb
class User < OmniAuth::Identity::Models::ActiveRecord
end

Quick and dirty sign in and sign out with help from RailsCasts

# config/routes.rb 
Lp31::Application.routes.draw do
  # OmniAuth strategies require a callback
  match "/auth/:provider/callback" => "sessions#create"
  match "/signout" => "sessions#destroy", :as => :signout

  # ... other configs omitted for brevity
end
# app/controllers/session.rb
class SessionsController < ApplicationController
  
  def create
    auth = request.env["omniauth.auth"]
    user = User.find(auth["uid"])
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Signed in!"
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Signed out!"
  end
  
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery 
  # Basic user session handling
  helper_method :current_user

  private
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

lp31 console

$ user = User.new(:first_name => "simeon", :last_name => "willbanks", :password => "", :password_confirmation => "nomatch", :email => "simeon@tld.com")
$ user.save
=> false
$ user.errors[:password]
=> ["doesn't match confirmation"]
$ user.errors[:password_digest]
=> ["can't be blank"]
$ user.password = "mUc3m00RsqyRe"
=> "mUc3m00RsqyRe"
$ user.save
=> false
$ user.password_confirmation = "mUc3m00RsqyRe"
=> "mUc3m00RsqyRe"
$ user.save
=> true
$ user.errors[:password_digest]
=> []
$ user.authenticate("notright")
=> false
$ user.authenticate("mUc3m00RsqyRe")
=> #<User id: 1>
$ User.find_by_email("simeon@tld.com").try(:authenticate, "notright")
=> false
$ User.find_by_email("simeon@tld.com").try(:authenticate, "mUc3m00RsqyRe")
=> #<User id: 1>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment