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 或时间戳。我认为使用 disabled 比使用 active 更容易说明。
然后我对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 的cookie 并再次打开http://localhost:5000/users。这次输入bar和test。
您会看到登录不起作用。
要进行反测试,请将users_table 替换为config.yml 并重新启动应用程序。
# config.yml
users_table: 'users'
现在用户 foo 可以登录了。
这种方法不仅易于实现,而且应该是迄今为止性能最高的方法,因为数据库处理所有逻辑(并且很可能已经缓存了它)。
您的应用程序,尤其是身份验证插件,根本不需要知道 active 或 disabled 字段的存在。他们不需要关心。东西就行了。