kevinkaske/herman

为 Pooch 简单的认证库

dev-master 2020-01-19 07:46 UTC

This package is auto-updated.

Last update: 2024-09-19 17:38:36 UTC


README

Pooch 提供的简单认证库

关于

Herman 是一个为 Pooch 设计的即插即用认证库。它很简单。它提供了一个用户表和一个账户表,以及用于验证用户的函数。

安装

安装概述

Herman 的安装通过 composer 完成。您只需将以下内容添加到您的 composer.json 文件中

{
	"minimum-stability": "dev",
	"require": {
		"kevinkaske/herman": "dev-master"
	}
}

然后运行 composer install。Composer 将安装依赖库。

现在我们需要设置项目。运行以下命令 php vendor/kevinkaske/herman/setup/setup.php

现在您需要运行迁移来设置 Herman 的数据库表。您可以通过在命令行中运行 php vendor/bin/phinx migrate 来执行此迁移。

与 Pooch 集成

现在我们已经安装了 Herman Auth 库并设置了数据库表,我们需要使用这个库来限制访问。

将您的 ApplicationController 修改为以下内容

<?
class ApplicationController extends Controller{
	public $auth;

	function __construct($controller, $action) {
		parent::__construct($controller, $action);

		$this->auth = new HermanAuth();

		if($controller != 'sessions'){
			$this->auth->membersOnly();
		}

		if($this->auth->isLoggedIn()){
			$this->getCurrentUser();
			$this->getCurrentAccount();
		}
	}

	function getCurrentUser(){
		$this->db->where("id", $_SESSION['user_id']);
		$this->addToApplicationData('current_user', $this->db->getOne("users"));
	}

	function getCurrentAccount(){
		$this->db->where("id", $_SESSION['account_id']);
		$this->addToApplicationData('current_account', $this->db->getOne("accounts"));
	}
}
?>

__construct 方法在每次请求到来时都会被调用。我们只是创建一个新的 HermanAuth 实例并选择我们想要应用的规则来限制访问。我们应用以下逻辑

if($controller != 'login'){
	$this->auth->membersOnly();
}

通过这种方式,我们检查当前请求被路由到的控制器。我们的登录控制器是我们用于创建会话的控制器,因此我们希望为该控制器提供通行证,并要求其他每个控制器都需要会话。如果您想显式列出所有要限制访问的控制器,则可以反转此逻辑。例如

if($controller == 'restricted' || $controller == 'members'){
	$this->auth->membersOnly();
}

最后一步是加载当前登录的用户和账户,并通过 $this->application_data['current_account']$this->application_data['current_user'] 使其可用。