Skip to content

How to restrict a view of a DIFFERENT page to a logged in admin user #50

@verachell

Description

@verachell

Noob here - I've got rails with Trestle and trestle-auth working on a simple tryout app. This question is similar to #21 but a little bit different.

FYI - In case this has any bearing on it, I'm not using the devise gem, I'm doing my authentication via the trestle-auth authenticator.

Here I'm asking how would I restrict a different view (i.e. one that's not in the Admin area / Trestle backend) to a logged in admin user. Here's what I tried so far. I went along the lines the solution of the other issue linked to above. I have a model called label with a labels_controller. I want the view for the labels page to be only visible to a logged in admin user. NOTE: I may be using 'admin' loosely - I mean a Trestle logged-in user.

I did this:

# app/controllers/labels_controller.rb
class LabelsController < ApplicationController
before_action :checkadmin
  def index
  @labels = Label.all
  end
  
  private
  
  def checkadmin
unless current_user.admin?
 redirect_to "/404.html"
 end
  end
  
end

The above resulted in an error
undefined local variable or method `current_user' for #<LabelsController...

I tried changing the line in checkadmin to unless Trestle.current_user.admin? but then it gave me this error
NoMethodError (undefined method `current_user' for Trestle:Module):

Next trying to use current_user in the Trestle admin area

After putting everything back to normal with my labels controller, I tried changing just the labels view in the Trestle admin area simply to test my usage of current_user.admin? (even though I don't actually want to do that in my real app)

# app/admin/labels_admin.rb
Trestle.resource(:labels) do
  menu do
    item :labels, icon: "fa fa-star"
  end

  # Customize the table columns shown on the index view.
  
  if current_user.admin?
   table do
     column :title
     column :created_at, align: :center
     actions
   end
   end

end

When I load the admin page for labels it says:
undefined local variable or method `current_user' for #<Trestle::Resource::Builder:0x00007f88a17fb4e0 @admin=LabelsAdmin, @ controller=LabelsAdmin::AdminController>

I think I must be making some basic error somewhere when testing if the current logged in user is an admin. Would anyone please be willing to point me in the right direction?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions