I have been following Ryan Bates railcasts to get an admin authentication system to display certain options if the currently logged in user is an admin or not.
The def admin? method works but only if I set it to true or false in the code. True displays all the options and false hides them.
I have tried:
current_user[:username] == 'dave' which works until the user changes to someone else then it gives a no method error .
session[:username] == 'dave' gives no errors but sets the admin? method to false on all users including 'dave'.
What should I be putting into my admin? method? Ideally I would like it to see if both the username and passsword matches then returns true.
Any help would be much appreciated!
class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details helper_method :admin? protected def authorize unless admin? flash[:error] = "not authorized!" redirect_to venues_path false end end def admin? true #false end end
Go::Application.routes.draw do get "log_in" => "sessions#new", :as => "log_in" get "log_out" => "sessions#destroy", :as => "log_out" get "sign_up" => "users#new", :as => "sign_up" root :to => "users#new" resources :sessions resources :users end
class SessionsController < ApplicationController
def create user = User.authenticate(params[:username], params[:password]) if user session[:user_id] = user.id redirect_to venues_path, :notice => "Logged in!" else flash.now.alert = "Invalid username or password" render "new" end end def destroy session[:user_id] = nil redirect_to venues_path, :notice => "Logged out!" end end
I think you should look into using CanCan, a gem written by Ryan Bate.
You'll learn how to set abilities and can do things like:
if can? :manage, :all
# Admin stuff
# Non-admin stuff
You'll also be able to check abilities on specific models.
if can? :manage, Project
# bla bla