开发者

Admin authentication

开发者 https://www.devze.com 2023-03-08 22:43 出处:网络
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.

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 d开发者_Python百科isplays 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消