Admin authentication

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 .

and 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!

application controller

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

sessions controller

class SessionsController < ApplicationController

def create user = User.authenticate(params[:username], params[:password]) if user session[:user_id] = redirect_to venues_path, :notice => "Logged in!" else = "Invalid username or password" render "new" end end def destroy session[:user_id] = nil redirect_to venues_path, :notice => "Logged out!" end end

-------------Problems Reply------------

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

Category:ruby on rails Views:0 Time:2011-05-29

Related post

Copyright (C), All Rights Reserved.

processed in 0.084 (s). 11 q(s)