Devise invitable: invite existing user - devise

I am using devise invitable in my application for inviting the users. If the user exists in the database I have to redirect him to signin screen otherwise to the signup screen if he is a new user. Even if I invite the user like:
User.invite!(:email => "jonny#email.com", :name => "Jonny"), the data is getting entered in the database, then the user is always getting redirected to sign in screen. I had written the following for checking the email in invitations controller:
def edit
if User.exists?(:email => params[:email])
redirect_to new_user_session_path
else
redirect_to new_user_registration_path
end
end
Can some help me how I can handle this situation.

For edit it should find a user by id rather than going on to the new_user_session_path. The edit method should contain the following piece of code.
def edit
if User.exists?
#user = User.find(params[:id])
else
redirect_to new_user_registration_path
end
end

Related

find_by_* method is not returning the object

I am trying to set up a simple authentication for my rails application. I have a security_users scaffold and have created some users.
When, I am trying to log in using some of these accounts it seams that the "find_by_*" method is not able to detect the current one.
This is how my session controller looks like (I have comment the password check in purpose in order to debug the issue):
class SessionsController < ApplicationController
def new
end
def create
#security_user = SecurityUser.find_by_email(params[:email])
if #security_user #&& #security_user.authenticate(params[:password])
session[:security_user_id] = #security_user.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render 'new'
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged out!"
end
end
So, when I try to create a session (to log in) I am redirect to the session 'new' template. This is the debug information:
which seems to be all right. Why the following statement could not find the record:
SecurityUser.find_by_email(params[:email])
EDIT:
When I entered the line above in the console it is returning the record:
First off, unless this is a simple exercise in Rails authentication, you should use Devise or AuthLogic at this stage.
Second, are you sure that params[:email] contains the email you are looking for? From your params, it looks to me like you want to use params[:session][:email].
Third, you should move this down into the model. For example:
class SecurityUser < ActiveRecord::Base
def self.authenticate(params)
user = where(email: params[:email]).first
(user && user.password == params[:password]) ? user : false
end
end
And in the controller:
#user = SecurityUser.authenticate params[:session]
session[:user_id] = user.id if #user
Note above that the password is not hashed - you should not save a plain text password - but that's not what this is about.
Also note that now you should use where().first instead of find_by.

Default Route for an admin User (Devise)

Little issue here, I cant seem to route an admin user to the appropriate place. I have setup devise and added the column admin and set it as boolean. I have then updated my user to admin => true and verified this in the console.
When i log into my app a user is routed to one page and the admin user should be routed to another, here is what i have so far
authenticated :current_admin_user do
root :to => 'book#searchbook'
end
authenticated :user do
root :to => 'search#index'
end
root :to => 'main#index'
However when i log in as thew admin user I get routed to 'search#index' as if i was a regular user.. What do i need to do to get the admin user routed to 'book#searchbook'. Ive never had a problem with this before
Any help appreciated
EDIT
ok so after some more research i need to specify the after_sign_in_path for an admin user, so far i have this
def after_sign_in_path_for(resource)
if current_admin_user
searchbook_path
else
root_path
end
end
but still it directs me to the user login page
Thanks
Ok so it seems as if I had quite a bit missing, so if anyone else has had problems like this before here's what i done
In the User model i added
def is_admin?
self.admin == 1
end
and then in my application controller i added these methods
def authenticate_admin_user!
authenticate_user!
unless current_user.admin?
flash[:alert] = "This area is restricted to administrators only."
redirect_to root_path
end
end
def current_admin_user
return nil if user_signed_in? && !current_user.admin?
current_user
end
def after_sign_in_path_for(resource)
if current_user.admin?
searchbook_path
else
root_path
end
end
and then in the controller that was only accessible by the admin user I added before_filter
before_filter :authenticate_admin_user!
Hope this helps anyone else in same situation (and thanks to Jayson Lane)
Turns out he helped me 9 months ago with the same issue...
Just try to implement the below code .. As I used this code in my controller..
def after_sign_in_path_for(resource_or_scope)
if resource_or_scope.is_a?(User)
return root_path
else
return search_path
end
end

Devise + Facebook Omniauth Error on redirect

I am using devise, omniauth & facebook-omniauth for my Rails 3.1 app. After authentication I wanted to redirect the user to the page was viewing. I have used the following code for the same:
def facebook
#user = Spree::User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = "Yipee! You were successfully authorized from your Facebook account!!"
sign_in #user, :event => :authentication
redirect_to request.referrer
end
This gives me the following error only at the time of user creation:
ActionController::ActionControllerError in Spree::OmniauthCallbacksController#facebook
Cannot redirect to nil!
The following times when the user has already been created, no errors are shown during & after log in.
How do you suggest I fix this? Thanks!
you can overwrite the functions for sign in/ sign up path in your application controller:
def after_sign_up_path_for(resource)
credit_path
return request.env['omniauth.origin'] || session[:return_to]
end
def after_sign_in_path_for(resource)
return request.env['omniauth.origin'] || session[:return_to]
end
use sessions to store the current path in the path that you want them to go to: session[:return_to] = request.url #store current location
or you create a method that will always be called once they go to a path and store that location. watch out for a giant loop redirection when you do that though.

How to allow a user to enter a password when deleting an authorization in devise/omniauth

