Ruby on Rails - Can't set cookies in some actions - ruby-on-rails

I'm trying to set in cookies target_path that non authorized user tried to reach and after authorization redirect him to the target. Everything works fine and good, but then I tried to set as target edit_test_path or create_test_path and other methods with POST/PATCH/PUT requests and seems that no cookies are being set. What can be the case?
application.rb - I'm setting cookies here. authenticate_user! calling in almost every controller before_actions
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
helper_method :current_user,
:logged_in?
private
def authenticate_user!
unless current_user
cookies[:target_path] = request.path_info
redirect_to login_path, alert: 'Verify Email or Password'
end
end
def current_user
#current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
def logged_in?
current_user.present?
end
end
sessions_controller.rb - I'm trying to redirect to the target from cookies here
class SessionsController < ApplicationController
def new; end
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
session[:user_id] = user.id
cookies[:target_path] ? (redirect_to cookies[:target_path]) : (redirect_to root_path) # With verb POST cookies don't work
else
flash.now[:alert] = 'Verify Email or Password'
render :new
end
end
def exit
session[:user_id] = nil
redirect_to login_path
end
end

I don't think, you can do this with POST/PUT/PATCH requests. When you are doing redirect_to, rails sends 302 Found reponse with location specified in parameter of redirect_to in your case cookies[:target_path] or root_path.
Browser then understends it should do redirect and sends GET request to URL specified in location header. You cannot nor should try to tell it to do POST/PUT/PATCH requests - these types of requests usually also require some kind of data (eg submitted form) that goes along with the request. You lost all of these data during redirect to login page anyway.
What I am trying to say - use these redirects only for GET requests. It will not work for POST/PUT/PATCH.

Related

OmniAuthGoogleOAuth2 in Rails 4 redirect to original request url after successful login

As per docs I implemented the authentication. Here is my application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
before_action :auth_user
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
private
def auth_user
current_user
if #current_user.nil?
flash[:notice] = "You need to be logged in to access this part of the site"
redirect_to root_path(url: request.url)
end
end
end
And I am using this "Sign In" Link
<%= link_to "Sign in with Google", "/auth/google_oauth2?url=#{#url}", id: "sign_in" %>
The route: get 'auth/:provider/callback', to: 'user_sessions#create'
The controller:
class UserSessionsController < ApplicationController
skip_before_filter :auth_user
def create
url = params[:url]
auth = env["omniauth.auth"]
if auth
user = User.from_omniauth(auth)
session[:user_id] = user.id
flash[:notice] = "Login Sucessful!"
redirect_to url
else
flash[:notice] = "error"
redirect_to root_path
end
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
end
Now when I without a valid session try to go to localhost:3000/privileged I get redirected to the root URL and the login link is this:
http://localhost:3000/auth/google_oauth2?url=http://localhost:3000/privileged
However when I click it, I get a successful login but then an error that I cannot redirect to nil. Why is the parameter dropped? Or is there a better way to redirect the user to the originally requested URL after a successful login in general?
It works when I changed the url parmaeter in the link to ?origin=... and in the controller I can then access it via url = request.env['omniauth.origin']. This makes the redirect_to url statement work

Restrict access in Rails app only for users logged in

I'm learning Rails and I'm trying to restrict access to pages if a user hasn't logged in and to only allow them to view the login and sign up pages.
Currently, my code creates a session when a user logs in and clears it when the user logs out. I've got a Sessions helper so that I can check whether a user is logged in but I'm unsure how to redirect the user throughout the app if he/she's not logged in.
UPDATE:
As I posted the question, I managed to get something to work with a before_filter. Should I use a before_action or before_filter?
Do I need to copy the same method in all my controllers where I want to restrict access?
CODE:
/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to root_url
end
end
/helpers/sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
#current_user = nil
end
end
You can use a before_action. The rails guide has a nice section with an example on that:
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end

Couldn't find User with 'id'=true Omniauth - rails 4

I am implementing omniauth for twitter and I have run into an error "Couldn't find User with 'id'=true" the error is pointing to the application controller current_user metho. Heere is my current_user method:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
and here is my User model:
class User < ActiveRecord::Base
def self.find_or_create_by_auth(auth_data)
user = where(provider: auth_data[:provider], uid: auth_data[:uid]).first_or_create
user.update(name: auth_data[:info][:name])
end
end
and finally the SessionController is below:
class SessionsController < ApplicationController
def create
#user = User.find_or_create_by_auth(request.env["omniauth.auth"])
session[:user_id] = #user
redirect_to products_path, notice: "logged in as "
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: "Goodbye!!"
end
end
When I trying to log in the error pops and i can't get past login to load my index page.
I think your problem should be solved with following modification in User.find_or_create_by_auth method:
def self.find_or_create_by_auth(auth_data)
# all previous code
# you should return user from here
# your current code returned true of false
user
end
Also you should save #user.id in session, not full #user object:
session[:user_id] = #user.id
I finally solved this, the issue was that i had deleted the previous authenticated twitter user in the db and i was trying to authenticate with the same credentials again on the app.
so what i did is create a new twitter app and use different keys to authenticate into my rails App... hoep this explains it thanks

