How to access current user with Devise - ruby-on-rails

I am using devise as well as ldap in my application to authenticate users. I have got the users model set up as well as devise. I can properly sign in and sign out users but I cannot access any information for the devise built in helper; current_user.
I want the main page of the application to show the current users name at the top of the page. I have created the column in the users table called display_name.
This is the code that I want to work:
<% if user_signed_in? %>
<div> <%= current_user.display_name %> </div>
<% end %>
When I used byebug and try to access the current user it returns nil.
Does anyone have any suggestions on how I can access the current users information?
Update
I tried using: <% if signed_in %>
but i still get the same error: undefined method `display_name' for nil:NilClass

devise documentation says:
If your devise model is something other than User, replace "_user"
with "_yourmodel".
Is your model User? If not, you need to use the appropriate helper method.

Which LDAP gem are you using? devise_ldap_authenticatable ?
You will need to define an instance variable #current_user in your ApplicationController, and set it to the correct user record based on the LDAP account which authenticated.
Then, during sign-in you need to set the value of #current_user, and during sign-out you need to set it to nil.
So for sign-in and sign-out you would have to implement this in Session#create and Session#destroy

Related

I want to change the page view based on whether the user is an admin

In rails, I have a model for users which has a flag for admins (yes, no). If the logged_in user is an admin, I'd like to be able to show different elements of the page using erb.
I'm currently doing this with logg in users vs non logged in users using this code
<% if current_user %>
But how would I specify if current_user is admin in the erb?
Or, is erb the best place to do this since it is exposed to the browser? If not, any suggestions for other ways to accomplish this in the model or controller?
I'm not using Devise for the user authentication currently.
When you say they have a flag, does that mean they have an attribute called admin?
If so, any model with a boolean in rails, you can check with:
<% if current_user.admin? %>
If there is another way of determining whether the user is an admin or not, you'll need to add an admin? method to the user class, which you can use to determine their status in the view.
You can use user is_admin column name in views.
<% if current_user.is_admin? %>

Rails issues with authentication

I am building my first app using rails and i am struggling to give an account to each user. Its a simple app where a user creates a post and saves it. this post can be seen on index page. Until now we are ok. when i sign out, i register a new user and i log in. when i go to the index page, i can see what other user has saved. I want to have a private index page for each user where no one can see what users are saving in their app. I am using Gem 'Device" to authenticate my app, but i don't know how to make private their account? any ideas?
You have implemented authentication. Now you need to build authorization.
You have to define what data can be accessed by user.
Take a look at:
CanCanCan
With devise authentication technique, after logging in the user you can write a clean piece of code to render the posts of the logged in user. You can use session data to do it. the current_user helper method returns the model class relating to the signed in user. With devise, it ensures after authentication that, it has the helper methods ready to be used. So, the error with no such user with that id can be avoided.
#web/controller/post_controller.rb
before_filter :authenticate_user!
def list
#posts = current_user.posts
end
And then, use #posts in the list view to render the posts of the logged in user only.
<% #posts.each do |post| do%>
<%= post.content %>
<% end %>

Accessing Params in Rails 3.2

I am working through the RailsApps Stripe tutorial.
When a new subscriber is created through a devise registration controller they are then directed to their content page through a content controller. I want to use their name and email address created upon registration on their content page. But I can't seem to bring the params into the content controller.
I put#user = User.find(params[:id]) into the content_controller but I get the error "Couldn't find User without an ID".
On the error page it lists under Request Info > rack session: "warden.user.user.key"=>["User", [2],
So does that mean that ID of User #2 is being passed to the content_controller but that I can't access it?
I put#user = User.find(params[:id]) into the content_controller but I
get the error "Couldn't find User without an ID".
This error means that params[:id] = nil, i.e., you are not passing id in the params hash when redirecting the user to content page.
Possible Solutions:
With Devise you get a helper method called current_user which returns an instance of currently logged in user. So, you could directly use current_user to access the attributes of currently logged in user. For example:
To access name and email fields of currently logged in user, all you need to do is
current_user.name
current_user.email
In routes.rb, pass the id of the currently logged in user via the route of content page as below:
## Add :id dynamic segment to your content page route
get "content/:id", :to => "contents#action_name", :as => "content_page"
Since, I don't have the route details, you would need to modify the above route as per your requirement.
Next, when redirecting the user to content page after sign up just pass the currently logged in user as below in ApplicationController method named after_sign_up_path_for (You need to override this Devise method if you want to redirect the user to a different route than the default root path):
def after_sign_up_path_for(resource)
content_page_path(resource) ## Provide the path and pass resource to it
end
With Devise, you can access the currently logged in user via the current_user helper in your controller.
See documentation: https://github.com/plataformatec/devise#controller-filters-and-helpers

Helper method for url?

I have multiple fields for social networking websites where users can enter their username and it would link to their twitter, facebook, myspace account etc. My problem is how can I have it so when a user enters their username I can link to their account.
Here's what I have and I know this is probably not correct. In my profile index.html
<%= link_to twitter_url %>
profile helper method
def twitter_url
return(self.url= "http://twitter.com/#{profile.twitter}/account")
end
In my profile controller
include ProfilesHelper
The actual field in database is called
twitter_link
How can I get the just the user username then on my part which will do the rest link to their twitter, facebook etc account page?
How is that method supposed to know what the profile object is without you passing it in?
I'm imagining there being a #profile variable defined in your controller. In the view, you would have this:
<%= link_to twitter_url %>
And in the helper, this:
def twitter_url
"http://twitter.com/#{#profile.twitter_link}/account"
end
Note here that you don't need to set self.url or have an explicit return. This is because the method will automatically return a String which is what link_to takes.
If you want this method to be in a helper that's available in just your ProfileController, then why not put it inside ProfileHelper so that it's automatically included just by being related by name?

'Cannot redirect to nil' error after adding a field to devise registration view

After adding this line to the devise/registrations/new.html.haml file (view):
%div
= f.label :account_type
%br/
= f.select(:account_type, [["Usertype1","usertype1"],["Usertype2","usertype2"]], {:selected => nil, :prompt => 'Pick One'})
I get the following error after clicking on the confirmation link in the confirmation e-mail:
ActionController::ActionControllerError in Devise::ConfirmationsController#show
Cannot redirect to nil!
It only happens if I select Usertype2 upon registration. I also made the account_type attr_accessible. The account_type seems to be getting assigned (I checked in the rails console) and the development logs don't have any further information.
I think this is the line in the devise confirmations controller where the error is occurring:
respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
Also, the account is being confirmed, but when trying to log in, I get the following:
undefined method `user_url' for #<Devise::SessionsController:0x9d1659c>
which is in the create action of the devise sessions controller.
Any help would be appreciated. Thanks!
John
The two errors you mentioned are one and the same, essentially when you are signing-in successfully Devise is unable to detect where to redirect you. This problem often occurs when you have multiple models or try to setup a custom redirect (post sign in) in the routes file.
Try to define the path in the ApplicationController.
Devise docs say that the after_sign_in_path_for method takes the actual model object (ie: the model being signed-in)
def after_sign_in_path_for(resource)
signed_in_path_for_user
end
Note: You can do the same for several Devise paths / variables (override them). Also for more information on doing this for multiple Devise models in the same app, you can look at this question and it's answer.

Resources