且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扶手:用Authlogic基本身份验证

更新时间:2023-12-01 08:16:34

这里是一个伟大的截屏解释,一步一步,如何在Rails项目中使用authlogic。

在authlogic设置,定义您的应用程序控制器以下有用的身份验证相关的辅助方法。

 高清current_user_session
  如果定义返回@current_user_session?(@ current_user_session)
  @current_user_session = UserSession.find
结束高清CURRENT_USER
  如果定义返回@current_user?(@ CURRENT_USER)
  @current_user = current_user_session&放大器;&安培; current_user_session.record
结束高清require_user
  除非CURRENT_USER
    store_location
    闪光[:通知] =您必须先登录才能访问该页面
    redirect_to的new_user_session_url
    返回false
  结束
结束高清require_no_user
  如果CURRENT_USER
    store_location
    闪光[:通知] =您必须注销访问此页面
    redirect_to的root_url
    返回false
  结束
结束

一旦这些方法的定义,您可以指定需要用户先登录操作:

 的before_filter:require_user,:只=> [新,:编辑]

I'm using Authlogic and I would like to implement Basic HTTP Authentication in my controller so I could define which action requires authentication.

I know how to do Basic HTTP Authentication authenticate_or_request_with_http_basic an before_filter, but I would like to here from other how to implement it with Authlogic plugin.

class ItemsController < ApplicationController  
  before_filter :authenticate , :only => [:index, :create]
  ...
end

Here is a great screencast that explains, step-by-step, how to use authlogic in your rails project.

Once authlogic is set up, define the following useful authentication-related helper methods in your Application Controller.

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

def require_user
  unless current_user
    store_location
    flash[:notice] = "You must be logged in to access this page"
    redirect_to new_user_session_url
    return false
  end
end

def require_no_user
  if current_user
    store_location
    flash[:notice] = "You must be logged out to access this page"
    redirect_to root_url
    return false
  end
end

Once those methods are defined, you can specify actions that require the user to be logged in:

before_filter :require_user, :only => [:new, :edit]