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

routes

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] = 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

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

I think you should look into using CanCan, a gem written by Ryan Bate.

https://github.com/ryanb/cancan

You'll learn how to set abilities and can do things like:

if can? :manage, :all
# Admin stuff
else
# Non-admin stuff
end

You'll also be able to check abilities on specific models.

if can? :manage, Project
# bla bla
end

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

Related post

Copyright (C) dskims.com, All Rights Reserved.

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