rafaelgou/php-apache2-basic-auth

PHP Apache2 Basic Auth

v1.0.0 2016-09-01 18:53 UTC

README

这是一个使用 .htpasswd 和 .htgroups 文件进行 .htaccess Basic Auth 的简单类服务。

原始的 HtPasswd 和 HtGroup 类来自 Yang Yang

如果您想使用这个库运行应用程序,请查看 PHP Apache2 Basic Auth Manager

完整 API

查看 API

安装

此规范可以通过 Composer 依赖管理器安装。

  1. 安装 Composer
  2. 将编码规范作为您项目的依赖项安装
composer require rafaelgou/php-apache2-basic-auth

使用

您需要定义一个 .htpasswd 文件和可选的 .htgroups 文件。

实例化服务

<?php

// ...
use Apache2BasicAuth\Service as HTService;

$htService = new HTService(
    'PATH_TO/.htpasswd',
    'PATH_TO/.htgroups'
);

创建一个组

<?php

// ... Instanciate the Service ...

// Create a new group
$group = $htService->createGroup();
$group->setName('admin')
    ->addUser('mateus')
    ->addUser('tiago');

// Groups can be also set:
$group->setUsers(array('bernardo', 'larissa'));

// Staging to write    
$htService->persist($group);

// Writing to disc
$htService->write();

编辑一个组

<?php

// ... Instanciate the Service ...

// Create a new group
$group = $htService->findGroup('admin');
$group
    ->removeUser('mateus')
    ->addUser('ana');

// Staging to write    
$htService->persist($group);

// Writing to disc
$htService->write();

删除一个组

<?php

// ... Instanciate the Service ...

// Create a new group
$group = $htService->findGroup('admin');

// Staging to write    
$htService->htService->removeGroup($group);

// Writing to disc
$htService->write();

创建一个用户

<?php

// ... Instanciate the Service ...

// Create a new user
$user = $htService->createUser();
$user->setUsername('rafael')
    ->setPassword('my_pass_123')
    ->setAddGroup('admin')
    ->setAddGroup('finance');

// Groups can be also set:
$user->setGroups(array('opperations', 'support'));

// Staging to write    
$htService->persist($user);

// Writing to disc
$htService->write();

注意:当您设置密码时,会更新哈希密码。

编辑用户

<?php

// ... Instanciate the Service ...

// Finding an existing user
$user = $htService->findUser('rafael');
$user->setPassword('my_pass_123')
    ->removeGroup('admin')
    ->setAddGroup('marketing');

// Staging to write    
$htService->persist($user);

// Writing to disc
$htService->write();

注意:当您设置密码时,会更新哈希密码。如果未设置,则保留旧哈希。

删除用户

<?php

// ... Instanciate the Service ...

// Finding an existing user
$user = $htService->findUser('rafael');

// Staging to write    
$htService->htService->removeUser($user);

// Writing to disc
$htService->write();

列出组和用户

<?php

// ... Instanciate the Service ...

// Getting Users
$users = $htService->getUsers();

// The key is the username too
foreach ($users as $username => $user) {
    echo $user->getUsername();
    echo $user->getHash(); // Hashed password
    echo implode(', ', $user->getGroups());
}

// Getting Groups
$groups = $htService->getGroups();

// The key is the username too
foreach ($groups as $groupname => $group) {
    echo $group->getName();
    echo implode(', ', $user->getUsers());
}