Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't debug work in this situation?

I'm using the gem called omniauth-facebook, with which I succeeded at implementing facebook login auth.

It looks fine but it won't pass data of the whole object to the view. It just says nil.

It should show an array of things when using 'debug' or 'inspect'. It shows the content of session[:name] fine somehow.

Controller

class SessionsController < ApplicationController
    def create
        @auth = request.env["omniauth.auth"]
        session[:oauth_token] = @auth.credentials.token
        session[:username] = @auth.extra.raw_info.username

        session[:name] = @auth.extra.raw_info.name
        redirect_to bookd_url, :notice => "Signed in!"
    end
end

View

<% if signed_in? %>
    <%= @auth.inspect %>
    <%= debug @auth %><br />
    <%= session[:name] %>
<% end %>

Output HTML

nil
--- 
...
John
like image 547
HUSTEN Avatar asked Dec 14 '25 02:12

HUSTEN


1 Answers

Your create controller action does a redirect. After the redirect, the process will start from scratch, and @auth will no longer be defined. If you render the view at this point, @auth will be nil. This is your problem.

You need to think about what you are trying to do here. You set an @auth variable from the authentication details in the initial request. You then use this to set some data in the session, which records who is logged in for example. Then, on the next page, where the user is logged in, you want to look at @auth. This doesn't really make sense: once you've authenticated a user, all you need to care about is remembering which user is currently logged in. You don't need to store details about HOW they logged in, and in fact you probably shouldn't.

You should instead be doing something like this:

#in ApplicationController, protected section
protected

def current_user
  if @current_user
    return @current_user
  elsif session[:username]
    @current_user = User.find_by_username(session[:username])
    return @current_user
  end
end

This will allow you to write current_user in your controller and view code, to access the user who authenticated, originally, which is the whole reason for logging someone in and keeping them logged in.

like image 130
Max Williams Avatar answered Dec 16 '25 19:12

Max Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!