Borodin suggested創建視圖並將其用作用戶表。我已經做了一些測試,可以說這確實是實現這一點的最簡單方法。
警告:由於視圖的性質,這使得應用程序無法修改或添加用戶!
請考慮以下Dancer2申請。我從dancer2
創建腳本開始。
$ dancer2 gen -a Foo
$ cd Foo
我創建了以下簡單的sqlite數據庫。
$ echo "
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(40) NOT NULL,
disabled TIMESTAMP NULL
);
CREATE VIEW active_users (id, username, password) AS
SELECT id, username, password FROM users WHERE disabled IS NULL;
INSERT INTO users (username, password, disabled)
VALUES ('foo', 'test', null),
('bar', 'test', '2017-10-01 10:10:10');
" | sqlite3 foo.sqlite
只有一個users
表由插件建議的默認列,加上列disabled
,其可以是或NULL
一個時間戳。我認爲用禁用來說明比用有效更容易說明。我想對lib/Foo.pm
做以下修改。所有這些基本上來自Dancer2::Plugin::Auth::Extensible和Dancer2::Plugin::Auth::Extensible::Provider::Database的文檔。
package Foo;
use Dancer2;
use Dancer2::Plugin::Database;
use Dancer2::Plugin::Auth::Extensible;
our $VERSION = '0.1';
get '/' => sub {
template 'index' => { 'title' => 'Foo' };
};
get '/users' => require_login sub {
my $user = logged_in_user;
return "Hi there, $user->{username}";
};
true;
接下來,插件需要進入配置。編輯config.yml
並用此替換它。
appname: "Foo"
layout: "main"
charset: "UTF-8"
template: "simple"
engines:
session:
Simple:
cookie_name: testapp.session
# this part is interesting
plugins:
Auth::Extensible:
realms:
users:
provider: 'Database'
############### here we set the view
users_table: 'active_users'
Database:
driver: 'SQLite'
database: 'foo.sqlite'
on_connect_do: ['PRAGMA foreign_keys = ON']
dbi_params:
PrintError: 0
RaiseError: 1
現在我們都準備嘗試。
$ plackup bin/app.psgi
HTTP::Server::PSGI: Accepting connections at http://0:5000/
在您的瀏覽器上訪問http://localhost:5000/users。你會看到默認的登錄表單。
輸入foo
和test
。這應該工作,你應該看到/users
路線。 (或者不是,就像我的情況那樣,重定向似乎被打破了......)。
現在去http://localhost:5000/logout擺脫Foo的餅乾和開放http://localhost:5000/users一次。這次輸入bar
和test
。
你會看到登錄不起作用。
要反測試,更換config.yml
的users_table
並重新啓動應用程序。
# config.yml
users_table: 'users'
現在用戶foo
將能夠登錄。因爲數據庫處理所有的邏輯(並且很可能已經緩存了它),所以這種方法不僅易於實現,而且也應該是具有最高性能的方式。
您的應用程序,特別是身份驗證插件,也不需要了解活躍或禁用領域都存在。他們不需要關心。東西只會工作。
我不明白爲什麼有人會低估你的問題。它寫得很好,顯示了一些研究(我們認爲閱讀源不應該被期望,或根本沒有問題),它清楚地說明你想要做什麼以及爲什麼,並且有一個代碼示例是這裏沒有關係。 – simbabque
我創建了一個票據將其移入文檔:https://github.com/PerlDancer/Dancer2-Plugin-Auth-Extensible-Provider-Database/issues/5 – simbabque