Deep linking problems on my Rails app

EDIT I've provided more detail on my objectives below.
I am having trouble deep linking users to my site after they log in through the landing page using the Omninauth gem.
The most common scenario is this: a user receives an email with a deep link to the site - say www.mysite.com/suggestions/15. We've placed a Facebook login (through Omniauth) on the landing page, (def landing page on the Authorization controller - see below). When a user tries to access any other page without being logged in they are bounced back via the authenticate_user! helper method placed in the relevant controllers. authenticate_user is defined in the Application Controller -see below.
Once they get bounced back they click a "log in with facebook" button on the landing page and we create a session for the user through def authcreate. This works in the classic omniauth way, i.e. a callback from facebook which captures the session token. Now at this point I want to redirect the user to the page they were trying to get to (e.g. www.mysite.com/suggestions/15) but instead they only go through the default page (www.mysite.com/suggestions). This is not a problem when the user is already logged in, but never works when they are logged out.
You can ignore authorize! as that is a separate module (confusing I know) which is concerned with admin rights. Ditto on check_authorization.
I've created a module and placed it into lib/
module RedirectModule
def self.included(controller)
controller.send :helper_method, :redirect_to_target_or_default
end
def redirect_to_target_or_default(default, *args)
redirect_to(session[:return_to] || default, *args)
session[:return_to] = nil
end
def redirect_to_or_default(target, *args)
redirect_to(target || default, *args)
end
private
def store_target_location # Friendly redirect: store URL.
session[:return_to] = request.url
end
end
There is an include in the ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery
check_authorization
include RedirectModule
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
end
end
helper_method :current_user
def authenticate_user!
if !current_user
store_target_location
redirect_to "/"
end
end
I initiate the sessions on the following controller:
class AuthorizationController < ApplicationController
def landingpage
authorize! :auth, :landingpage
if current_user
redirect_to_target_or_default('/suggestions')
else
store_target_location
end
end
def authcreate
authorize! :auth, :authcreate
reset_session
authHash = env["omniauth.auth"]
existingUser = User.where(authHash.slice(:provider, :uid)).first
user = User.from_omniauth(authHash)
session[:user_id] = user.id
redirect_to_target_or_default('/suggestions')
end
def authdestroy
authorize! :auth, :authdestroy
session[:user_id] = nil
redirect_to "/"
end
end
What am I doing wrong?

basic ruby on rails authentication trouble

I am working on a basic authentication system for a rails app. The authentication is verifying account information from Active Directory using a net-ldap class (this part is working fine).
Something seems to be wrong with my session_helper however. Even though ActiveDirectoryUser.authenticate is successful, the signed_in helper always returns false. After signing in, the script redirects to root_path (default_controller's home) and then immediately redirects back to signin_path again-- as a result of the signed_in helper returning false.
See the code below. What am I missing?
Thanks
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
default_controller.rb
class DefaultController < ApplicationController
before_filter :signed_in_user
def home
end
private
def signed_in_user
redirect_to signin_path, notice: "Please sign in." unless signed_in?
end
end
sessions_helper.rb
module SessionsHelper
def sign_in(user)
#current_user = user
end
def current_user
#current_user ||= nil
end
def signed_in?
!#current_user.nil?
end
def sign_out
#current_user = nil
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = ActiveDirectoryUser.authenticate(params[:session][:username],params[:session][:password])
if user.nil?
# authentication failed
flash.now[:error] = 'Invalid email/password combination'
render 'new'
else
# authentication succeeded
sign_in #user
flash[:error] = 'Great success'
redirect_to root_path
end
end
def destroy
sign_out
redirect_to root_path
end
end
You should use session for to persist that kind of data (will be assessable for every request), it's user data. But I highly recommend you to use something like the devise gem that do all that authentication things and more for you. Why reinvent the weel right?
I believe this would work for you.
module SessionsHelper
def sign_in(user)
session[:user_id] = user.id
end
def current_user
ActiveDirectoryUser.find(session[:user_id]) ||= nil
end
def signed_in?
!session[:user_id].nil?
end
def sign_out
session[:user_id] = nil
end
end

Resources