Ruby Rails Active Storage Exception - ruby-on-rails

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.

Related

No automatic sign_in after modifying devise registration controller

I initially wanted to send my user to a different page after sign_up. This works now, as I created a registrations controller. The problem now is that the user is prompted to login right after sign_up. Of course I want him to be automatically signed_in after sign_up. Any idea how I can fix that? I found this explanation but both answers do not work for me: Rails: Devise login after sign up.
Here is my registrations controller:
class RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters, if: :devise_controller?
def start_date
#user =current_user
end
protected
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status])
end
def after_sign_up_path_for(resource)
'/profiles/new' # Or :prefix_to_your_route
end
end
here are my application Logs after signup:
Started GET "/users/sign_up?job_category=IT+%26+Development&job_status=Other+Category&vacancy_id=general+application" for ::1 at 2019-08-08 15:32:17 +0200
Processing by RegistrationsController#new as HTML
Parameters: {"job_category"=>"IT & Development", "job_status"=>"Other Category", "vacancy_id"=>"general application"}
Rendering devise/registrations/new.html.erb within layouts/application
Rendered devise/registrations/new.html.erb within layouts/application (1.1ms)
Rendered shared/_navbar.html.erb (1.0ms)
Rendered shared/_flashes.html.erb (0.4ms)
Completed 200 OK in 174ms (Views: 171.7ms | ActiveRecord: 0.0ms)
Started POST "/users" for ::1 at 2019-08-08 15:32:32 +0200
Processing by RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Rb06/S6dB019mw8I46x0tJytVG7HNeVV23ZbuX/9Ykb9amYwI3bCLlk8AqNjTEGAR0qTy6rlCNZE1U6w8skslA==", "user"=>{"email"=>"testtesttest#test.de", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "applications"=>"\#{general application}", "job_category"=>"IT & Development", "job_status"=>"Other Category", "terms"=>"1"}, "commit"=>"Sign up"}
Can't verify CSRF token authenticity.
Unpermitted parameter: :terms
(0.5ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "testtesttest#test.de"], ["LIMIT", 1]]
SQL (6.9ms) INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "applications", "job_category", "job_status") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["email", "testtesttest#test.de"], ["encrypted_password", "$2a$11$MlDweUU00bKQsNyA81/Cuu/o9HQSYJHM8FCInvVSaYVspvcs36oMS"], ["created_at", "2019-08-08 13:32:32.764097"], ["updated_at", "2019-08-08 13:32:32.764097"], ["applications", "{{\"general application\"}}"], ["job_category", "IT & Development"], ["job_status", "Other Category"]]
UserMailer#welcome: processed outbound mail in 0.2ms
(8.4ms) COMMIT
Redirected to http://localhost:3000/profiles/new
Completed 302 Found in 316ms (ActiveRecord: 16.2ms)
Started GET "/profiles/new" for ::1 at 2019-08-08 15:32:32 +0200
Processing by ProfilesController#new as HTML
Completed 401 Unauthorized in 3ms (ActiveRecord: 0.0ms)
Started GET "/users/sign_in" for ::1 at 2019-08-08 15:32:32 +0200
Processing by Devise::SessionsController#new as HTML
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (1.3ms)
Rendered devise/sessions/new.html.erb within layouts/application (11.0ms)
Rendered shared/_navbar.html.erb (1.4ms)
Rendered shared/_flashes.html.erb (0.5ms)
Completed 200 OK in 198ms (Views: 196.5ms | ActiveRecord: 0.0ms)
Change permitted params from:
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status])
end
to:
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [ update_attrs, :applications, :job_category, :job_status])
end
And I think in profiles controller has a problem with before_action :authenticate_user! .
In terminal redirect has work.
You have a problem with terms, in your terminal:
Can't verify CSRF token authenticity.
Unpermitted parameter: :terms
Try changing the protect_from_forgery with: :exception to protect_from_forgery with: :exception, prepend: true
Ref: https://github.com/plataformatec/devise#controller-filters-and-helpers
Devise by default signout the session if the request is unverified.
Ref: from devise code(Devise::Controllers::Helpers),
# Overwrite Rails' handle unverified request to sign out all scopes,
# clear run strategies and remove cached variables.
def handle_unverified_request
super # call the default behaviour which resets/nullifies/raises
request.env["devise.skip_storage"] = true
sign_out_all_scopes(false)
end
Try this out if the first one solves the issue, https://github.com/plataformatec/devise/issues/2734 for solving the issue,
Change this:
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status]
To this:
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status, :terms]

