Rails 4 + Devise 3.0 - Authenticate using username and email - email

I'm trying to allow users to sign in with either their username or their email address.
as per here: https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address
When ever I try to sign in with either the email or the login this is logged:
Started POST "/users/sign_in" for 192.168.2.8 at 2013-11-22 10:11:50 +0800
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"WVTOKWQ8yJAJSu3NmXi3skJ8UC8zXY7qGZj7qbM3cr0=", "user"=>{"email"=>"testuser", "password"=>"password"}, "commit"=>"Sign in"}
User Load (3.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'testuser' ORDER BY "users"."id" ASC LIMIT 1
Completed 401 Unauthorized in 20ms
Processing by Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"WVTOKWQ8yJAJSu3NmXi3skJ8UC8zXY7qGZj7qbM3cr0=", "user"=>{"email"=>"rtype", "password"=>"password"}, "commit"=>"Sign in"}
Rendered devise/sessions/new.html.erb within layouts/application (6.4ms)
Completed 200 OK in 80ms (Views: 62.6ms | ActiveRecord: 0.0ms)
its weird the sql isn't checking for the username, so maybe the call on the user is wrong, but its exactly from the devise documentation.
I have read the following:
Adding Username to devise rails 4
Logging in with username using Devise with Rails 4
I also reviewed the warden code and the devise code to try and discover if I'm overriding the wrong method in the user.
Any ideas why it is not authenticating with username, when it does with email?
ApplicationController.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :remember_me) }
# Need to add other user fields like gender etc.
devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :current_password)}
end
end
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable, :encryptable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :login # This is used to add the login for allowing user to sign in with both email or username
# Validations
validates :username, presence: true, length: {maximum: 255}, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z0-9]*\z/, message: "may only contain letters and numbers." }
# Overwrite devise’s find_for_database_authentication method in user model
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:username)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
end
new.html
<fieldset>
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => { :class => 'form-horizontal' }) do |f| %>
<div class="control-group">
<%= f.label :login, "Email or Username" %>
<div class="controls"><%= f.text_field :login, :autofocus => true %></div>
</div>
<div class="control-group">
<%= f.label :password %>
<div class="controls"><%= f.password_field :password %></div>
</div>
<div class="form-actions">
<%= f.submit "Sign in", :class => "btn btn-primary", data: { disable_with: 'Working...' } %> <%= link_to "Forgot password?", new_password_path(resource_name), :class => "btn" %>
</div>
<% end %>
</fieldset>
Devise.rb
config.secret_key = 'Omitted for security'
config.mailer_sender = 'Omitted for security'
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true
config.password_length = 8..128
config.reset_password_within = 6.hours
config.encryptor = :sha512
config.sign_out_via = :delete

You need to add
config.authentication_keys = [ :login ]
within devise.rb
Also if you want to use login as reset password or confirmation keys you should also add within the same file:
config.reset_password_keys = [ :login ]
config.confirmation_keys = [ :login ]
You also need to whitelist the login parameter within your application_controller. In the new.html view you have a login form, so you must accept the login parameter for the sign_in instead of the username and email parameters.
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :password, :remember_me) }

Related

Submitting follower by form

