Redirected to http://localhost:3000/session/new - iphone

So I have a rails app 2.x app that works fine via the web, but when trying to perform a POST I keep getting "Redirected to http://localhost:3000/session/new Filter chain halted as [:require_user] rendered_or_redirected.". In my iPhone app, I can create a new session and sign-in via my iPhone app, but cannot POST to say the POSTS_Controller.
I have this in my code
Posts_Controller
before_filter :require_user, :only => [:create, :update, :destroy]
Application_Controller
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
include AuthenticatedSystem
include Geokit::Geocoders
helper :all # include all helpers, all the time
#session :session_key => '_cwa_session_id'
#filter_parameter_logging :password
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => 'eejj7eded74769099999944a729b4f'
#filter_parameter_logging(:password)
before_filter :login_from_cookie
before_filter :find_user_interests
before_filter :find_user_posts
protected
def find_user_interests
#user_interests = cur_user ? cur_user.interesting_posts : []
logger.debug "User interests hash: #{current_user.inspect}"
end
def find_user_posts
#user_posts = cur_user ? cur_user.posts : []
end
def cur_user
User.find(session[:user_id]) if session[:user_id]
end
def require_user
unless cur_user
flash[:error] = "You must be logged in to do that."
redirect_to '/session/new'
return false
end
end
geocode_ip_address
def geokit
#location = session[:geo_location]
end
end
I have been working on this for 2 months and cannot figure out the issue. In my iPhone app I am using ObjectiveResource. I am sending over json and have "Mime::Type.register_alias "application/json", :json" set up on the rails side.

I am not a rails developer, but the before filter for require_user is unable to pass the cur_user test in that is cannot find :user_id in the session hash. Are you sure that you have a session that persists when using the iPhone? Are you using devise for authentication? Just for kicks, does it work if you manually pass the user_id as params?

Related

Ruby on Rails Tutorial NoMethodError in Users#index

I'm reading Michael Hartl's great "The Ruby on Rails Tutorial". And I faced a problem that wasn't described in the book.
I push a submit button on a Sign up page with blank fields, then, as it expected, the mistakes messages like these appears:
Name can't be blank
Email can't be blank
Email is invalid
Password can't be blank
But the URL changes from http://[::1]:3000/signup to http://[::1]:3000/users
Then I push the Chrome's refresh button and get redirecting to exactly http://[::1]:3000/users URL.
I understand that the pushing the submit button directs to .../users URL. How to change this route to the right one (still http://[::1]:3000/signup)?
Here's my users_controller.rb file
class UsersController < ApplicationController
before_action :logged_in_user, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.where(activated: true).paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
redirect_to root_url and return unless #user.activated?
#microposts = #user.microposts.paginate(page: params[:page])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'users/new', status: :unprocessable_entity
end
end
def edit
#user = User.find(params[:id])
end
end
Here's my routes.rb file
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
default_url_options :host => "example.com"
resources :users
end
Thanks in advance!

rails calling get request twice

I am using rails 5 and I am trying to save an object to my db with some parameters on a get request. But for some reason my object is getting saved twice.
here is my code in controller
class ParticipantCardController < ApplicationController
before_action :authenticate_user!
before_action :authenticate_current_user_profile
def participate
# byebug
params.permit(:event_id, :_method, :authenticity_token)
event_id=params[:event_id].to_i
byebug
#new_participant = ParticipantCard.new
#new_participant.user=current_user
#new_participant.event_id=event_id
#new_participant.name=" "
#new_participant.description=" "
#new_participant.save
# end
# flash[:error] = #new_participant.errors.messages
end
this is code calls the insert sql query twice, like so:
terminal query

#<ActionDispatch::Request::Session:0xa8fde64 not yet loaded> error while accessing the rails application from ipad

I am getting "ActionDispatch::Request::Session:0xa8fde64 not yet loaded" when try to access the session in application controller.
It gives error when try to access rails application on iphone.
It's working properly on desktops browsers.
After login it goes to index page and I added before filter "admin_authenticate" for index page.
my sessioncontrollerfile
class AdminSessionController < ApplicationController
def create
if (params[:username] == 'abc#abc.com' and params[:password] == '12345')
session[:admin_id] = 1
redirect_to admins_path, :notice => "Login Ok"
end
end
my applicationcontoller file
class ApplicationController < ActionController::Base
def admin_authenticate
if session[:admin_id] == 1
return true
else
redirect_to "/login"
end
end
end
Not able to access session value set in AdminSessionController inside admin_authenticate method of application controller.
This issue is solved.
By default cookies are disabled in iOS-7, if you enable the cookies you can access the sessions.

Setting env when using rspec to test omniauth callbacks

I'm having a strange problem when trying to set a callback for Facebook Authentication via Omniauth. In my controller (simplified to just the code necessary to show the error) I have:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
raise env.inspect
# auth_hash = env["omniauth.auth"]
end
end
this works in production mode, showing me the hash. However in test mode env is set to nil.
I have the following set in my spec_helper.rb file
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:facebook, {"credentials" => {
"token" => "foo-token"
}
})
and my spec looks like this:
require 'spec_helper'
describe Users::OmniauthCallbacksController do
describe "Facebook" do
before(:each) do
request.env["devise.mapping"] = Devise.mappings[:user]
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end
it "should be a redirect" do
get :facebook
response.should redirect_to(root_path)
end
end
end
Can anyone enlighten me on what I need to do to have env not be nil when running my tests?
I use the following in my spec_helper.rb :
RACK_ENV = ENV['ENVIRONMENT'] ||= 'test'
I don't use Rails or Devise though so YMMV. I've also seen various threads saying that someone had to do this before their requires to get it to work.

500 error when calling webservice through rhosync/rhodes

I am trying to call a web service in rhosync application.rb, I see a 500 error response in rhosync console .. and 'server returned an error' in BB simulator .. :(
Some info about my setup -
I have created a rhodes app that connects to a rhosync app when user enters user name and password and clicks on "login". I am calling this webservice through "authenticate" method of application.rb of the rhosync application ..
def authenticate(username,password,session)
Rho::AsyncHttp.get(:url => 'http://mywebserviceURL',:callback => (url_for :action => :httpget_callback),:callback_param => "" )
end
UPDATE
Instead of http:async, I tried consuming a soap based webservice and it worked just fine .. here is code if anyone cones here in search of a sample.. in application.rb of rhosync app
require "soap/rpc/driver"
class Application < Rhosync::Base
class << self
def authenticate(username,password,session)
driver = SOAP::RPC::Driver.new('http://webserviceurl')
driver.add_method('authenticate', 'username', 'password')
ret=driver.authenticate(username,password)
if ret=="Success" then
true
else
false
end
end
end
Application.initializer(ROOT_PATH)
You can typically find the problem if you crank up your log. Edit rhoconfig.txt in your app
set these properties -
# Rhodes runtime properties
MinSeverity = 1
LogToOutput = 1
LogCategories = *
ExcludeLogCategories =
then try again and watch the terminal output. Feel free to post the log back and I'll take a look.
You also might want to echo out puts the mywebserviceURL if you're using that as a variable, I trust you just changed that for the post here. Can you access the webservice if you hit it with a browser?
require "soap/rpc/driver"
class Application < Rhosync::Base
class << self
def authenticate(username,password,session)
driver = SOAP::RPC::Driver.new('http://webserviceurl')
driver.add_method('authenticate', 'username', 'password')
ret=driver.authenticate(username,password)
if ret=="Success" then
true
else
false
end
end
end
Application.initializer(ROOT_PATH)
in this what is done in add_method and authenticate method and where it to be written.