Rails session gets destroy whenever model destroy link is clicked - ruby-on-rails-3

If I click destroy on any record for my 3 models models, the user gets logged out. I'm using Devise and Ominauth.
#This logs out a user
def destroy
#rating = Rating.find(params[:id])
#rating.destroy
end
Started POST "/ratings/29" for 192.168.1.103 at 2011-02-26 20:11:45 +0000
Processing by RatingsController#destroy as HTML
Parameters: {"id"=>"29"}
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Rating Load (0.3ms) SELECT `ratings`.* FROM `ratings` WHERE `ratings`.`id` = 29 LIMIT 1
SQL (0.0ms) BEGIN
AREL (0.5ms) DELETE FROM `ratings` WHERE `ratings`.`id` = 29
SQL (2.7ms) COMMIT
Request
Parameters:
None
Show session dump
session_id: "16a92c418fdfa8966b60b09e76346443"
Show env dump
GATEWAY_INTERFACE: "CGI/1.1"
HTTP_ACCEPT: "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
HTTP_ACCEPT_CHARSET: "ISO-8859-1,utf-8;q=0.7,*;q=0.3"
HTTP_ACCEPT_ENCODING: "gzip,deflate,sdch"
HTTP_ACCEPT_LANGUAGE: "en-US,en;q=0.8"
HTTP_CACHE_CONTROL: "max-age=0"
HTTP_CONNECTION: "keep-alive"
HTTP_COOKIE: "_traitly_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY%3D--4c140502f8a075f61742fdf11e6fc7100722ca14"
HTTP_HOST: "192.168.1.105:3000"
HTTP_IF_NONE_MATCH: "\"2d7f4ba60c47e0cf39f1361e2274fa89\""
HTTP_REFERER: "http://192.168.1.105:3000/subjects"
HTTP_USER_AGENT: "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.82 Safari/534.16"
HTTP_VERSION: "HTTP/1.1"
PATH_INFO: "/subjects"
QUERY_STRING: ""
REMOTE_ADDR: "192.168.1.103"
REMOTE_HOST: "192.168.1.103"
REQUEST_METHOD: "GET"
REQUEST_PATH: "/"
REQUEST_URI: "http://192.168.1.105:3000/subjects"
SCRIPT_NAME: ""
SERVER_NAME: "192.168.1.105"
SERVER_PORT: "3000"
SERVER_PROTOCOL: "HTTP/1.1"
SERVER_SOFTWARE: "WEBrick/1.3.1 (Ruby/1.9.2/2010-12-25)"
action_controller.instance: #<SubjectsController:0x90ecc1c #action_has_layout=true, #view_context_class=nil, #_headers={"Content-Type"=>"text/html"}, #_status=200, #_response=#<ActionDispatch::Response:0x90ecb68 ......Too long - had to cut it off
action_dispatch.cookies: {"_traitly_session"=>"BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY=--4c140502f8a075f61742fdf11e6fc7100722ca14"}
action_dispatch.parameter_filter: [:password, :password, :password_confirmation]
action_dispatch.remote_ip: 192.168.1.103
action_dispatch.request.content_type: nil
action_dispatch.request.formats: [text/html]
action_dispatch.request.parameters: {"action"=>"index", "controller"=>"subjects"}
action_dispatch.request.path_parameters: {:action=>"index", :controller=>"subjects"}
action_dispatch.request.query_parameters: {}
action_dispatch.request.request_parameters: {}
action_dispatch.request.unsigned_session_cookie: {"session_id"=>"199411b3c1c3ce55b0d3cb86cab0cb76"}
action_dispatch.secret_token: "b3dc65e5cc9d1af31fb06160a604132f5a1f4d13edc313d74cb1bfd7e63994d429f6e8032669ea26ff4a8dab66b79f6070f8449b4a422a7862bb4307a4d84416"
rack.errors: #<IO:<STDERR>>
rack.input: #<StringIO:0x913578c>
rack.multiprocess: false
rack.multithread: false
rack.request.cookie_hash: {"_traitly_session"=>"BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY=--4c140502f8a075f61742fdf11e6fc7100722ca14"}
rack.request.cookie_string: "_traitly_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY%3D--4c140502f8a075f61742fdf11e6fc7100722ca14"
rack.request.query_hash: {}
rack.request.query_string: ""
rack.run_once: false
rack.session: {"session_id"=>"199411b3c1c3ce55b0d3cb86cab0cb76"}
rack.session.options: {:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :id=>"199411b3c1c3ce55b0d3cb86cab0cb76"}
rack.url_scheme: "http"
rack.version: [1, 1]
warden: #<Warden::Proxy:0x9133bf8 #winning_strategies={}, #users={:user=>nil}, #env={"GATEWAY_INTERFACE"=>"CGI/1.1", "PATH_INFO"=>"/subjects", "QUERY_STRING"=>"", "REMOTE_ADDR"=>"192.168.1.103", "REMOTE_HOST"=>"192.168.1.103", "REQUEST_METHOD"=>"GET", "REQUEST_URI"=>"http://192.168.1.105:3000/subjects", "SCRIPT_NAME"=>"", "SERVER_NAME"=>"192.168.1.105", "SERVER_PORT"=>"3000", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"WEBrick/1.3.1 (Ruby/1.9.2/2010-12-25)", "HTTP_HOST"=>"192.168.1.105:3000", "HTTP_CONNECTION"=>"keep-alive", "HTTP_REFERER"=>"http://192.168.1.105:3000/subjects", "HTTP_CACHE_CONTROL"=>"max-age=0", "HTTP_USER_AGENT"=>"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.82 Safari/534.16", "HTTP_ACCEPT"=>"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "HTTP_ACCEPT_ENCODING"=>"gzip,deflate,sdch", "HTTP_ACCEPT_LANGUAGE"=>"en-US,en;q=0.8", "HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.3", "HTTP_COOKIE"=>"_traitly_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY%3D--4c140502f8a075f61742fdf11e6fc7100722ca14", "HTTP_IF_NONE_MATCH"=>"\"2d7f4ba60c47e0cf39f1361e2274fa89\"", "rack.version"=>[1, 1], "rack.input"=>#<StringIO:0x913578c>, "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>false, "rack.multiprocess"=>false, "rack.run_once"=>false, "rack.url_scheme"=>"http", "HTTP_VERSION"=>"HTTP/1.1", "REQUEST_PATH"=>"/", "action_dispatch.parameter_filter"=>[:password, :password, :password_confirmation], "action_dispatch.secret_token"=>"b3dc65e5cc9d1af31fb06160a604132f5a1f4d13edc313d74cb1bfd7e63994d429f6e8032669ea26ff4a8dab66b79f6070f8449b4a422a7862bb4307a4d84416", "action_dispatch.remote_ip"=>192.168.1.103, "rack.session"=>{"session_id"=>"199411b3c1c3ce55b0d3cb86cab0cb76"}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :id=>"199411b3c1c3ce55b0d3cb86cab0cb76"}, "rack.request.cookie_string"=>"_traitly_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY%3D--4c140502f8a075f61742fdf11e6fc7100722ca14", "rack.request.cookie_hash"=>{"_traitly_session"=>"BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY=--4c140502f8a075f61742fdf11e6fc7100722ca14"}, "action_dispatch.cookies"=>{"_traitly_session"=>"BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTk5NDExYjNjMWMzY2U1NWIwZDNjYjg2Y2FiMGNiNzY=--4c140502f8a075f61742fdf11e6fc7100722ca14"}, "action_dispatch.request.unsigned_session_cookie"=>{"session_id"=>"199411b3c1c3ce55b0d3cb86cab0cb76"}, "warden"=>#<Warden::Proxy:0x9133bf8 ...>, "action_dispatch.request.path_parameters"=>{:action=>"index", :controller=>"subjects"}, "action_controller.instance"=>#<SubjectsController:0x90ecc1c #action_has_layout=true, #view_context_class=nil, #_headers={"Content-Type"=>"text/html"}, #_status=200, #_response=#<ActionDispatch::Response:0x90ecb68 #writer=#<Proc:0x90ecaf0#/usr/local/rvm/gems/ruby-1.9.2-p136#traitly/gems/actionpack-3.0.4/lib/action_dispatch/http/response.rb:43 (lambda)>, #block=nil, #length=0, #header={}, #status=200, #body=[], #cookie=[], #sending_file=false, #blank=false, #cache_control={}, #etag=nil, #request=#<ActionDispatch::Request:0x90ecb7c #env={...}, #fullpath="/subjects", #request_method="GET", #filtered_parameters={"action"=>"index", "controller"=>"subjects"}, #method="GET">>, #_request=#<ActionDispatch::Request:0x90ecb7c #env={...}, #fullpath="/subjects", #request_method="GET", #filtered_parameters={"action"=>"index", "controller"=>"subjects"}, #method="GET">, #_env={...}, #lookup_context=#<ActionView::LookupContext:0x90ec4c4 #details_key=nil, #details={:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]}, #skip_default_locale=false, #frozen_formats=false, #view_paths=[/root/projects/traitly/app/views, /usr/local/rvm/gems/ruby-1.9.2-p136#traitly/gems/devise-1.1.7/app/views]>, #_action_name="index", #_response_body=nil, #_config={}, #current_user=nil>, "action_dispatch.request.content_type"=>nil, "action_dispatch.request.request_parameters"=>{}, "rack.request.query_string"=>"", "rack.request.query_hash"=>{}, "action_dispatch.request.query_parameters"=>{}, "action_dispatch.request.parameters"=>{"action"=>"index", "controller"=>"subjects"}, "action_dispatch.request.formats"=>[t

