Error on receive POST from third party URL in rails 4 - ruby-on-rails

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

Related

Ruby-on-rails: Get working but Post isn't

In very short.
When I have a form set as POST, the controller picks up the request, processes it and even starts to render the correct view. But the browser stays on the form page
When I switch the form to GET, it works
(yes, I remembered to change the route from get to post and back)
Here is the log:
Started POST "/sooth/search" for 127.0.0.1 at 2022-07-02 13:43:40
-0700 Processing by SoothController#search as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]",
"search"=>{"name"=>"search keywords"}, "commit"=>"Save Search"}
Rendering layout layouts/application.html.erb Rendering
sooth/search.html.erb within layouts/application
I am rendering the search html page
The line above is a log message in the search.html.erb page
Rendered sooth/search.html.erb within
layouts/application (Duration: 1.0ms | Allocations: 148) Rendered
layout layouts/application.html.erb (Duration: 6.6ms | Allocations:
2710) Completed 200 OK in 15ms (Views: 11.3ms | ActiveRecord: 0.0ms |
Allocations: 4040)
BUT the search page is not displayed. Browser stays on the search form page.
Any hints deeply appreciated.
(And as you have probably guessed, I am day 1 with rails)
EDIT:
class SoothController < ApplicationController
include SoothHelper
def index
puts "sooth index"
template = get_query_template('sooth_search')
puts(template)
end
def search
form_params = params[:search]
puts 'searching' + form_params[:name].to_s
render "sooth/search"
end
end
ROUTES
Rails.application.routes.draw do
Rails.application.routes.draw do
get "/nlp_data", to: "nlp_data#index"
get "/sooth", to: "sooth#index"
post "/sooth/search", to: "sooth#search"
end
Your problem is you are trying to render the same page instead of redirecting to to the sooth page ,and secondly you cannot acces params directly in a post request, instead you must acces it from a strong param method
class SoothController < ApplicationController
include SoothHelper
def index
puts "sooth index"
template = get_query_template('sooth_search')
puts(template)
end
def search
form_params = sooth_params[:search]
puts 'searching' + form_params[:name].to_s
redirect_to "/sooth"
end
private
def sooth_params
params.require(:sooth).permit(:search)
end
end

Ruby Rails Active Storage Exception

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.

Making Turbo Demo app work with local Rails server

I've set up a local Rails app that uses Turbo. I'm trying to shim the Turbo Demo iOS app to display my local Rails app. Has anyone been able to do a similar thing?
I switched Demo.current to use the local address, but all the requests show the "Error loading page" screen, with no useful logs coming out of the Demo app.
The Rails app shows my base route as being attempted, with some form of persistence with retrying a 401 error. I changed the SceneController default URL to load a /networks/all-people, which requires an authorized user (via Devise) to hopefully see how the authentication logic would go. Below is the Rails output when running the Demo app:
Started GET "/networks/all-people" for 127.0.0.1 at 2021-01-21 19:50:26 -0500
Processing by NetworksController#all_people as HTML
Completed 401 Unauthorized in 0ms (Allocations: 256)
Started GET "/users/sign_in" for 127.0.0.1 at 2021-01-21 19:50:26 -0500
Processing by Devise::SessionsController#new as HTML
Rendering layout layouts/application.html.erb
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (Duration: 0.3ms | Allocations: 218)
Rendered devise/sessions/new.html.erb within layouts/application (Duration: 1.7ms | Allocations: 1056)
Rendered layout layouts/application.html.erb (Duration: 9.4ms | Allocations: 7318)
Completed 200 OK in 10ms (Views: 9.8ms | Allocations: 7945)
Has anyone been able to shim the Demo app into working with a local Rails server? I'm entirely unsure of what's happening wrong here, or whether shimming is even a good idea here.
Turbo is being loaded in, as verified by the following event listener fires when visiting from my browser.
<script>
document.addEventListener("turbo:load", function(e) {
console.log("TURBO LOADED");
});
</script>
There are a few things that are needed to get Devise to work with Turbo.
Add app/controllers/turbo_controller:
# frozen_string_literal: true
class TurboController < ApplicationController
class Responder < ActionController::Responder
def to_turbo_stream
controller.render(options.merge(formats: :html))
rescue ActionView::MissingTemplate => e
raise e if get?
if has_errors? && default_action
render rendering_options.merge(formats: :html, status: :unprocessable_entity)
else
redirect_to navigation_location
end
end
end
self.responder = Responder
respond_to :html, :turbo_stream
end
Add data: { turbo: "false" } to your devise login form:
# app/views/devise/sessions/new.html.erb
<%= form_for(resource, as: resource_name, url: session_path(resource_name), data: { turbo: "false" }) do
Update config/initializers/devise.rb:
class TurboFailureApp < Devise::FailureApp
def skip_format?
%w[html turbo_stream */*].include?(request_format.to_s)
end
end
config.parent_controller = "TurboController"
config.navigational_formats = ["*/*", :html, :turbo_stream]
config.warden do |manager|
manager.failure_app = TurboFailureApp
end
Detailed explanation thanks to GoRails!

Rails_Admin Sign out not Redirecting (Devise)

We are using Devise, Rails_Admin and Simple_Token_Authentication (for API) in our application.
Everything is working fine except for sign out. When we click on Sign out, following request is made and the user gets signed out.
Started DELETE "/admins/sign_out" for 127.0.0.1 at 2015-07-12 18:50:44
+0530 Processing by Devise::SessionsController#destroy as HTML Parameters:
{"authenticity_token"=>"rtSRPzpRN7cWEk8wV8q6VDAUB575ZV46JeFFlMFVOQc="}
Admin Load (0.4ms) SELECT "admins".* FROM "admins" WHERE
"admins"."id" = 1 ORDER BY "admins"."id" ASC LIMIT 1 (0.1ms)
begin transaction (0.1ms) commit transaction Completed 204 No
Content in 700ms (ActiveRecord: 0.5ms)
The problem is that the page does not redirect after sign out.
On pressing the sign out button again, here is the request:
Started DELETE "/admins/sign_out" for 127.0.0.1 at 2015-07-12 19:01:59
+0530 Processing by Devise::SessionsController#destroy as HTML Parameters:
{"authenticity_token"=>"dHuxA5hRosyquhlsRmchK3vW9bQOCM/YXYXUNMxTufc="}
Filter chain halted as :verify_signed_out_user rendered or redirected
Completed 204 No Content in 1ms (ActiveRecord: 0.0ms)
Here is the application controller (app/controllers/application_controller.rb):
class ApplicationController < ActionController::Base
protect_from_forgery
skip_before_filter :verify_signed_out_user
respond_to :html, :json
protected
# Overwriting the sign_out redirect path method
def after_sign_out_path_for(resource_or_scope)
request.referrer
end
end
Here is the devise related code in app/config/initializers/rails_admin.rb
config.authenticate_with do
warden.authenticate! scope: :admin
end
config.current_user_method(&:current_admin)
Please suggest. Thanks in advance!
The problem is in your after_sign_out_path_for(resource_or_scope).
request.referrer redirects to the current page.
Change the after_sign_out_path_for(resource_or_scope) accordingly. If you want to redirect to root_path, then below would work.
def after_sign_out_path_for(resource_or_scope)
root_path
end

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

Resources