In my earlier posts we have learnt how to do a simple login with Omniauth and denying admin access to pages for non admin users. Today I will be talking about how you can allow only Admins to log into a system. We will be referring to and building up on the code from the posts "Simple Google Authentication using Omniauth & oauth2" and "before_filter in Rails".
Now open up your sessions controller and scroll down to the create action, all the magic we're about to do will be done there. Using the admin? method which we defined in ApplicationController (in "before_filter in Rails") we will check if the google account belongs to one of the admins, if not they would not be loggin in to the system.
def create
auth = request.env["omniauth.auth"]
if admin?
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!"
else
redirect_to root_path, :notice=> "Unauthorized Access"
end
end
and that's it! After modifying the create action, you have implemented login exclusively for admin users.
Now open up your sessions controller and scroll down to the create action, all the magic we're about to do will be done there. Using the admin? method which we defined in ApplicationController (in "before_filter in Rails") we will check if the google account belongs to one of the admins, if not they would not be loggin in to the system.
def create
auth = request.env["omniauth.auth"]
if admin?
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!"
else
redirect_to root_path, :notice=> "Unauthorized Access"
end
end
and that's it! After modifying the create action, you have implemented login exclusively for admin users.
No comments:
Post a Comment