Getting strange error in rails when saving a follower:
Error on Page after submitting follower form
I execute all of the commands in the followers#create method in the rails console and it works. But for some reason when I execute the form on the page, it does not seem to save the user then I get this error on the page. Any ideas? Not sure if it's got something to do with my routes, so I'll post them as well.
Routes.rb:
TwitterApp::Application.routes.draw do
get "followers/show"
get "followers/new"
get "dashboard/new"
get "users/new"
get "users/edit"
get "sessions/new"
get "add_follower" => "followers#new", :as => "add_follower"
#get '/followers/:id', to: 'followers#show', as: 'followers'
get '/like/:id', to: 'followers#like', as: 'like'
get "log_out" => "sessions#destroy", :as => "log_out"
get "" => "sessions#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
get "settings" => "users#edit", :as => "settings"
get "dashboard" => "dashboard#new", :as => "dashboard"
root :to => "sessions#new"
resources :users
resources :sessions
resources :followers
end
Follower Form:
<%= #follower_to_save.inspect %>
<h3>Add Follower: </h3>
<%= form_for #follower do |f| %>
<% if #follower.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :follower_username, class: "form-control", autofocus: "", required: "", placeholder: "Twitter Username" %><br/>
<p class="button"><%= submit_tag "Add", class: "btn btn-lg btn-primary btn-block" %></p>
<% end %>
Follower Controller:
class FollowersController < ApplicationController
helper_method :logged_in?
def new
#follower = Follower.new
end
def create
Twitter.configure do |config|
# Test Account
config.consumer_key = "6xkis3S0lpGZD6uFuhaLQ"
config.consumer_secret = "pxxDbmipacThWNZYOYVphakXbXGa5IMY0k6CFoe0M"
config.oauth_token = "2182147123-5V5Wy6syh420U6M6SduBWScZXiPSfCrLmN9GtUi"
config.oauth_token_secret = "KgeKQEt8Tddq8xjSVZIQ65TW9m48GWJardgZA7zloGvDF"
# Personal Account
#config.consumer_key = "HwJH0RTuonm8Z01IwCr0pA"
#config.consumer_secret = "1INqGLyDucW6rIHKKqq2pBS9pHgoIwQTg8CYvBuXrjI"
#config.oauth_token = "82839887-bCld1xMgYKq9Bqe8ie4XhzcEevsOyNc7kJC3NOpOB"
#config.oauth_token_secret = "In3a5B1oRG2xoaQSqoCk7gJqsJTOnMegWZoAirZp0tPzj"
end
#user = User.find(session[:user_id])
#follower_to_save = Follower.new
follower = Twitter.user(params[:follower_username])
#follower_to_save.follower_id = follower[:id]
#follower_to_save.owner = #user.id
#follower_to_save.follower_username = follower[:screen_name]
#follower_to_save.follower_nationality = follower[:location]
#follower_to_save.no_of_followers = follower[:followers_count]
#follower_to_save.following= follower[:friends_count]
#follower_to_save.no_of_tweets = follower[:statuses_count]
#follower_to_save.profile_picture_url = follower[:profile_image_url]
#follower_to_save.updated_at = Time.now
if #follower_to_save.save
redirect_to "/dashboard", #just_updated => "Follower Added!"
else
render "new"
end
end
def like
follower = Follower.find(params[:id])
if follower.liked == false
follower.liked = true
else
follower.liked = false
end
follower.save
end
def show
#follower = params[:id]
Twitter.configure do |config|
# Test Account
#config.consumer_key = "6xkis3S0lpGZD6uFuhaLQ"
#config.consumer_secret = "pxxDbmipacThWNZYOYVphakXbXGa5IMY0k6CFoe0M"
#config.oauth_token = "2182147123-5V5Wy6syh420U6M6SduBWScZXiPSfCrLmN9GtUi"
#config.oauth_token_secret = "KgeKQEt8Tddq8xjSVZIQ65TW9m48GWJardgZA7zloGvDF"
# Personal Account
config.consumer_key = "HwJH0RTuonm8Z01IwCr0pA"
config.consumer_secret = "1INqGLyDucW6rIHKKqq2pBS9pHgoIwQTg8CYvBuXrjI"
config.oauth_token = "82839887-bCld1xMgYKq9Bqe8ie4XhzcEevsOyNc7kJC3NOpOB"
config.oauth_token_secret = "In3a5B1oRG2xoaQSqoCk7gJqsJTOnMegWZoAirZp0tPzj"
end
#follower_tweets = Twitter.user_timeline(#follower)
#follower_db_instance = Follower.find_by_follower_username(#follower)
#follower_profile_pic ||= Twitter.user(#follower)[:profile_image_url]
end
def logged_in?
if session[:user_id].present?
true
else
false
end
end
end
rename #follower_to_save to #follower in method create

Call method after submitting form Rails