You're using Rails 3, which uses JavaScript to issue delete requests. Because the request isn't set up properly, your log is showing Started POST instead of the correct Started DELETE.
The request will also not include the required CSRF data, and as of Rails 3.0.4 the session is silently reset instead of throwing an ActionController::InvalidAuthenticityToken error. This is why you suspect the authentication issue lies with Devise, but it is actually being triggered within Rails itself.
To fix this include the following in your layout:
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
Also ensure you have an updated rails.js (which contains the JavaScript code used for delete requests). The Rails 3.0.4 upgrade notes explain the issue in more detail.
If you're using the jquery rails.js replacement, you can get the updated version from here.

Related

ActiveAdmin error 401 Can no longer log in with working credentials. Using rails 5.2

I created an ActiveAdmin user and I can no longer log on using any of my previous ActiveAdmin users nor can I create a new one. When I try, I get a 401 error. I have tried multiple times to manipulate the devise initializer and the model to no avail.
Using rails 5.2.1,activeadmin 1.3.1, activeadmin_addons 1.6.0, cancancan 2.2.0
active_admin_role 0.2.1
Processing by ActiveAdmin::Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEpX4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>"hodari#hiddengeniusproject.org", "password"=>"[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
AdminUser Load (1.1ms) SELECT "admin_users".* FROM "admin_users" WHERE (lower(email) = 'hodari#hiddengeniusproject.org') ORDER BY "admin_users"."id" ASC LIMIT $1 [["LIMIT", 1]]
Completed 401 Unauthorized in 149ms (ActiveRecord: 1.9ms)
Processing by ActiveAdmin::Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEp X4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>" ", "password"=>"
[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
Rendering /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/shared/_links.erb (1.6ms)
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out (51.6ms)
Completed 200 OK in 838ms (Views: 836.8ms | ActiveRecord: 0.0ms)
Here is my adminuser model
class AdminUser < ApplicationRecord
role_based_authorizable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable
attr_accessor :login
has_many :classrooms
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
where(conditions).where(["lower(email) = :value", { :value => login
}]).first
end
end
and here is my devise.rb
Devise.setup do |config|
config.secret_key = ENV['devise_secret_key'] if Rails.env.production?
config.mailer_sender = 'Devise Omniauth
config.mailer = 'Devise::Mailer'
config.parent_mailer = 'ActionMailer::Base'
config.authentication_keys = [:login]
config.reset_password_keys = [:login]
config.strip_whitespace_keys = [:email, :username ]
config.params_authenticatable = true
config.http_authenticatable = false
config.paranoid = true
config.skip_session_storage = [:http_auth]
config.clean_up_csrf_token_on_authentication = true
config.reload_routes = true
config.stretches = Rails.env.test? ? 1 : 11
config.allow_unconfirmed_access_for = 364.days
config.confirm_within = 365.daysconfig.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 6..128
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
config.unlock_strategy = :both
config.reset_password_within = 6.hours
Rails.application.config.app_middleware.use OmniAuth::Builder do
config.omniauth :google_oauth2,
Figaro.env.google_client_id,
Figaro.env.google_client_secret
#google_oauth2_options
{
scope: 'email, calendar',
prompt: 'select_account',
image_aspect_ratio: 'original',
name: 'google',
access_type: 'offline',
provider_ignores_state: true
}
end
end
I'm am not sure what else to include, I am still learning.
thank you
I just went back into my git repository to the last known working version and reset to there. Not sure what the problem was but my app is working again.

Reset password email is not sent by Devise

Rails 3.2.13, Ruby 1.9.3
My Devise controller is working fine sending emails, with one exception: sending the reset password instructions email.
When I click on the "Forgot your password?" link, I get the message:
You will receive an email with your password reset instructions in a few minutes.
But, I do not receive the email. Following is the relevant dump from the log file:
Started GET "/password/new.user" for 174.xx.xxx.xx at 2013-04-29 01:28:48 +0000
Processing by Devise::PasswordsController#new as
BlogPost Load (0.5ms) SELECT `blog_posts`.* FROM `blog_posts`
Rendered devise/_links.erb (1.0ms)
Rendered devise/passwords/new.html.erb within layouts/application (23.1ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (2.5ms)
Rendered layouts/_promo_bar.html.erb (0.9ms)
Rendered layouts/_footer.html.erb (2.6ms)
Completed 200 OK in 54ms (Views: 51.2ms | ActiveRecord: 0.5ms)
Started POST "/password" for 174.xx.xxx.xx at 2013-04-29 01:30:19 +0000
Processing by Devise::PasswordsController#create as HTML
Parameters: {"utf8"=>"✓", "user"=>{"email"=>"emailaddress#outlook.com"}, "commit"=>"Send me reset password instructions"}
BlogPost Load (137.8ms) SELECT `blog_posts`.* FROM `blog_posts`
User Load (82.4ms) SELECT `users`.* FROM `users` WHERE `users`.`email` = 'emailaddress#outlook.com' LIMIT 1
User Load (14.8ms) SELECT `users`.* FROM `users` WHERE `users`.`reset_password_token` = 'NysDaribCpgNySc5Nmog' LIMIT 1
(0.2ms) BEGIN
(99.0ms) UPDATE `users` SET `reset_password_token` = 'NysDaribCpgNySc5Nmog', `reset_password_sent_at` = '2013-04-29 01:30:19', `updated_at` = '2013-04-29 01:30:19' WHERE `users`.`id` = 113
(60.6ms) COMMIT
Rendered devise/mailer/reset_password_instructions.html.erb (1.3ms)
Rendered devise/mailer/reset_password_instructions.text.erb (1.5ms)
Sent mail to emailaddress#outlook.com (133ms)
Date: Mon, 29 Apr 2013 01:30:21 +0000
To: emailaddress#outlook.com
Message-ID: <517dcd2db584b_71bc6778701193#testsite-test.mail>
Subject: testsite Account Reset password instructions
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_517dcd2d93927_71bc677870116dc";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_517dcd2d93927_71bc677870116dc
Date: Mon, 29 Apr 2013 01:30:21 +0000
Mime-Version: 1.0
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <517dcd2d9bfb9_71bc677870117a2#testsite-test.mail>
Hello emailaddress#outlook.com!
A Request to change the password for this account has been received. If this is you, and you still want to change the password, you can do so by clicking on the link below.
Change my password
If you didn't request this, please ignore this email.
----==_mimepart_517dcd2d93927_71bc677870116dc
Date: Mon, 29 Apr 2013 01:30:21 +0000
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <517dcd2db365a_71bc677870118da#testsite-test.mail>
<p>Hello emailaddress#outlook.com!</p>
<p>A Request to change the password for this account has been received. If this is you, and you still want to change the password, you can do so by clicking on the link below.</p>
<p>Change my password</p>
<p>If you didn't request this, please ignore this email.</p>
----==_mimepart_517dcd2d93927_71bc677870116dc--
Redirected to http://test.testsitethefuture.com/login
Completed 302 Found in 2520ms (ActiveRecord: 0.0ms)
Started GET "/login" for 174.xx.xxx.xx at 2013-04-29 01:30:22 +0000
Processing by Devise::SessionsController#new as HTML
BlogPost Load (3.0ms) SELECT `blog_posts`.* FROM `blog_posts`
Rendered devise/_links.erb (0.8ms)
Rendered devise/sessions/new.html.erb within layouts/application (7.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (2.2ms)
Rendered layouts/_promo_bar.html.erb (1.2ms)
Rendered layouts/_footer.html.erb (2.6ms)
Completed 200 OK in 49ms (Views: 35.9ms | ActiveRecord: 3.0ms)
Any ideas of what I should be looking for?
environments/test.rb
Myapp::Application.configure do
config.cache_classes = false
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
config.whiny_nils = true
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.active_record.mass_assignment_sanitizer = :strict
config.active_support.deprecation = :stderr
config.action_mailer.default_url_options = {:host => 'myapp.com'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "myapp.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: 'Admin#myapp.com',
password: 'xxxxxxxxxxx'
}
end
Check the SMTP Mailer settings in your config file, from log it is showing that mail is sending correctly but it is not delivered, because of SMTP settings problem.
Correct the smtp settings and check the mailer from console
Ex:-
Notification.forgot_password("sample#test.com").deliver
Having the line ActionMailer::Base.delivery_method = :smtp in config/environment.rb overrides ActionMailer::Base.delivery_method = :test in config/environments/test.rb.
So, add that line, ActionMailer::Base.delivery_method = :smtp' from config/environment.rb and place it in config/environments/test.rb. That allows you to place
ActionMailer::Base.delivery_method = :test in config/environments/test.rb.
Note: You must restart your server for these changes to take effect.
In config/environment.rb:
# Configuration for using SendGrid on Heroku
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => 'app[my app number]#heroku.com',
:password => '[something super secret]',
:domain => '[let's get this party started!.com]',
:enable_starttls_auto => true
}
ActionMailer::Base.delivery_method = :smtp
Worked for me.

C# client HttpWebRequest on a rails application and reuse a session

I have a rails 3 application running on windows and apache server.
As I have to use NTLM I use the sspi auth module of apache.
As the auth module don't work well with IE (each request results in 401 and another request) we setup the rails application that we only use the authentication on one url /login inside apache.
The rails application has a before_filter :authenticate.
If we don't have a valid login we redirect (http 302) to the login controller, authenticate and redirect back to the original url (request.env['REQUEST_URI]).
On a normal browser login it works perfect. The web browser login any url, gets redirected to authenticate and redirect back to the target url.
Now I have a client plugin writte as a C# project. There I have to make some web request calls to retrieve some json data.
If I make a simple GET request I manage the client to work:
CookieContainer cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.AllowAutoRedirect = true;
request.CookieContainer = cookies;
if (isWindowAuthentication)
request.Credentials = CredentialCache.DefaultNetworkCredentials;
Which results in apache access.log like this:
192.168.14.9 - - [02/Jun/2012:11:26:15 +0200] "POST /ror/ioi/start HTTP/1.1" 302 123
192.168.14.9 - - [02/Jun/2012:11:26:16 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 401 401
192.168.14.9 - - [02/Jun/2012:11:26:16 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 401 401
192.168.14.9 - rausch [02/Jun/2012:11:26:16 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 302 94
But the redirect won't work if I have to post data (like upload a document which I want to do).
So my approach was to make a request, store the session information and send them with the POST.
CookieContainer cookieContainer = new CookieContainer();
WebHeaderCollection headerCollection = new WebHeaderCollection();
if (Common.WindowAuthentication)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Common.PortalUrl + Common.IoiStart);
request.Method = WebRequestMethods.Http.Post;
request.AllowAutoRedirect = true;
request.CookieContainer = cookieContainer;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
for (int i = 0; i < response.Headers.Count; i++)
{
headerCollection.Add(response.Headers.AllKeys[i], response.Headers.Get(i));
}
response.Close();
}
LogWriter.LogError("second request");
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.AllowAutoRedirect = false;
httpWebRequest2.CookieContainer = cookieContainer;
for (int i = 0; i < headerCollection.Count; i++)
{
string key = headerCollection.GetKey(i);
if (key == "Set-Cookie")
{
key = "Cookie";
}
else
{
continue;
}
string value = headerCollection.Get(i);
httpWebRequest2.Headers.Add(key, value);
}
httpWebRequest2.ServicePoint.Expect100Continue = false;
httpWebRequest2.Accept = "*/*";
This ends in this (access.log):
192.168.14.9 - - [02/Jun/2012:11:51:22 +0200] "POST /ror/ioi/start HTTP/1.1" 302 123
192.168.14.9 - - [02/Jun/2012:11:51:22 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 401 401
192.168.14.9 - - [02/Jun/2012:11:51:22 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 401 401
192.168.14.9 - rausch [02/Jun/2012:11:51:22 +0200] "GET /ror/login?ror_referer=%2Fror%2Fioi%2Fstart HTTP/1.1" 302 94
192.168.14.9 - - [02/Jun/2012:11:51:22 +0200] "GET /ror/ioi/start HTTP/1.1" 200 27
192.168.14.9 - - [02/Jun/2012:11:51:22 +0200] "POST /ror/ioi/upload HTTP/1.1" 302 124
For the /ioi/upload request I disallow redirection.
Inspecting the rails settings (some code in application controller) I get this:
request: /ror/ioi/start
#<ActionDispatch::Request:0x4114458 #env={"SERVER_SOFTWARE"=>"thin 1.2.11 codename Bat-Shit Crazy", "SERVER_NAME"=>"thorx64", "rack.input"=>#<StringIO:0x41eaeb0>, "rack.version"=>[1, 0], "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>false, "rack.multiprocess"=>false, "rack.run_once"=>false, "REQUEST_METHOD"=>"POST", "REQUEST_PATH"=>"/ror/ioi/start", "PATH_INFO"=>"/ioi/start", "REQUEST_URI"=>"/ror/ioi/start", "HTTP_VERSION"=>"HTTP/1.1", "HTTP_HOST"=>"thorx64", "HTTP_MAX_FORWARDS"=>"10", "HTTP_X_FORWARDED_FOR"=>"192.168.14.9", "HTTP_X_FORWARDED_HOST"=>"thorx64", "HTTP_X_FORWARDED_SERVER"=>"thorx64", "HTTP_CONNECTION"=>"Keep-Alive", "GATEWAY_INTERFACE"=>"CGI/1.2", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "rack.url_scheme"=>"http", "SCRIPT_NAME"=>"/ror", "REMOTE_ADDR"=>"127.0.0.1", "async.callback"=>#<Method: Thin::Connection#post_process>, "async.close"=>#<EventMachine::DefaultDeferrable:0x41ea700>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.secret_token"=>"a1ef5e037607d12742a40a0793de973a5e68605ccf087ad1baedaee6d811687b82a0671b94da2c4a9af2b481a5346585649e83d2f56f2838a4aca8eedbfc93b7", "action_dispatch.show_exceptions"=>true, "action_dispatch.remote_ip"=>127.0.0.1, "rack.session"=>{}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :id=>nil}, "rack.request.form_input"=>#<StringIO:0x41eaeb0>, "rack.request.form_hash"=>{}, "rack.request.form_vars"=>"", "action_dispatch.request.path_parameters"=>{:controller=>"ioi", :action=>"start"}, "action_controller.instance"=>#<IoiController:0x4114548 #action_has_layout=true, #view_context_class=nil, #_headers={"Content-Type"=>"text/html"}, #_status=200, #_response=#<ActionDispatch::Response:0x4114440 #writer=#<Proc:0x41143b0#D:/Informer/ruby/lib/ruby/gems/1.9.1/gems/actionpack-3.0.10/lib/action_dispatch/http/response.rb:43 (lambda)>, #block=nil, #length=0, #header={}, #status=200, #body=[], #cookie=[], #sending_file=false, #blank=false, #cache_control={}, #etag=nil, #request=#<ActionDispatch::Request:0x4114458 ...>>, #_request=#<ActionDispatch::Request:0x4114458 ...>, #_env={...}, #lookup_context=#<ActionView::LookupContext:0x4113390 #details_key=nil, #details={:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :flv, :file, :image, :auto, :sourcefile, :sourceimage, :sourceauto, :legacy, :edit], :locale=>[:de, :de]}, #skip_default_locale=false, #frozen_formats=false, #view_paths=[d:/Informer/company/latest/ror/app/views, d:/Informer/company/latest/ror/vendor/plugins/will_paginate/app/views, d:/Informer/company/latest/ror/vendor/plugins/usesguid/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_tree/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_solr/app/views]>, #_action_name="start", #_response_body=nil, #_config={}, #_params={"controller"=>"ioi", "action"=>"start"}>, "action_dispatch.request.request_parameters"=>{}, "rack.request.query_string"=>"", "rack.request.query_hash"=>{}, "action_dispatch.request.query_parameters"=>{}, "action_dispatch.request.parameters"=>{"controller"=>"ioi", "action"=>"start"}, "action_dispatch.request.formats"=>[text/html], "rack.session.record"=>#<ActiveRecord::SessionStore::Session id: nil, session_id: "c068a38edeb9bfa71aa5bf7885af35cd", client_ip: nil, username: nil, data: nil, created_at: nil, updated_at: nil>, "action_dispatch.request.flash_hash"=>nil}, #request_method="POST", #filtered_parameters={"controller"=>"ioi", "action"=>"start"}, #method="POST", #fullpath="/ror/ioi/start">
HTTP_VERSION => HTTP/1.1
HTTP_HOST => thorx64
HTTP_MAX_FORWARDS => 10
HTTP_X_FORWARDED_FOR => 192.168.14.9
HTTP_X_FORWARDED_HOST => thorx64
HTTP_X_FORWARDED_SERVER => thorx64
HTTP_CONNECTION => Keep-Alive
i am a user?: false
session:
request: /ror/login?ror_referer=%2Fror%2Fioi%2Fstart
request: /ror/ioi/start
#<ActionDispatch::Request:0x41eda00 #env={"SERVER_SOFTWARE"=>"thin 1.2.11 codename Bat-Shit Crazy", "SERVER_NAME"=>"thorx64", "rack.input"=>#<StringIO:0x3e6f4a8>, "rack.version"=>[1, 0], "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>false, "rack.multiprocess"=>false, "rack.run_once"=>false, "REQUEST_METHOD"=>"GET", "REQUEST_PATH"=>"/ror/ioi/start", "PATH_INFO"=>"/ioi/start", "REQUEST_URI"=>"/ror/ioi/start", "HTTP_VERSION"=>"HTTP/1.1", "HTTP_HOST"=>"thorx64", "HTTP_COOKIE"=>"_ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch", "HTTP_MAX_FORWARDS"=>"10", "HTTP_X_FORWARDED_FOR"=>"192.168.14.9", "HTTP_X_FORWARDED_HOST"=>"thorx64", "HTTP_X_FORWARDED_SERVER"=>"thorx64", "HTTP_CONNECTION"=>"Keep-Alive", "GATEWAY_INTERFACE"=>"CGI/1.2", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "rack.url_scheme"=>"http", "SCRIPT_NAME"=>"/ror", "REMOTE_ADDR"=>"127.0.0.1", "async.callback"=>#<Method: Thin::Connection#post_process>, "async.close"=>#<EventMachine::DefaultDeferrable:0x3e6e668>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.secret_token"=>"a1ef5e037607d12742a40a0793de973a5e68605ccf087ad1baedaee6d811687b82a0671b94da2c4a9af2b481a5346585649e83d2f56f2838a4aca8eedbfc93b7", "action_dispatch.show_exceptions"=>true, "action_dispatch.remote_ip"=>127.0.0.1, "rack.session"=>{"current_user_id"=>49}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :id=>"bfd6cdcd0650812edeb58c9a915e3948"}, "rack.request.cookie_string"=>"_ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch", "rack.request.cookie_hash"=>{"_ror_session"=>"bfd6cdcd0650812edeb58c9a915e3948", "user"=>"rausch"}, "rack.session.record"=>#<ActiveRecord::SessionStore::Session id: 712, session_id: "bfd6cdcd0650812edeb58c9a915e3948", client_ip: "192.168.14.9", username: "rausch", data: "BAh7BkkiFGN1cnJlbnRfdXNlcl9pZAY6BkVGaTY=\n", created_at: "2012-06-02 11:51:22", updated_at: "2012-06-02 11:51:22">, "action_dispatch.request.path_parameters"=>{:controller=>"ioi", :action=>"start"}, "action_controller.instance"=>#<IoiController:0x41edac0 #action_has_layout=true, #view_context_class=nil, #_headers={"Content-Type"=>"text/html"}, #_status=200, #_response=#<ActionDispatch::Response:0x41ed9e8 #writer=#<Proc:0x41ed8e0#D:/Informer/ruby/lib/ruby/gems/1.9.1/gems/actionpack-3.0.10/lib/action_dispatch/http/response.rb:43 (lambda)>, #block=nil, #length=0, #header={}, #status=200, #body=[], #cookie=[], #sending_file=false, #blank=false, #cache_control={}, #etag=nil, #request=#<ActionDispatch::Request:0x41eda00 ...>>, #_request=#<ActionDispatch::Request:0x41eda00 ...>, #_env={...}, #lookup_context=#<ActionView::LookupContext:0x41ecc80 #details_key=nil, #details={:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :flv, :file, :image, :auto, :sourcefile, :sourceimage, :sourceauto, :legacy, :edit], :locale=>[:de, :de]}, #skip_default_locale=false, #frozen_formats=false, #view_paths=[d:/Informer/company/latest/ror/app/views, d:/Informer/company/latest/ror/vendor/plugins/will_paginate/app/views, d:/Informer/company/latest/ror/vendor/plugins/usesguid/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_tree/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_solr/app/views]>, #_action_name="start", #_response_body=nil, #_config={}, #_params={"controller"=>"ioi", "action"=>"start"}>, "action_dispatch.request.content_type"=>nil, "action_dispatch.request.request_parameters"=>{}, "rack.request.query_string"=>"", "rack.request.query_hash"=>{}, "action_dispatch.request.query_parameters"=>{}, "action_dispatch.request.parameters"=>{"controller"=>"ioi", "action"=>"start"}, "action_dispatch.request.formats"=>[text/html]}, #request_method="GET", #filtered_parameters={"controller"=>"ioi", "action"=>"start"}, #method="GET", #fullpath="/ror/ioi/start">
HTTP_VERSION => HTTP/1.1
HTTP_HOST => thorx64
HTTP_COOKIE => _ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch
HTTP_MAX_FORWARDS => 10
HTTP_X_FORWARDED_FOR => 192.168.14.9
HTTP_X_FORWARDED_HOST => thorx64
HTTP_X_FORWARDED_SERVER => thorx64
HTTP_CONNECTION => Keep-Alive
i am a user?: true
session: bfd6cdcd0650812edeb58c9a915e3948
request: /ror/ioi/upload
#<ActionDispatch::Request:0x4235610 #env={"SERVER_SOFTWARE"=>"thin 1.2.11 codename Bat-Shit Crazy", "SERVER_NAME"=>"thorx64", "rack.input"=>#<StringIO:0x3b754f0>, "rack.version"=>[1, 0], "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>false, "rack.multiprocess"=>false, "rack.run_once"=>false, "REQUEST_METHOD"=>"POST", "REQUEST_PATH"=>"/ror/ioi/upload", "PATH_INFO"=>"/ioi/upload", "REQUEST_URI"=>"/ror/ioi/upload", "HTTP_VERSION"=>"HTTP/1.1", "HTTP_HOST"=>"thorx64", "HTTP_ACCEPT"=>"*/*", "HTTP_COOKIE"=>"_ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch", "HTTP_MAX_FORWARDS"=>"10", "HTTP_X_FORWARDED_FOR"=>"192.168.14.9", "HTTP_X_FORWARDED_HOST"=>"thorx64", "HTTP_X_FORWARDED_SERVER"=>"thorx64", "HTTP_CONNECTION"=>"Keep-Alive", "CONTENT_LENGTH"=>"100058", "CONTENT_TYPE"=>"multipart/form-data; boundary=----------------------------8cf0ecd4ab52a04", "GATEWAY_INTERFACE"=>"CGI/1.2", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "rack.url_scheme"=>"http", "SCRIPT_NAME"=>"/ror", "REMOTE_ADDR"=>"127.0.0.1", "async.callback"=>#<Method: Thin::Connection#post_process>, "async.close"=>#<EventMachine::DefaultDeferrable:0x3b749f8>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.secret_token"=>"a1ef5e037607d12742a40a0793de973a5e68605ccf087ad1baedaee6d811687b82a0671b94da2c4a9af2b481a5346585649e83d2f56f2838a4aca8eedbfc93b7", "action_dispatch.show_exceptions"=>true, "action_dispatch.remote_ip"=>127.0.0.1, "rack.session"=>{}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :id=>nil}, "rack.request.cookie_string"=>"_ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch", "rack.request.cookie_hash"=>{"_ror_session"=>"bfd6cdcd0650812edeb58c9a915e3948", "user"=>"rausch"}, "rack.session.record"=>#<ActiveRecord::SessionStore::Session id: 712, session_id: "bfd6cdcd0650812edeb58c9a915e3948", client_ip: "192.168.14.9", username: "rausch", data: "BAh7BkkiFGN1cnJlbnRfdXNlcl9pZAY6BkVGaTY=\n", created_at: "2012-06-02 11:51:22", updated_at: "2012-06-02 11:51:22">, "action_dispatch.request.content_type"=>multipart/form-data, "rack.request.form_input"=>#<StringIO:0x3b754f0>, "rack.request.form_hash"=>{"document"=>{"id"=>"20", "guid"=>"{ed20ec73-94bc-413b-b3a9-07b44ab6e624}"}, "file"=>{"name"=>"Dokument1.docx", "source"=>{:filename=>"Dokument1_201262114815.docx", :type=>"application/octet-stream", :name=>"file[source]", :tempfile=>#<File:C:/Windows/Temp/RackMultipart20120602-10036-1bfrx5x>, :head=>"Content-Disposition: form-data; name=\"file[source]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.docx\"\r\n Content-Type: application/octet-stream\r\n"}, "pdf"=>{:filename=>"Dokument1_201262114815.pdf", :type=>"application/octet-stream", :name=>"file[pdf]", :tempfile=>#<File:C:/Windows/Temp/RackMultipart20120602-10036-1uzoxvw>, :head=>"Content-Disposition: form-data; name=\"file[pdf]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.pdf\"\r\n Content-Type: application/octet-stream\r\n"}}}, "action_dispatch.request.path_parameters"=>{:controller=>"ioi", :action=>"upload"}, "action_controller.instance"=>#<IoiController:0x4235748 #action_has_layout=true, #view_context_class=nil, #_headers={"Content-Type"=>"text/html"}, #_status=200, #_response=#<ActionDispatch::Response:0x42355f8 #writer=#<Proc:0x4235550#D:/Informer/ruby/lib/ruby/gems/1.9.1/gems/actionpack-3.0.10/lib/action_dispatch/http/response.rb:43 (lambda)>, #block=nil, #length=0, #header={}, #status=200, #body=[], #cookie=[], #sending_file=false, #blank=false, #cache_control={}, #etag=nil, #request=#<ActionDispatch::Request:0x4235610 ...>>, #_request=#<ActionDispatch::Request:0x4235610 ...>, #_env={...}, #lookup_context=#<ActionView::LookupContext:0x42343c8 #details_key=nil, #details={:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :flv, :file, :image, :auto, :sourcefile, :sourceimage, :sourceauto, :legacy, :edit], :locale=>[:de, :de]}, #skip_default_locale=false, #frozen_formats=false, #view_paths=[d:/Informer/company/latest/ror/app/views, d:/Informer/company/latest/ror/vendor/plugins/will_paginate/app/views, d:/Informer/company/latest/ror/vendor/plugins/usesguid/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_tree/app/views, d:/Informer/company/latest/ror/vendor/plugins/acts_as_solr/app/views]>, #_action_name="upload", #_response_body=nil, #_config={}, #_params={"document"=>{"id"=>"20", "guid"=>"{ed20ec73-94bc-413b-b3a9-07b44ab6e624}"}, "file"=>{"name"=>"Dokument1.docx", "source"=>#<ActionDispatch::Http::UploadedFile:0x41ced28 #original_filename="Dokument1_201262114815.docx", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[source]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.docx\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1bfrx5x>>, "pdf"=>#<ActionDispatch::Http::UploadedFile:0x41cec68 #original_filename="Dokument1_201262114815.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[pdf]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.pdf\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1uzoxvw>>}, "controller"=>"ioi", "action"=>"upload"}>, "action_dispatch.request.request_parameters"=>{"document"=>{"id"=>"20", "guid"=>"{ed20ec73-94bc-413b-b3a9-07b44ab6e624}"}, "file"=>{"name"=>"Dokument1.docx", "source"=>#<ActionDispatch::Http::UploadedFile:0x41ced28 #original_filename="Dokument1_201262114815.docx", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[source]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.docx\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1bfrx5x>>, "pdf"=>#<ActionDispatch::Http::UploadedFile:0x41cec68 #original_filename="Dokument1_201262114815.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[pdf]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.pdf\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1uzoxvw>>}}, "rack.request.query_string"=>"", "rack.request.query_hash"=>{}, "action_dispatch.request.query_parameters"=>{}, "action_dispatch.request.parameters"=>{"document"=>{"id"=>"20", "guid"=>"{ed20ec73-94bc-413b-b3a9-07b44ab6e624}"}, "file"=>{"name"=>"Dokument1.docx", "source"=>#<ActionDispatch::Http::UploadedFile:0x41ced28 #original_filename="Dokument1_201262114815.docx", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[source]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.docx\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1bfrx5x>>, "pdf"=>#<ActionDispatch::Http::UploadedFile:0x41cec68 #original_filename="Dokument1_201262114815.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[pdf]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.pdf\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1uzoxvw>>}, "controller"=>"ioi", "action"=>"upload"}, "action_dispatch.request.accepts"=>[*/*], "action_dispatch.request.formats"=>[*/*], "action_dispatch.request.flash_hash"=>nil}, #request_method="POST", #filtered_parameters={"document"=>{"id"=>"20", "guid"=>"{ed20ec73-94bc-413b-b3a9-07b44ab6e624}"}, "file"=>{"name"=>"Dokument1.docx", "source"=>#<ActionDispatch::Http::UploadedFile:0x41ced28 #original_filename="Dokument1_201262114815.docx", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[source]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.docx\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1bfrx5x>>, "pdf"=>#<ActionDispatch::Http::UploadedFile:0x41cec68 #original_filename="Dokument1_201262114815.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file[pdf]\"; filename=\"C:\\Users\\rausch\\AppData\\Roaming\\TQsoft\\InformerOfficeExtension\\Temp\\Dokument1_201262114815.pdf\"\r\n Content-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Windows/Temp/RackMultipart20120602-10036-1uzoxvw>>}, "controller"=>"ioi", "action"=>"upload"}, #method="POST", #fullpath="/ror/ioi/upload">
HTTP_VERSION => HTTP/1.1
HTTP_HOST => thorx64
HTTP_ACCEPT => */*
HTTP_COOKIE => _ror_session=bfd6cdcd0650812edeb58c9a915e3948; user=rausch
HTTP_MAX_FORWARDS => 10
HTTP_X_FORWARDED_FOR => 192.168.14.9
HTTP_X_FORWARDED_HOST => thorx64
HTTP_X_FORWARDED_SERVER => thorx64
HTTP_CONNECTION => Keep-Alive
i am a user?: false
session:
So my question to rails professionals:
So I don't understand why all header data for the ioi/upload request are valid but the rails application do not reuse the session (as you can see the last two line above user => false and session id is empty).
So is there something I have to send again (modify C# client) or is this a rails issue? I think last, but I don't know what to change at the rails part to make the reuse of the session.
Got it!
It was a issue in rails.
This little thing caused the issue :)
application_controller.rb
Line 2: protect_from_forgery
This is to protect the application. Creates a security token to use on every ajax request.
<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="sGeq9l+HfYotFbfuZFHqtmrMGBygMGZc2SjnmEwp9eo="/>
So the solution in this case as I don't have this in the c# client:
Create a handshake to get the security token and post this as well (to much work for me :))
What I did: Add a skip filter in the target controller: skip_before_filter :verify_authenticity_token
Conclusion:
It works to store cookies and headers like I did and send them with the following requests to "simulate" the session.

Rails 3 :mobile MIME type throws 406 error after attempt to load content with JavaScript

I'm following Railscast #199 to allow my web app to be viewed in a mobile browser. It works great, except when I try to access information in a tabbed interface using UJS in the mobile version. Clicking on the tabs works in the web app, but on the mobile side I get a 406 error. (I tried this after setting the User Agent as iPhone in Safari. I also tested on iOS Simulator and my iPhone. Neither time loaded anything.)
Below is some code for one of the tabs. Can anyone can help me target what is going on? Here is my code.
Here's the profile_about action in profiles_controller.rb:
def profile_about
#profile = Profile.find(params[:id])
respond_to do |format|
format.js { render :layout => nil }
end
end
In my profiles/show.mobile.erb (this is the exact same code as in profiles/show.html.erb):
<div id="tabs">
<ul id="infoContainer">
<li><%= link_to "Cred", profile_cred_profile_path, :class=> 'active', :remote => true %></li>
<li><%= link_to "About", profile_about_profile_path, :class=> 'inactive', :remote => true %></li>
</ul>
<div id="tabs-1">
<%= render :partial => 'profile_cred' %>
</div>
</div><!-- end tabs -->
(NOTE: I have a file for profiles/_profile_about.html.erb and profiles/_profile_about.mobile.erb.)
Here is my profiles/profile_about.js.erb:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");
My Heroku logs showing the 406:
2012-03-08T03:02:55+00:00 app[web.1]: Started GET "/profiles/1/profile_about" for 98.218.231.113 at 2012-03-08 03:02:55 +0000
2012-03-08T03:02:55+00:00 heroku[router]: GET myapp.com/profiles/1/profile_about dyno=web.1 queue=0 wait=0ms service=14ms status=406 bytes=1
2012-03-08T03:02:55+00:00 app[web.1]: Processing by ProfilesController#profile_about as JS
2012-03-08T03:02:55+00:00 app[web.1]: Parameters: {"id"=>"1"}
2012-03-08T03:02:55+00:00 app[web.1]: Completed 406 Not Acceptable in 3ms
2012-03-08T03:02:55+00:00 heroku[nginx]: 98.218.231.113 - - [08/Mar/2012:03:02:55 +0000] "GET /profiles/1/profile_about HTTP/1.1" 406 1 "http://myapp.com/profiles/1" "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3" myapp.com
From running tail -f logs/development.log:
Started GET "/profiles/1/profile_about" for 127.0.0.1 at Wed Mar 07 22:35:36 -0500 2012
Processing by ProfilesController#profile_about as JS
Parameters: {"id"=>"1"}
PK and serial sequence (5.4ms) SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
pg_depend dep,
pg_namespace name,
pg_constraint cons
WHERE seq.oid = dep.objid
AND seq.relkind = 'S'
AND attr.attrelid = dep.refobjid
AND attr.attnum = dep.refobjsubid
AND attr.attrelid = cons.conrelid
AND attr.attnum = cons.conkey[1]
AND cons.contype = 'p'
AND dep.refobjid = '"goals_profiles"'::regclass
PK and custom sequence (2.5ms) SELECT attr.attname,
CASE
WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
substr(split_part(def.adsrc, '''', 2),
strpos(split_part(def.adsrc, '''', 2), '.')+1)
ELSE split_part(def.adsrc, '''', 2)
END
FROM pg_class t
JOIN pg_attribute attr ON (t.oid = attrelid)
JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
WHERE t.oid = '"goals_profiles"'::regclass
AND cons.contype = 'p'
AND def.adsrc ~* 'nextval'
Profile Load (1.3ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = '1' LIMIT 1
Completed 406 Not Acceptable in 30ms
There's a few bugs in your code, maybe it's just stackoverflow formatting here but the inner quotes should be ' instead of " , like this:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");
And this line is casuing your error:
format.mobile.js {render :layout => nil}
This is impossible because the request can only have a single mime type. "mobile" or "js", not both. If you are requesting the "profile_about" action from javascript, then you must respond back to it with js. "format.mobile" should only be used to render a "profile_about.mobile" template.
Hopefully that's at least a step in the right direction for you.
Probably don't fully answer your question but I was having the 406 status problem, because I've been deploying my app to Phonegap!
It basically happened because the request type didn't match any of the Rails responders in the action.
it was like:
respond_to do |format|
format.json {
render( json: (#parishes) )
}
end
Since I only used it to responde to JSON I changed and it now works:
render( json:(#parishes) )
A more complete way to deal with this is to figure exactly what responder is being asked for that request, or default to something you know to work
Turns out this was due to a lacking check for an xhr request in the prepare_for_mobile method. I found the answer in another question. So the below prepare_for_mobile method allows the JS to work:
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
request.format = :mobile if mobile_device? && !request.xhr?
end

Callback URL works locally but not on remotely on Heroku

I have a callback URL that is outlined in the MessagesController like so:
def message_create
message = Message.new( :message => params[:PAYLOAD],
:recipient => params[:DEST_ADDR],
:api_message_id => params[:MSG_ID],
:from => params[:SRC_ADDR],
:api_timestamp => params[:DATETIME],
:network => params[:NETWORK],
:origin => "sms")
message.save
redirect_to message
end
When I run my app locally this callback URL works just fine:
http://localhost:3000/message_create?PAYLOAD=asdfasdf&DEST_ADDR=234523&MSG_ID=23452345&SRC_ADDR=24345234234&DATETIME=20110915130534&NETWORK=blah
However, when I push the app to heroku and enter the same callback URL:
http://myapp.heroku.com/message_create?PAYLOAD=asdfasdf&DEST_ADDR=234523&MSG_ID=23452345&SRC_ADDR=24345234234&DATETIME=20110915130534&NETWORK=blah
It just gives me an error. I've looked into whether it's due to the:
before_filter :authenticate
line in my controller but even when that's commented out the data just won't submit to the remote DB. Your thoughts and experience are very-much appreciated.
UPDATE:
Just worked out how to access the full logs on Heroku. Looks like the issue might be to do with integer's not being large enough in Heroku by default:
2011-09-15T13:25:28+00:00 app[web.1]: Started GET "/message_create?PAYLOAD=asdfasdf&DEST_ADDR=234523&MSG_ID=23452345&SRC_ADDR=24345234234&DATETIME=20110915130534&NETWORK=blah" for 80.46.10.63 at 2011-09-15 06:25:28 -0700
2011-09-15T13:25:28+00:00 app[web.1]: Processing by MessagesController#message_create as HTML
2011-09-15T13:25:28+00:00 app[web.1]: Parameters: {"PAYLOAD"=>"asdfasdf", "DEST_ADDR"=>"234523", "MSG_ID"=>"23452345", "SRC_ADDR"=>"24345234234", "DATETIME"=>"20110915130534", "NETWORK"=>"blah"}
2011-09-15T13:25:28+00:00 app[web.1]: Completed in 10ms
2011-09-15T13:25:28+00:00 app[web.1]:
2011-09-15T13:25:28+00:00 app[web.1]: ActiveRecord::StatementInvalid (PGError: ERROR: integer out of range
2011-09-15T13:25:28+00:00 app[web.1]: : INSERT INTO "messages" ("message", "created_at", "updated_at", "recipient", "api_message_id", "from", "origin", "timestamps", "user_id", "status", "api_timestamp", "network", "group_id") VALUES ('asdfasdf', '2011-09-15 13:25:28.650894', '2011-09-15 13:25:28.650894', 234523, 23452345, 24345234234, 'sms', NULL, NULL, NULL, '2011-09-15 13:05:34.000000', 'blah', NULL) RETURNING "id"):
2011-09-15T13:25:28+00:00 app[web.1]: app/controllers/messages_controller.rb:48:in `message_create'
2011-09-15T13:25:28+00:00 app[web.1]:
2011-09-15T13:25:28+00:00 app[web.1]:
2011-09-15T13:25:28+00:00 heroku[router]: GET www.myherokuapp.com/message_create dyno=web.1 queue=0 wait=0ms service=14ms status=500 bytes=728
2011-09-15T13:25:28+00:00 heroku[nginx]: 80.46.10.63 - - [15/Sep/2011:06:25:28 -0700] "GET /message_create?PAYLOAD=asdfasdf&DEST_ADDR=234523&MSG_ID=23452345&SRC_ADDR=24345234234&DATETIME=20110915130534&NETWORK=blah HTTP/1.1" 500 728 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.12 Safari/535.2" www.myherokuapp.com
Yes it seems like a data type error, what data types did you set for your fields on the messages table migration?