Error on receive POST from third party URL in rails 4

I receive POST request from third party URL and update the data to my DB.
In config/environments/production.rb, I have:
config.force_ssl = true
Now when I receive the request the following error was occurred in my console.
Started POST "/delivery_details" for 35.355.466.466 at 2015-07-20 17:11:51 +1000
Processing by DeliveryDetailsController#create as HTML
Parameters: {"data"=>"{\"numbers\":{\"911234567890\":{\"desc\":\"MESSAGE\",\"status\":1,\"userId\":\"35534\",\"senderId\":\"qwerty\",\"date\":\"2015-07-20 12:41:59.0\"}},\"requestId\":\"12345566778\"}"}
Completed 401 Unauthorized in 1ms
Started GET "/users/sign_in" for 35.355.466.466 at 2015-07-20 17:11:51 +1000
Cannot render console from 35.355.466.466! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Devise::SessionsController#new as HTML
Rendered devise/sessions/new.html.erb within layouts/application (55.3ms)
Rendered layouts/_header.html.erb (3.9ms)
Rendered layouts/_menu.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (7.5ms)
Completed 200 OK in 82ms (Views: 78.6ms | ActiveRecord: 0.0ms)
My controller:
class DeliveryDetailsController < ApplicationController
skip_before_action :verify_authenticity_token
def index
updateSmsDeliveryStatus
end
def updateSmsDeliveryStatus
destinationType = "SMS"
json = JSON.parse(params["data"])
requestId = json["requestId"]
numbers = json['numbers']
numbers.each do |num|
#delivery_detail = DeliveryDetail.where(sms_request_id: requestId, destination_value: num[0].to_s,
destination_type: destinationType)
.update_all(:is_success => num[1]["status"], :sent_date => num[1]["date"])
end
end
end
I suppose that you have in your application controller the next line:
before_filter :authenticate_user!
So in your controller you need to skip this authentication:
skip_before_filter :authenticate_user!
And I don´t see in your controller the action create so maybe you receive a 404 error after this

Devise: one user getting a 302 and 401 error, no idea why, correct credentials not much in the log

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).

Can't authenticate on Rails with BCrypt - password hashes are different

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.

strange behavior when using devise: do not show flash message

in the sign_in page, I entered nothing and click submit. the page just refresh and no error message appears.
I have flash[:alert] and flash[:notice] in my view:
- if flash[:alert]
div.alert #{flash[:alert]}
- elsif flash[:notice]
div.notice #{flash[:notice]}
the logger says:
Started POST "/users/sign_in" for 127.0.0.1 at 2012-03-25 12:38:49 +0800
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9a85NKpAj3ZJgKnzStvBA3sxGqrShgbUqbjiJrqQCAM=", "user"=>{"email"=>"", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"登陆"}
Completed 401 Unauthorized in 0ms
Processing by SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9a85NKpAj3ZJgKnzStvBA3sxGqrShgbUqbjiJrqQCAM=", "user"=>{"email"=>"", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"登陆"}
Rendered devise/shared/_links.html.slim (0.3ms)
Rendered devise/sessions/new.html.slim within layouts/one_column (5.1ms)
Rendered layouts/_navbar.html.slim (0.8ms)
Rendered layouts/site.html.slim (12.8ms)
Completed 200 OK in 22ms (Views: 21.2ms | ActiveRecord: 0.0ms)
I'm confused with
"Completed 401 Unauthorized in 0ms"
I think there is something wrong..
but where?
Check your view page. Don't use 'flash'. According to the template (generated by scaffold)
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
You should change the variables in your view page, and you will see the error message such as "username should not be blank" or "用户名不能为空" in Chinese.
I had the same issue and you are correct to use:
- if flash[:alert]
div.alert #{flash[:alert]}
- elsif flash[:notice]
div.notice #{flash[:notice]}
My problem was I had my own config/locales defined ( en.yml, it.yml, etc ) but I had not copied the Devise entries over from config/locales/devise.en.yml.
As a quick test, I added the following to config/locales/en.yml:
en:
devise:
sessions:
signed_in: 'Signed in successfully.'
After signing in, flash[:notice] started working.

Resources