I have the following model:
class Coupon < ActiveRecord::Base
belongs_to :company
validates :description, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }
validates :fine_print, presence: true
end
and the following method in the coupon controller:
def redeem
if params[:pin] == #coupon.company.pin
redirect_to root_path
else
flash.now[:notice] = "Incorrect Pin"
render :show
end
end
This form is in the a view:
<%= form_for( #coupon, :url => coupons_redeem_path( #coupon ), :html => { :method => :post } ) do |f| %>
<%= label_tag("pin", "Search for:") %>
<%= text_field_tag("pin") %>
<%= f.submit "Close Message" %>
<% end %>
I want the form to call the redeem method in the coupons controller when hitting submit but am getting this error:
No route matches [POST] "/coupons/redeem.1"
EDIT
These are my routes:
resources :companies do
resources :coupons
end
get 'coupons/redeem'
In your routes, coupons are nested resources of companies. So you should choose one of these alternatives:
1st:
resources :companies do
resources :coupons do
post :redeem, on: :member
end
end
This leads to helpers like this: redeem_company_coupon_path(company, coupon) (and send smth there via POST).
If you don't want to include company to your path, you could choose 2nd:
resources :companies do
resources :coupons
end
post 'coupons/:id/redeem', to: 'coupons#redeem', as: :redeem_coupon
After that you could use redeem_coupon_path(coupon) helper

Rails: how to save few elements from string

I have rails form_tag helper to save data provided by do..each loop. This is my form:
<%= form_tag (customers_path) do |f| %>
< #contacts.each do |c|%>
<%= check_box_tag "accept[]", c %><%= c[:email] %>
<% end %>
<%= submit_tag ("Save") %>
<%end%>
This form saves the contacts whose checkbox is checked. Here is what, c has:
"accept"=>["{:id=>\"2f310f1d9b8f\",
:first_name=>\"San\",
:last_name=>\"Jori\",
:name=>\"Jori,San\",
:email=>\"abc#qwe.com\",
:gender=>nil,
:birthday=>nil,
:profile_picture=>nil,
:relation=>nil}"],
"commit"=>"Save"
I want to save only :name and :email from above hash.
This is my create action of controller:
if params[:accept].present?
params[:accept].each do |customer|
#customer = current_user.customers.new(:name => customer[:name], :email => customer[:email])
#customer.save
end
redirect_to customers_path
end
But it is giving error of :
no implicit conversion of Symbol into Integer
Can anyone tell me how to make it work?
Thank you!
Instead of using
#customer = current_user.customers.new(:name => customer[:name], :email => customer[:email])
Try
#customer = current_user.customers.build(:name => customer[:name], :email => customer[:email])

Save the file manually using paperclip from the params, without scaffold

I am new to rails, I was working on paperclip gem and wanted to save the simple files, saved from paperclip.
I have the My model as follow :-
class UserAttachment < ActiveRecord::Base
attr_accessible :email, :user_id, :attached_file
has_attached_file :attached_file
validates_attachment_presence :attached_file
validates_attachment_size :attached_file, :less_than => 20.megabytes
end
My controller action where the form is called :-
class HomeController < ApplicationController
def index
#uattachment = UserAttachment.new
end
end
Index view code, where the form is located
<%= form_for #uattachment, :url => attachment_get_link_path, :html => { :method => :post, :id => 'attachment_form', :multipart => true }, :remote => true do |f| %>
<%= f.email_field :email, :value=>nil, :placeholder => "Enter your email here", :required => true %><br />
<%= f.file_field :attached_file %>
<%= f.submit "Submit" %>
<% end %>
I want to use some following kind of code to save the data :-
(Code below is not the correct code, it's an excitation to tell what I want to do in my application.)
#uattachment = UserAttachment.new
#uattachment = params[:user_attachment]
#uattachment.save
Params received are as follows :-
(rdb:6) pp params
{"utf8"=>"✓",
"authenticity_token"=>"dfjaskldjadslgjsoidruts48589034lsker=",
"user_attachment"=>
{"email"=>"testing#email.com",
"attached_file"=>
#<ActionDispatch::Http::UploadedFile:0x007fcb58682ba0
#content_type="image/jpeg",
#headers=
"Content-Disposition: form-data; name=\"user_attachment[attached_file]\"; filename=\"someimage.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="800px-Kinnaur_Kailash.jpg",
#tempfile=#<File:/tmp/RackMultipart20121205-8432-1fc1kpi>>},
"commit"=>"Submit",
"controller"=>"attachment",
"action"=>"get_link"}
Got the catch, it was pretty simple, I checked it from the scaffolded assignment,
def index
#uattachment = UserAttachment.new(params[:user_attachment])
#uattachment.save
end
And you get the golden words in response "true".

How do I submit this form in Rails so it lands at /users/:id?

I'm trying to do something that seems conceptually simple, but I just can't get it working. Here's what I'm trying to do:
I have a simple "search" form on the /users/index page. It
leverages jQuery Tokeninput to autocomplete a user (name/username)
when the current user types into the search field. What I want to do
is let the user type a name, select a user from the list, then click
"submit" and be taken to the selected user's profile (/users/:id/ - which is
Users#show). I have jQuery Tokeinput configured to submit the user_id as :user_token.
I can't seem to get this working. The autocomplete part works correctly, but I can't figure out how to "submit" so that the entered user's profile is shown.
Here's what happens when I hit the "submit" button on the form (pulled from the development log in the terminal):
Started PUT "/users/2" for 127.0.0.1 at 2012-05-08 11:19:56 -0400
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"blah blah=", "user"=>{"user_token"=>"41"}, "commit"=>"Go to profile", "id"=>"2"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "2"]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1
Completed 500 Internal Server Error in 83ms
NoMethodError (undefined method `downcase!' for nil:NilClass):
app/controllers/users_controller.rb:119:in `update'
So it's calling the update action on the users controller, I assume because "#user" already exists (specifically, it's the current_user who clicks the submit button).
On screen, I see:
The path shown up top is .../users/2 (the id of current user), and in
the browser I see:
NoMethodError in UsersController#update
undefined method `downcase!' for nil:NilClass
I'm getting that because it's trying to run the "update" action in the Users controller, and there's a "downcase!" call on one of the params at the beginning up the update action. That parameter ([:user][:email]) obviously doesn't exist since it's not in the form I'm submitting.
What I really want to do is go to "/users/41" (the show page for the user whose id is passed as params[:user][:user_token]). How do I do this?
Here's all the relevant code:
#users_controller.rb#Index
def index
#title = "All users"
#label = "All users"
#list_users = User.order(:name).page(params[:page]) #generates users shown on index page
#user = current_user
# This is used to populate the autocomplete field in the little search form
#users = User.where("LOWER(name) like ? OR LOWER(username) like ?", "%#{params[:q].downcase}%", "%#{params[:q].downcase}%").order('name ASC').limit(10) if params[:q]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users, :only => [:id, :name, :username] }
end
end
My routes...
#routes.rb
resources :comments
resources :invitations
resources :sessions, :only => [:new, :create, :destroy]
resources :shares, :controller => "item_shares", :as => "item_shares" do
resources :comments
end
resources :posts, :controller => "item_posts", :as => "item_posts" do
resources :comments
end
resources :items
resources :relationships, only: [:create, :destroy]
resources :users do
member do
get :following, :followers
end
end
resources :password_resets
match '/signup', :to => 'users#new'
match '/signup/:invitation_token' => 'users#new', :as => :signup_with_invitation
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/invite', :to => 'invitations#new'
match '/users/:id/shared', :to => 'users#shared'
match '/users/:id/received', :to => 'users#received'
match '/users/:id/saved', :to => 'users#saved'
match '/users/:id/posts', :to => 'users#posts'
match '/reciprocal_followers', :to => 'users#reciprocal_followers'
root :to => 'pages#home'
Here is my form (this definitely does NOT work, although the jQuery Tokeninput does work):
#_user_search_form.html.erb
<div class="form">
<span class="form-label-right round-bottom-left-5 round-top-right-5 gray-gradient">Find someone</span>
<%= form_for #user, :action => "show" do |f| %>
<div class="field">
<%= f.label :user_token, "Name or Username" %></br>
<%= f.text_field :user_token, :placeholder => 'John Doe or JohnDoe123', "data-pre" => (#pre_populate_data.to_json(:only => [:id, :name, :username]) unless #pre_populate_data.nil?) %>
</div>
<div class="actions">
<%= f.submit "Go to profile" %>
</div>
<% end %>
</div>
Here's the relevant part of my user model:
#user.rb
attr_accessible :user_token
attr_reader :user_token
<% form_for #project, :url => { :controller => "project", :action => "thumbnail_save" } do |form| %>
....
<% end %>
Also write something like this in your config file (put it at the top)
get "users/show"
If that doesn't work try this. (you might have to change your form for below to work)
match "project/thumbnail_save", :to => "project#thumbnail_save"
Let us know if any more issues.