如果你只是想有个用户,一个管理员,使用登录名和密码,并没有其他用户帐户,那么我会推荐HTTP Digest Auth,它可以被开箱即用的Rails支持,并且不需要任何额外的宝石或插件。 (或HTTP基本身份验证,但摘要身份验证稍微安全一些。)
以下大部分内容取自rails网站上的action controller guide。
在配置/ routes.rb中:
resources :posts
在控制器/ posts_controller.rb:
class PostsController < ActionController::Base
USERS = { "admin" => "password" }
before_action :authenticate, except: [:index, :show]
# actions here (index, show, new, create, edit, update, destroy)
private
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
end
如果你愿意,你可以修改的路线,以便新/创建/编辑/更新/销毁行动是在 '管理/' 的网站的一部分:
在配置/ routes.rb中:
scope '/admin' do
resources :posts, except: [:index, :show]
end
resources :posts, only: [:index, :show]
这仍然会将所有与帖子相关的请求定向到PostsController。
我不完全相信我明白这一点。我需要在我的控制台中创建管理员帐户和密码吗?否则验证方法将如何获取密码进行验证? – coderwannabe2 2015-02-01 10:39:06
我不确定我是否知道你的意思,但'authenticate_or_request_with_http_digest'需要一个块;该块被赋予用户名作为第一个参数,并且必须返回密码。 – 2015-02-08 20:35:51