所以我有一个非常基本的静态页面rails应用程序,我想为人们创建一些用户名和密码来访问这些静态页面。当然,rails api有http_basic_atenticate,但是你应该如何拥有多个用户呢?
要清楚,我想只为多个用户使用http_basic。如何解决这个问题?
EG; user1有password1,user2有password2,user3有password3,等等吗?
class StaticController < ApplicationController
http_basic_authenticate_with :name => "user", :password => "password"
def home
end
def content
end
end
答案 0 :(得分:3)
简单的解决方案:
h = Hash[user1: "Password1", user2: "Password2"]
authenticate_or_request_with_http_basic do |id, password|
if h.has_key?(id.to_sym)
password == h[id.to_sym]
end
end
答案 1 :(得分:0)
找出答案。只需将一组USERS {.. etc}传递给def end块并根据需要调用它。
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
答案 2 :(得分:0)
虽然之前的答案肯定是100%正确,但我想分享一种更通用且可重复使用的方法(但基本上使用与之前答案相同的方法):
应用/控制器/关切/ guest_list_auth.rb 强>
module GuestListAuth
extend ActiveSupport::Concern
included do
cattr_accessor :guest_list
self.guest_list = :everyone_is_invited
before_action :perform_guest_list_auth
end
class_methods do
def authenticate_against_guest_list(guest_list)
self.guest_list = guest_list
end
end
protected
def perform_guest_list_auth
return if guest_list == :everyone_is_invited
authenticate_or_request_with_http_basic('Application') do |name, password|
guest_list.present? &&
guest_list.has_key?(name.to_sym) &&
guest_list[name.to_sym] == password.to_s
end
end
end
应用/控制器/ static_controller.rb 强>
class StaticController < ApplicationController
include GuestListAuth
authenticate_against_guest_list (
{
demo01: '...',
demo02: '...',
demo03: '...',
}
)
def home
end
# ...
end