I have a rais 3 app that uses devise and omniauth to allow users to register/login via their twitter account and/or with local login credentials. Everything works fine for registering and logging in. My problem occurs when a user chooses to destroy their twitter authorization without first establishing a local password. If a user destroys their authorizations, then I would like to route them to new_password_path so that they can choose a password for future log-ins.
Here is the controller code:
class AuthenticationsController < ApplicationController
before_filter :authenticate_user!, :except => [:create, :failure]
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication #existing user is logging-in with existing authentication service
flash[:notice] = "Signed in successfully."
set_home_location_cookies(authentication.user, authentication.user.home_lat, authentication.user.home_lng)
sign_in(:user, authentication.user)
redirect_to root_path
elsif current_user #existing user who is already logged-in is creating a new authentication service for future use
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => omniauth['credentials']['token'])
current_user.update_posting_preferences(omniauth['provider'])
flash[:notice] = "Successfully linked to your #{omniauth['provider'].titleize} account."
redirect_to root_path
else #new user is creating a new authentication service and logging in
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in(:user, user)
redirect_to root_path
else
session[:omniauth] = omniauth.except('extra')
session[:user_message] = {:success => false, :message => "userSaveError"}
redirect_to new_user_registration_url
end
end
end
def failure
flash[:alert] = "Could not authorize you from your social service."
redirect_to root_path
end
def destroy
#authentication = current_user.authentications.find(params[:id])
current_user.update_posting_preferences(#authentication.provider)
#authentication.destroy
flash[:notice] = "You have successfully destroyed your link to your #{#authentication.provider.titleize} account."
if current_user.authentications.empty? && current_user.encrypted_password.empty?
sign_out
flash[:alert] = "Alert: Your account does not currently have a password for account authorization. You are in danger of losing your account unless you create a new password by using this form."
redirect_to new_password_path(current_user) and return
else
redirect_back_or(root_path)
end
end
The code results in a "could not find valid mapping for nil" error triggered by my redirect_to new_password_path(current_user) and return command
I would greatly appreciate some help figuring out this problem.
Thanks!
OK. I'll admit it. I implemented the authentications controller from a tutorial without studying devise routing to learn what was going on behind the scenes. Last night I reviewed the docs and figured out my problem. What is funny is that the above routine did work on an older version of devise but does not work on devise 1.5.3.
In the destroy action I sign-out the current_user then I try to route to the new_password_path sending in "current_user" as a parameter. Not surprisingly, at that point "current_user" has been nulled out. So, I get the, "could not find a valid mapping for nil" error. Here is my easy fix:
def destroy
#authentication = current_user.authentications.find(params[:id])
user = current_user
current_user.update_posting_preferences(#authentication.provider)
#authentication.destroy
flash[:notice] = "You have successfully destroyed your link to your #{#authentication.provider.titleize} account."
if current_user.authentications.empty? && current_user.encrypted_password.empty?
sign_out
flash[:alert] = "Alert: Your account does not currently have a password for account authorization. You are in danger of losing your account unless you create a new password by using this form."
redirect_to new_password_path(user) and return
else
redirect_back_or(root_path)
end
end

devise+omniauth devise helper like current_user,user_signed_in? not working

I am using devise and create login with Facebook using omniauth, but having problem of lost the devise helper methods access like current_user and user_signed_in? methods are not working.
EDIT
AuthenticationController
def create
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) || User.create_with_omniauth(omniauth)
session[:user_id] = user.id
redirect_to dashboard_path(user.id), :notice => "Signed in!"
end
redirect_to USercontroller dashboard method
UserController
before_filter :logged_in
def dashboard
#user = User.find(params[:id])
#comment = Comment.new
#comments = #user.comments.all.paginate(:page => params[:page], :per_page => 5)
end
so here control should go to dashboard method after checking logged_in method in ApplicationController
logged_in method in ApplicationController
Application Controller
def logged_in
if user_signed_in?
return true
else
redirect_to root_path
flash[:message] = "please login"
end
end
when I logged in using facebook following code generated at console
Started GET "/users/52/dashboard" for 127.0.0.1 at Thu Mar 29 12:51:55 +0530 2012
Processing by UsersController#dashboard as HTML
Parameters: {"id"=>"52"}
Redirected to http://localhost:3000/
Filter chain halted as :logged_in rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)
in the above code control is render from logged_in method to root_path but it shold render dashboard_path
So I am guessing User_signed_in? helper is not working I also use current_user in stead of that generate same error
As I see, user_signed_in? is working, but returns false, as for Devise user is not logged in. To fix this, just replace the session id storing with Devise sign_in method in your controller action:
def create
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) || User.create_with_omniauth(omniauth)
sign_in(:user, user)
# actually if you really really need that id in the session, you can leave this line too :)
session[:user_id] = user.id
redirect_to dashboard_path(user.id), :notice => "Signed in!"
end
After creating the user account via Facebook, how do you sign in the user?
You should still be using devise helpers like sign_in_and_redirect. Something like:
user = User.build_from_omniauth(omniauth)
if user.save
sign_in_and_redirect(:user, user)
end
Then you should be able to use helpers like current_user and user_signed_in? (which just check if current_user is not nil).
Taking a look at your edit, my answer is still valid. What you need to do is use sign_in_and_redirect(:user, user) instead of just setting the id in the session.
You can easily customize where the user is redirected after sign in with devise.
Another thing, remove this logged_in filter, Devise has a authenticate_user! method that you can use as a before_filter. It will redirect the user to the sign in page, and when they login, it will redirect them to the page they were trying to access.
You're using Devise, so try to take advantage of that, and go read the doc ;)