find_by_* method is not returning the object - ruby-on-rails-3

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.

Related

Bcrypt with two different user models on rails 5.2

I have two migration tables: parents and teachers. And I use Bcrypt for registration. I can't figure out what I should do with log in and sessions_controller (sessions helper). I can register new user and when user registers he can only see Sign Out link in navbar. However, I can not sign out user, I am not sure how I define the methods in sessions controller and session helper. Maybe somebody can help me with this?
I can not find information about bcrypt with different user models - is this thing not popular or is this so easy and I am just stupid and do not understand a thing??
class SessionsController < ApplicationController
include SessionsHelper
def new
end
def create
teacher = Teacher.find_by(email: params[:session][:email])
parent = Parent.find_by(email: params[:session][:email])
if teacher && teacher.authenticate(params[:session][:password])
log_in teacher
redirect_to documents_path
flash[:notice] = "Welcome!"
elsif parent && parent.authenticate(params[:session][:password])
log_in parent
redirect_to root_path
flash[:notice] = "Welcome!"
else
flash[:alert] = "Please log in again!"
render 'new'
end
end
def destroy
if log_out parent
redirect_to root_path
elsif log_out teacher
redirect_to root_path
end
end
end
And here is my sessions helper:
module SessionsHelper
# Logs in the given user.
def log_in(parent)
session[:parent_id] = parent.id
end
def log_in(teacher)
session[:teacher_id] = teacher.id
end
# Returns the current logged-in user (if any).
def current_teacher
#current_teacher ||= Teacher.find_by(id: session[:teacher_id])
end
def current_parent
#current_parent ||= Parent.find_by(id: session[:parent_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?(teacher)
!current_teacher.nil?
end
def logged_in?(parent)
!current_parent.nil?
end
def log_out(teacher)
session.delete(:teacher_id)
#current_teacher = nil
end
def log_out(parent)
session.delete(:parent_id)
#current_parent = nil
end
end
I don't know the details of the your application, but I can explain the general case.
First of all, controller which has log in function is not have to be named sessions_controller, name is anything OK.
And Bcrypt is basically only a library for encrypting passwords. Main process is checking the password entered by user is valid or not without decrypting. There is no clear answer how to implement controller logic.
Apparently, user is divided into two types, Teacher and Parent, and probably each has different functions. So essentially, I want to divide the two login processes into separate controllers or actions. Because each login process is not the same one.
But Teacher and Parent will log in with the same URL if user have to login from the same page due to the UI restriction. If you are in such circumstances, implementing in the same controller & action will be appropriate.
After all, it depends on how to design your application. So your code is not always wrong.
However, look at your code, Teacher or Parent is judged only by e-mail, it is doubtful whether this is a proper approach. I have not seen many websites where users with different privileges log in from the same page.
I think that it is basically divide the login page depending on Teacher or Parent. If you divide the login page, example is as follows.
class TeachersController < ApplicationController
include SessionsHelper
def login
end
def login_action
teacher = Teacher.find_by(email: params[:teacher][:email])
if teacher && teacher.authenticate(params[:teacher][:password])
log_in teacher
flash[:notice] = 'Welcome!'
redirect_to root_path
else
flash[:notice] = 'Invalid log in information!'
redirect_to action: :login
end
end
def logout
teacher = Teacher.find(session[:teacher_id])
log_out teacher
redirect_to root_path
end
end
class ParentsController < ApplicationController
include SessionsHelper
def login
end
def login_action
parent = Parent.find_by(email: params[:parent][:email])
if parent && parent.authenticate(params[:parent][:password])
log_in parent
flash[:notice] = 'Welcome!'
redirect_to root_path
else
flash[:notice] = 'Invalid log in information!'
redirect_to action: :login
end
end
def logout
parent = Parent.find(session[:parent_id])
log_out parent
redirect_to root_path
end
end
Although this is not the main issue, did you write sessions_helper in the helpers directory?
Usually, helper is used to implement for view logic, so if you want to share method in controller, use ActiveSupport::Concern in the concerns directory.

Ruby on Rails security regarding session cookies

In my app, I have a User model and it has a rememberable_token column. When creating a user, a random secure string is saved in a before_create filter to act as a secure token for the user:
user.rememberable_token = SecureRandom.urlsafe_base64
In the session controller, it creates a permanent cookie with the value of that token so that the user doesn't get logged out when closing the browser and only gets logged out when they log out via the logout action:
Session controller:
def create
.
.
cookies.permanent.signed[:permanent_user_session] = user.rememberable_token
end
def logout
cookies.delete :permanent_user_session
redirect_to root_url
end
The cookie is used in the application controller to determine if there is a current user as well as in a before_filter that is used in a few controllers to determine if a user is logged in and authorized.
Application controller:
def current_user
#current_user ||= User.find_by_rememberable_token(cookies.signed[:permanent_user_session]) if cookies.signed[:permanent_user_session]
end
def authorize
unless User.find_by_rememberable_token(cookies.signed[:permanent_user_session])
render :action => 'login'
end
end
The question is if this is safe or if it is prone to session hijacking? If it is prone to hijacking, would it be alright if in the session#logout method it created a new rememberable_token for the user just before deleting the existing cookie (but not creating a new cookie with that value)?
Thank you.
If someone is stealing the cookie, this code:
def current_user
#current_user ||= User.find_by_rememberable_token(cookies.signed[:permanent_user_session]) if cookies.signed[:permanent_user_session]
end
will still work. On your logout method you have to delete the token from user table and recreated at login.
Basically, what you are doing at create should be done at each login and reverted at each logout.
I'd probably do this:
On session create:
random_string = SecureRandom.urlsafe_base64
cookies.permanent.signed[:permanent_user_session] = random_string
user.rememberable_token = Digest::MD5.hexdigest(random_string) && user.save
On session destroy:
cookies.delete :permanent_user_session
In the application controller:
def current_user
#current_user ||= User.find_by_rememberable_token(Digest::MD5.hexdigest(cookies.signed[:permanent_user_session])) if cookies.signed[:permanent_user_session]
end
def authorize
unless #current_user
render :action => 'login'
end
end
This way, you're storing a hash of the token and a new one is regenerated for every new login (and expired on every log out). Rails takes care of CSRF but long-term sessions are probably not a good idea.

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.

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 ;)

Rails redirect issue - Hartl's Rails Tutorial 10.2.3

I'm a complete noob working through Michael Hartl's (awesome) Rails tutorials, and have an issue with the friendly redirect in Ch.10.2.3. The purpose is to try to store the location, redirect to the sign in page, then redirect back to the original intended destination when sign-in is complete. My problem is that it simply renders the standard user profile page after signing in/creating a session, rather than redirecting.
I have this in the sessions_controller:
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
redirect_back_or user
end
end
And this in sessions_helper:
def authenticate
deny_access unless signed_in?
end
def deny_access
store_location
redirect_to signin_path, :notice => "Please sign in to access this page."
end
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
clear_return_to
end
private
def store_location
session[:return_to] = request.fullpath
end
def clear_return_to
session[:return_to] = nil
end
I'm sure I've yet again made a stupid, simple mistake but I can't find it.. help?
The code is available here: https://github.com/railstutorial
Consider making a new git branch (or new project) for yourself that uses just this repository's code. Then you will have a working local version for comparison when things go wrong.