· 2 min read

Screencast: OmniAuth

Resourcen:

bash

[bash] rails g model identity name:string email:string password_digest:string rake db:migrate rails g controller identities [/bash]

Gemfile

[ruby] gem ‘omniauth-identity’ [/ruby]

config/initializers/omniauth.rb

[ruby] Rails.application.config.middleware.use OmniAuth::Builder do # … provider :identity, on_failed_registration: lambda { |env| IdentitiesController.action(:new).call(env) } end [/ruby]

models/identity.rb

[ruby] class Identity < OmniAuth::Identity::Models::ActiveRecord validates_presence_of :name validates_uniqueness_of :email validates_format_of :email, :with => /^[-a-z0-9_+.]+@([-a-z0-9]+.)+[a-z0-9]{2,4}$/i end [/ruby]

sessions/new.html.erb

[html]

Don’t use these services? <%= link_to “Create an account”, new_identity_path %> or login below.

<%= form_tag “/auth/identity/callback” do %>

<%= label_tag :auth_key, “Email” %>
<%= text_field_tag :auth_key %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<%= submit_tag “Login” %>
<% end %> [/html]

routes.rb

[ruby] resources :identities [/ruby]

identities_controller.rb

[ruby] def new @identity = env[‘omniauth.identity’] end [/ruby]

identities/new.html.erb

[html] <%= form_tag “/auth/identity/register” do %> <% if @identity && @identity.errors.any? %>

<%= pluralize(@identity.errors.count, “error”) %> prohibited this account from being saved:

    <% @identity.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>
<%= label_tag :name %>
<%= text_field_tag :name, @identity.try(:name) %>
<%= label_tag :email %>
<%= text_field_tag :email, @identity.try(:email) %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<%= label_tag :password_confirmation %>
<%= password_field_tag :password_confirmation %>
<%= submit_tag “Register” %>
<% end %> [/html]

Back to Blog