Boomerange Boomerange - 3 years ago 101
Ruby Question

How to find user by email and if not, redirect him to register page

I use Omniauth and Omniauth-facebook gems and I want to click on button, if user is found, then sign him in. If not, redirect him to register page.

So far I use just classic login/register:

user.rb:

def self.from_omniauth(auth, role)
user = User.where(:provider => auth.provider, :uid => auth.uid).first

if user
return user
else
registered_user = User.where(:email => auth.info.email).first

if registered_user
registered_user.provider = auth.provider
return registered_user
else
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|

if (role == "1")
user.add_role :sportsman
elsif (role == "2")
user.add_role :donor
end

user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
end


omniauth_callbacks_controller.rb:

def facebook
role = cookies[:role]
# signin = cookies[:signin]
user = User.from_omniauth(request.env["omniauth.auth"], role)

if user.persisted?
flash.notice = "Signed by Facebooku"
sign_in_and_redirect user
else
flash.notice = "Error, try again."
session["devise.user_attributes"] = user.attributes
redirect_to new_user_registration_url
end
end


This code works, but if user is not registered, it will register him. But I sign roles when user register himself.

Thanks for help.

Answer Source

So I used simple params to get where the user come from:

<script type="text/javascript">
    document.cookie = "login=0"
</script>

This code is in views/devise/registrations/new.html.erb (and in views/devise/sessions/new.html.erb) and it is a JavaScript. It tells me if user went from login page (sessions folder - login=1) or from registration page (registrations folder - login=0). Then I use this code to determinate if user is from login page AND if he is not registered yet. If both conditions are true, then he is redirected to register page. It is so simple that I am embarrassed...

def facebook
    hash  = request.env["omniauth.auth"]
    info  = hash.info
    email = info["email"]

    user = User.find_by_email(email)

    login = cookies[:login]

    if (user == nil && login == "1")
      redirect_to new_user_registration_path
    else
      role = cookies[:role]
      user = User.from_omniauth(request.env["omniauth.auth"], role)
      if user.persisted?
        flash.notice = "Logged in by Facebook"
        sign_in_and_redirect user
      else
        flash.notice = "Error, try again."
        session["devise.user_attributes"] = user.attributes
        redirect_to new_user_registration_url
      end
    end
  end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download