I am trying to create a simple authentication system but I seem to have a problem.
The signup process works fine, but when I try to login with the exact same information, I can't (I get "Invalid email or password"). As I saw, the hash comparison returns false. Here is my code:
#sessions_controller.rb
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
and
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :name
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = User.where(email: email).first
# throw Exception.new(user.password_hash) #uncaught throw #<Exception: $2a$10$9FHhPyb7BW01ktwTTgZHX.hlKKv4ajX/dX9D/xNGmZoajJTdGG4N.>
# throw Exception.new(user.password_salt) #uncaught throw #<Exception: $2a$10$9FHhPyb7BW01ktwTTgZHX.>
# throw Exception.new(BCrypt::Engine.hash_secret(password, user.password_salt)) #uncaught throw #<Exception: $2a$10$9FHhPyb7BW01ktwTTgZHX.O62xalJit020Jb0g5XDdB5V8dGMslQS>
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
So, as you can see in the commented lines in user.rb, the password hash that I get when trying to log in is not the same with the original one. Obviously, the password I enter is the correct one.
user.password_hash = $2a$10$9FHhPyb7BW01ktwTTgZHX.hlKKv4ajX/dX9D/xNGmZoajJTdGG4N.
user.password_salt = $2a$10$9FHhPyb7BW01ktwTTgZHX.
BCrypt::Engine.hash_secret(password, user.password_salt) = $2a$10$9FHhPyb7BW01ktwTTgZHX.O62xalJit020Jb0g5XDdB5V8dGMslQS
Can you please give me a hint here? What is that I do wrong?
Thanks a lot!
//later edit: also adding the users controller, perhaps this can help.
class UsersController < ApplicationController
def new
#user = User.new(user_params)
end
def create
#user = User.new(user_params)
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
private
def user_params
params.fetch(:user).permit(:name, :email, :password, :password_confirmation) if params[:user]
end
end
Edit: posting the logs for signing up/logging in
Started GET "/sign_up" for 127.0.0.1 at 2013-10-11 11:23:13 +0300
Processing by UsersController#new as HTML
Rendered users/new.html.erb within layouts/application (31.8ms)
Completed 200 OK in 48ms (Views: 41.8ms | ActiveRecord: 1.2ms)
Started POST "/users" for 127.0.0.1 at 2013-10-11 11:24:30 +0300
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LPLEs9at6BLGgjikYynnEzA/JAMMVl9IYGId1zEyNEg=", "user"=>{"name"=>"johntest", "email"=>"johntest#johntest.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
(0.1ms) BEGIN
User Exists (0.4ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'johntest#johntest.com' LIMIT 1
SQL (0.3ms) INSERT INTO `users` (`created_at`, `email`, `name`, `password_hash`, `password_salt`, `updated_at`) VALUES ('2013-10-11 08:24:30', 'johntest#johntest.com', 'johntest', '$2a$10$tpDFvkFUC.OPckDm6xacU.xkjFmECg2CDpsi3cjTJNX6K58ujHOn6', '$2a$10$tpDFvkFUC.OPckDm6xacU.', '2013-10-11 08:24:30')
(39.2ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 141ms (ActiveRecord: 40.0ms)
Started GET "/" for 127.0.0.1 at 2013-10-11 11:24:30 +0300
Processing by TroublesController#frontpage as HTML
Trouble Load (0.2ms) SELECT `troubles`.* FROM `troubles`
CACHE (0.0ms) SELECT `troubles`.* FROM `troubles`
Rendered troubles/_marker_infowindow.html.erb (0.8ms)
Rendered troubles/_marker_infowindow.html.erb (0.1ms)
Rendered /home/alex/.rvm/gems/ruby-2.0.0-p247/gems/gmaps4rails-1.5.6/app/views/gmaps4rails/_gmaps4rails.html.erb (1.9ms)
Rendered troubles/frontpage.html.erb within layouts/application (3.9ms)
Completed 200 OK in 21ms (Views: 13.5ms | ActiveRecord: 0.2ms)
[...](loading assets)
Started GET "/log_in" for 127.0.0.1 at 2013-10-11 11:24:52 +0300
Processing by SessionsController#new as HTML
Rendered sessions/new.html.erb within layouts/application (1.1ms)
Completed 200 OK in 14ms (Views: 12.8ms | ActiveRecord: 0.0ms)
Started POST "/sessions" for 127.0.0.1 at 2013-10-11 11:25:05 +0300
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LPLEs9at6BLGgjikYynnEzA/JAMMVl9IYGId1zEyNEg=", "name"=>"johntest", "email"=>"johntest#johntest.com", "password"=>"[FILTERED]", "commit"=>"Log in"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`email` = 'johntest#johntest.com' ORDER BY `users`.`id` ASC LIMIT 1
Rendered sessions/new.html.erb within layouts/application (1.7ms)
Completed 200 OK in 99ms (Views: 10.9ms | ActiveRecord: 0.4ms)
[...](loading assets)
So I went to the sign up page, filled in the details, I was forwarded to the homepage and it said "Signed up!". I clicked login, entered the details and it says "Invalid email or password".
Bcrypt is decrypting the right way but the culprit in your code is the before_save :encrypt_password just change the before save event as before_create event. with before_save , Every time you update the user record encrypt_password is called and it is encrypting the password field that way you are losing the first encrypted password which never matches though you give the correct password. I got stuck up with the same issue, after a deep analysis I got to know the fix.
Related
I'm working on a project in Ruby on Rails that I just added Active Storage to. Its throwing an exception and I can't quite figure it out. The aim is simply to allow a new registering user to upload an avatar image. In this case called :avatar_pic
Ruby 2.6.5
Rails 5.2.4
The error:
ActiveSupport::MessageEncryptor::InvalidMessage in UsersController#create
ActiveSupport::MessageEncryptor::InvalidMessage
Rails.root: /home/drew/code/epicodus/mario
Application Trace | Framework Trace | Full Trace
(erb):12:in `<main>'
app/controllers/users_controller.rb:8:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"LzeQ0IRBGGtNtKYt6z-NLGfLJJq4VVWy2KGkLa5aMAxDibOQQlKsPnbmIW6ZWkLJmUYGirKDW70bS2GLO0eNXw",
"user"=>
{"email"=>"i_mojo_jojo#yahoo.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"avatar_pic"=>
#<ActionDispatch::Http::UploadedFile:0x00007f3e3879bb48
#content_type="image/webp",
#headers="Content-Disposition: form-data; name=\"user[avatar_pic]\"; filename=\"1778557mojo_jojo_cropped.webp\"\r\n" + "Content-Type: image/webp\r\n",
#original_filename="1778557mojo_jojo_cropped.webp",
#tempfile=#<File:/tmp/RackMultipart20210402-20294-1gntmpk.webp>>,
"admin"=>"1"},
"commit"=>"Sign Up"}
Toggle session dump
Toggle env dump
Response
Headers:
None
The Rails Server says:
enteStarted GET "/signup" for 127.0.0.1 at 2021-04-02 14:18:21 -0700
Processing by UsersController#new as HTML
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (12.3ms)
Rendered layouts/_header.html.erb (2.5ms)
Rendered layouts/_navbar.html.erb (1.5ms)
Completed 200 OK in 103ms (Views: 93.7ms | ActiveRecord: 0.0ms)
Started GET "/signup" for 127.0.0.1 at 2021-04-02 14:18:37 -0700
Processing by UsersController#new as HTML
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (5.3ms)
Rendered layouts/_header.html.erb (1.8ms)
Rendered layouts/_navbar.html.erb (1.5ms)
Completed 200 OK in 52ms (Views: 50.5ms | ActiveRecord: 0.0ms)
Started POST "/users" for 127.0.0.1 at 2021-04-02 14:29:09 -0700
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XhEhZj9D8m_uamyYLt-IjQaVtNyrhQKz47DN1zjmkbwyrwIm-VBGOtU469tcukdo-BiWzKFTDLwgWghxrfss7w", "user"=>{"email"=>"i_mojo_jojo#yahoo.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "avatar_pic"=>#<ActionDispatch::Http::UploadedFile:0x00007f3e34d71ff8 #tempfile=#<Tempfile:/tmp/RackMultipart20210402-20294-1rjp10e.webp>, #original_filename="1778557mojo_jojo_cropped.webp", #content_type="image/webp", #headers="Content-Disposition: form-data; name=\"user[avatar_pic]\"; filename=\"1778557mojo_jojo_cropped.webp\"\r\nContent-Type: image/webp\r\n">, "admin"=>"1"}, "commit"=>"Sign Up"}
Completed 500 Internal Server Error in 31ms (ActiveRecord: 9.2ms)
ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage):
(erb):12:in `<main>'
app/controllers/users_controller.rb:8:in `create'
Started GET "/signup" for 127.0.0.1 at 2021-04-02 14:39:11 -0700
Processing by UsersController#new as HTML
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (2.6ms)
Rendered layouts/_header.html.erb (1.2ms)
Rendered layouts/_navbar.html.erb (1.0ms)
Completed 200 OK in 50ms (Views: 30.4ms | ActiveRecord: 6.8ms)
Started POST "/users" for 127.0.0.1 at 2021-04-02 14:39:18 -0700
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LkVpArq_38Esb10kyWy_dKpK60_r5OIuFNGBNS4n1PtC-0pCfKxrlBc92me7CXCRVMfJX-Ey7CHXO0STuzppqA", "user"=>{"email"=>"i_mojo_jojo#yahoo.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "avatar_pic"=>#<ActionDispatch::Http::UploadedFile:0x00007f3e38d978a8 #tempfile=#<Tempfile:/tmp/RackMultipart20210402-20294-171sahq.webp>, #original_filename="1778557mojo_jojo_cropped.webp", #content_type="image/webp", #headers="Content-Disposition: form-data; name=\"user[avatar_pic]\"; filename=\"1778557mojo_jojo_cropped.webp\"\r\nContent-Type: image/webp\r\n">, "admin"=>"1"}, "commit"=>"Sign Up"}
Unpermitted parameter: :avatar_pic
Completed 500 Internal Server Error in 13ms (ActiveRecord: 2.6ms)
ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage):
(erb):12:in `<main>'
app/controllers/users_controller.rb:9:in `create'
Started GET "/signup" for 127.0.0.1 at 2021-04-02 14:39:51 -0700
Processing by UsersController#new as HTML
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (5.1ms)
Rendered layouts/_header.html.erb (2.4ms)
Rendered layouts/_navbar.html.erb (1.3ms)
Completed 200 OK in 80ms (Views: 60.3ms | ActiveRecord: 4.9ms)
Started POST "/users" for 127.0.0.1 at 2021-04-02 14:39:57 -0700
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LzeQ0IRBGGtNtKYt6z-NLGfLJJq4VVWy2KGkLa5aMAxDibOQQlKsPnbmIW6ZWkLJmUYGirKDW70bS2GLO0eNXw", "user"=>{"email"=>"i_mojo_jojo#yahoo.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "avatar_pic"=>#<ActionDispatch::Http::UploadedFile:0x00007f3e3879bb48 #tempfile=#<Tempfile:/tmp/RackMultipart20210402-20294-1gntmpk.webp>, #original_filename="1778557mojo_jojo_cropped.webp", #content_type="image/webp", #headers="Content-Disposition: form-data; name=\"user[avatar_pic]\"; filename=\"1778557mojo_jojo_cropped.webp\"\r\nContent-Type: image/webp\r\n">, "admin"=>"1"}, "commit"=>"Sign Up"}
Completed 500 Internal Server Error in 15ms (ActiveRecord: 3.7ms)
ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage):
(erb):12:in `<main>'
app/controllers/users_controller.rb:8:in `create'
r code here
My Model:
class User < ApplicationRecord
attr_accessor :password
validates_confirmation_of :password
validates :email, :presence => true, :uniqueness => true
before_save :encrypt_password
has_one_attached :avatar_pic
def encrypt_password
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password,password_salt)
end
def self.authenticate(email, password)
user = User.find_by "email = ?", email
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
end
My controller:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(user_params)
#user.avatar_pic.attach(params[:user][:avatar_pic])
if #user.save
flash[:notice] = "You've successfully signed up!"
session[:user_id] = #user.id
redirect_to "/"
else
flash[:alert] = "There was a problem signing up."
redirect_to '/signup'
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :admin, :avatar_pic)
end
end
My view form:
<%= form_for #user do |f| %>
<%= f.label "Email" %>
<%= f.text_field :email, id: 'registration_email' %>
<%= f.label "Password" %>
<%= f.password_field :password, id: 'registration_password' %>
<%= f.label "Password confirmation" %>
<%= f.password_field :password_confirmation, id: 'reg_password_confirm' %>
<br>
<%= f.label "Upload Avatar Image" %>
<%= f.file_field :avatar_pic %>
<br>
<%= f.label "Admin?", name: 'admin_check', id: 'admin_check' %>
<%= f.check_box:admin %>
<br>
<%= f.submit "Sign Up" %>
<% end %>
So it seems the image uploads alright. I think my controller params are the problem and it isn't validating.... something. But I don't see how. I think it's in the params. I'm stumped.
Ok, so I found the problem. I had copied this repo down and it was originally developed on a different system. I didn't have the master.key (which I wasn't aware existed at the time).
https://github.com/rails/rails/issues/33463
I followed the instructions of Vladimir-19 and that solved it.
Trying to signup in my RoR webapp give me the Devise Message "Auth token has already been taken"
Also, the webapp have an API and works fine, doesn't give any message, this only happen when I'm trying to use the HTML view.
user_controller.rb
before_action :set_user, only: [:show, :edit, :update, :destroy]
# DELETE /users/:id.:format
def destroy
# authorize! :delete, #user
#user.destroy
respond_to do |format|
format.html { redirect_to root_url }
end
end
private
def set_user
#user = User.find(params[:id])
end
def user_params
accessible = [ :name, :email ]
accessible << [ :password, :password_confirmation ] unless params[:user][:password].blank?
params.require(:user).permit(accessible)
end
User.rb
validates :auth_token, uniqueness: true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_create :generate_authentication_token!
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
logs
Started GET "/users/sign_up" for 127.0.0.1 at 2015-06-30 09:31:46 -0500
Processing by Devise::RegistrationsController#new as HTML
Rendered devise/registrations/new.html.haml within layouts/application (12.9ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."auth_token" IS NULL LIMIT 1
Rendered layouts/_navigation_links.html.haml (2.1ms)
Rendered layouts/_navigation.html.haml (3.4ms)
Rendered layouts/_messages.html.haml (0.2ms)
Completed 200 OK in 132ms (Views: 117.0ms | ActiveRecord: 1.5ms)
Started POST "/users" for 127.0.0.1 at 2015-06-30 09:32:00 -0500
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"20w9AXmACwggvPocKfLBdrxQRasT5OiaC7niuzooBBm3BAp8xkN6VLWyxZLRoLIpFPEIIdkxZRd9CCwsJxkeUA==", "user"=>{"email"=>"hola#x.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
(0.1ms) BEGIN
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."auth_token" = '' LIMIT 1
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'hola#x.com' LIMIT 1
(0.1ms) ROLLBACK
Rendered devise/registrations/new.html.haml within layouts/application (3.2ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."auth_token" IS NULL LIMIT 1
Rendered layouts/_navigation_links.html.haml (1.5ms)
Rendered layouts/_navigation.html.haml (2.1ms)
Rendered layouts/_messages.html.haml (0.2ms)
Completed 200 OK in 232ms (Views: 134.4ms | ActiveRecord: 1.2ms)
Started GET "/assets/jquery/jquery-bb5529929fa5581a780a38ecb7470f2c.js?body=1" for 127.0.0.1 at 2015-06-30 09:32:00 -0500
Follow the following
1) Open Rails console
rails console
2) Get the total count of users
user = User.all
user.count
this should be 1
3) Get the user and check the auth token
user = User.last
user.auth_token
auth token would be an empty string which is the reason your command is failing as the user doesn't have valid auth token
4) Create a valid auth token for the user
user.auth_token = Devise.friendly_token
user.save
It would create a valid auth token for the user and save it
5) Now you can run your commands and it would work perfectly
Cheers! :)
It's probably because you already have users in your db without auth_token,
use Devise.friendly_token to update those users with a token
The create method is getting executed properly as shown on the console but redirect is failing to render on the browser.
controller
def create
#try to authenticate the user - if they authenticate successfully, an instance of the User model is returned
#user = User.authenticate(params[:email], params[:password])
#if an instance is returned and #user is not nil...
if #user
#let the user know they've been logged in with a flash message
flash.now[:notice] = "You've been logged in."
#THIS IS THE MOST IMPORTANT PART. Actually log the user in by storing their ID in the session hash with the [:user_id] key!
session[:user_id] = #user.id
#then redirect them to the homepage
redirect_to "/"
return
else
#whoops, either the user wasn't in the database or their password is incorrect, so let them know, then redirect them back to the log in page
flash.now[:alert] = "There was a problem logging you in."
redirect_to "/log-in"
return
end
end
console
Started POST "/log-in? create=%7B%22method%22:%22PUT%22,%22responseType%22:%22json%22%7D" for 127.0.0.1 at 2015-05-21 12:51:36 +0530
Processing by SessionsController#create as HTML
Parameters: {"email"=>"harsh#gmail.com", "password"=>"[FILTERED]", "create"=>"{\"method\":\"PUT\",\"responseType\":\"json\"}", "session {"email"=>"harsh#gmail.com", "password"=>"[FILTERED]"}}
User Load (22.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'harsh#gmail.com' ORDER BY "users"."id" ASC LIMIT 1
this is user entered passwordharsh
this is encript hash passwors$2a$10$kPfxXAMxcWHhJjcO9ubXv.Q2xbCMPA6K2epe/dGX5EDAIcbmnvJDi
Redirected to http://localhost:3000/
Completed 302 Found in 307ms (ActiveRecord: 23.0ms)
Started GET "/" for 127.0.0.1 at 2015-05-21 12:51:37 +0530
Processing by UsersController#index as HTML
Rendered users/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 349ms (Views:324.0ms | ActiveRecord: 0.0ms)
I searched for similar questions and tried all the answers but its still not getting rendered on browser.
Please help if you know the answer
Thanks
Remove return from the last lines. Rails looks for the redirection/rendering on the last line of the action being called. Let me know if that does the trick.
Hope this helps!
I've got a Rails app which generally works fine, but one (that I can find) user is causing a 302 error, and they can't log in. The log looks like this:
Started GET "/d/sign_in" for 127.0.0.1 at 2014-12-15 05:38:14 +0000
Processing by Devise::SessionsController#new as */*
Rendered devise/sessions/new.html.erb within layouts/application (0.5ms)
Rendered layouts/_navigation.html.erb (2.3ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 10.1ms (Views: 7.2ms | ActiveRecord: 0.8ms)
Started GET "/d/sign_in" for 127.0.0.1 at 2014-12-15 05:38:14 +0000
Processing by Devise::SessionsController#new as */*
Rendered devise/sessions/new.html.erb within layouts/application (0.7ms)
Rendered layouts/_navigation.html.erb (2.2ms)
Rendered layouts/_messages.html.erb (0.2ms)
Completed 200 OK in 10.9ms (Views: 8.1ms | ActiveRecord: 0.7ms)
Started GET "/" for 58.111.229.203 at 2014-12-15 05:38:20 +0000
Processing by DocumentsController#index as HTML
Completed 401 Unauthorized in 0.5ms
Started POST "/d/sign_in" for 58.111.229.203 at 2014-12-15 05:38:28 +0000
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"cvyg6GWTtpd4M1klk0j6APbv4h36+a99yb9k646BRZA=", "user"=>{"email"=>"admin#blank.net", "password"=>"[FILTERED]"}, "commit"=>"Sign in"}
Redirected to http://appdomain.com/
Completed 302 Found in 310.2ms (ActiveRecord: 0.0ms)
Started GET "/d/sign_in" for 127.0.0.1 at 2014-12-15 05:38:29 +0000
Processing by Devise::SessionsController#new as */*
Rendered devise/sessions/new.html.erb within layouts/application (0.5ms)
Rendered layouts/_navigation.html.erb (2.7ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 10.1ms (Views: 7.4ms | ActiveRecord: 0.8ms)
Now, the 127.0.0.1 things concern me since this is a production environment, but it might be just a service (Pingdom) ensuring the app is still up. Nevertheless, this user can't log in and I can't figure it out. No other users are affected that I know of, and the user has everything they need to be able to log in. No detailed errors are in the log (like missing resources or similar), it just hangs when they log in. Any help would be great.
Update
Here's DocumentsController (the relevant parts):
class DocumentsController < ApplicationController
include ApplicationHelper
include DocumentsHelper
include ServerHelper
load_and_authorize_resource
def index
#documents = current_user.documents.includes(:template).includes(:user)
.includes(:pdf_result).created.page(params[:page])
.per(10)
#categories = current_user.brand.templates.all.group_by(&:category)
#assets = AssetResources.new(current_user)
end
...
Changing this user to an administrator does not fix the problem. I guess ApplicationController is relevant too, and this is it:
class ApplicationController < ActionController::Base
before_filter :authenticate_user!, :check_mode
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
redirect_to documents_url, alert: exception.message
end
helper_method :current_user, :authorised_user
hide_action :current_user
def mode
#mode = Mode.first
end
def check_mode
flash.now[:alert] = mode.messages unless mode.all_online
end
private
def user_activity
current_user.try :touch
end
def authorised_user
#authorised_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
UPDATE The credentials are correct, when that email address and an incorrect password are entered I get a bad credentials message. The correct credentials just hangs.
Check
Whether this "admin#blank.net" user exists in database.
You are providing correct credentials.
Because when sign in fails, devise internally performs redirection and 302 is HTTP response status code for URL redirection.
In the database, ensure whether this user exists and you are providing the right credentials.
I know this is old. But just in case someone has the same problem, as I just did, here is what fixed it for me:
In
config/initializers/session_store.rb
change
Rails.application.config.session_store :cookie_store, key: 'my_secure_session', httponly: false, secure: true
to
Rails.application.config.session_store :cookie_store, key: 'my_session'
Why I had this problem in the first place: I copied a running Rails 4 server with SSL and booted it up in dev mode without SSL. Commenting out force_ssl in application_controller.rb allowed me to start the server without ssl but left me with the 302 and 401 error and a redirect back to the sign-in page (without notification).
I am using devise and i am trying to allow user to modify their information without providing their information. I have followed the tutorial https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password.
I have this link to allow user to change their own settings
<%= link_to "Account Settings", edit_user_registration_path(current_user) %>
What I did his follow
rails g controller Registration
In the registrations controller replace the content with this
class RegistrationsController < Devise::RegistrationsController
def update
#user = User.find(current_user.id)
email_changed = #user.email != params[:user][:email]
password_changed = !params[:user][:password].empty?
successfully_updated = if email_changed or password_changed
#user.update_with_password(params[:user])
else
#user.update_without_password(params[:user])
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in #user, :bypass => true
redirect_to after_update_path_for(#user)
else
render "edit"
end
end
end
And in route.rb file i did this
devise_for :users, :controllers => { :registrations => "registrations" }
But it still bring me to the folder /views/devise/registration/edit.erb.html instead of bringing me to /views/registrations/edit.erb.html. I also restarted the server and my computer but no clue what else to do
Update: Note(customers = Users)
Started GET "/customers/edit.2" for 127.0.0.1 at 2012-12-09 20:06:03 -0500
Processing by Devise::RegistrationsController#edit as
[1m[35mCustomer Load (0.3ms)[0m SELECT `customers`.* FROM `customers` WHERE `customers`.`id` = 2 LIMIT 1
[1m[36mPage Load (0.2ms)[0m [1mSELECT `pages`.* FROM `pages` [0m
[1m[35mTag Load (0.2ms)[0m SELECT `tags`.* FROM `tags`
Rendered devise/registrations/edit.html.erb within layouts/application (0.1ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_iewrap.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_search_tags.html.erb (0.0ms)
Rendered layouts/_navigation.html.erb (0.8ms)
Rendered layouts/_thirdcol.html.erb (0.0ms)
Rendered pages/_link.html.erb (0.0ms)
Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 41ms (Views: 36.4ms | ActiveRecord: 0.7ms)
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2012-12-09 20:06:04 -0500
Served asset /application.css - 304 Not Modified (5ms)
Started GET "/assets/activity_managers.css?body=1" for 127.0.0.1 at 2012-12-09 20:06:04 -0500
Served asset /activity_managers.css - 304 Not Modified (0ms)
this is the path i get to
http://localhost:3000/customers/edit.2
You got the name and location of your file wrong.
The file should be called edit.html.erb, not edit.erb.html.
The file should be localed in app/views/registrations.
Also, whenever a url has .id appended at the end, it means that you are passing something to the url helper that you shouldn't be. So in this case, you can remove the current_user argument and use your link like this:
<%= link_to "Account Settings", edit_user_registration_path %>
In config/initializers/devise.rb, uncomment this line config.scoped_views = true then restart Rails server. Also check if your edit.erb.html is in the right directory, it may be need to be in app/views/users/registrations/.
UPDATE:
You need to define edit method in your RegistrationsController because without it will inherit from Devise's RegistrationsController and consequently render Devises's views. Just add these two lines to the controller and it should work.
def edit
end