michele-angioni/phalcon-auth

一个提供简单认证的库。

v0.1 2016-05-08 20:41 UTC

This package is auto-updated.

Last update: 2024-08-29 03:42:01 UTC


README

License Latest Stable Version Latest Unstable Version Build Status

简介

Phalcon Auth 为您提供了一种快速注册和验证用户的方法。

每个应用程序、每个网站都需要一个包含其自身属性和方法的自定义用户模型。Phalcon Auth 不会强迫您使用其自己的模型,也不会通过与其他模型定义关系来创建无用的开销。您是 Phalcon 用户,因此速度和简单性是您所追求的。

因此,Phalcon Auth 只需要您的用户模型通过实现其接口来满足某些要求。基本上,它只需要几个方法

  • getId() : (int)
  • getEmail() : (string)
  • getPassword() : (string)
  • setPassword($password) : (bool)
  • getConfirmationCode() : (string)
  • setConfirmationCode($confirmationCode) : (bool)
  • confirm() : (bool)
  • isConfirmed() : (bool)
  • isBanned() : (bool)

此外,如果您想使用“记住我”功能,还需要以下记住令牌获取器和设置器

  • getRememberToken() : (string)
  • setRememberToken($token) : (bool)

安装

Phalcon Auth 可以通过 Composer 安装,只需在您的 composer.json 中包含 "michele-angioni/phalcon-auth": "~0.1",然后运行 composer updatecomposer install

用法

假设您有一个 MyApp\Users 模型,您想使其可验证。要这样做的方法非常简单,即它必须实现 MicheleAngioni\PhalconAuth\Contracts\AuthableInterface 或,如果您想使用“记住我”功能,则实现 MicheleAngioni\PhalconAuth\Contracts\RememberableAuthableInterface

以下是一个示例

namespace MyApp;

class Users extends \Phalcon\Mvc\Model implements \MicheleAngioni\PhalconAuth\Contracts\RememberableAuthableInterface
{
    protected $id;
    
    protected $banned;

    protected $confirmation_code;

    protected $confirmed;

    protected $email;

    protected $password;

    protected $remember_token;

    public function getId()
    {
        return $this->id;
    }

    public function getConfirmationCode()
    {
        return $this->confirmation_code;
    }

    public function isConfirmed()
    {
        return (bool)$this->confirmed;
    }

    public function getEmail()
    {
        return $this->email;
    }
    
    public function setEmail($email)
    {
        $this->email = $email;
        return true;
    }

    public function getPassword()
    {
        return $this->password;
    }
    
    public function setPassword($password)
    {
        $this->password = $password;
        return true;
    }

    public function getRememberToken()
    {
        return $this->remember_token;
    }

    public function setRememberToken($token)
    {
        $this->remember_token = $token;
        return true;
    }
    
    public function isBanned()
    {
        return (bool)$this->banned;
    }
}

我们可以在应用程序引导文件中的 Phalcon 容器中定义 auth 服务,并将 MyApp\Users 模型传递给它。这样,它将很容易在控制器中检索到

/**
 * Authentication
 */
$di->setShared('auth', function () {
    return \MicheleAngioni\PhalconAuthAuth(new \MyApp\Users());
});

现在我们可以定义一个用于用户注册、确认、登录、注销和密码重置的简单控制器

<?php

namespace MyApp\Controllers;

use Phalcon\Mvc\Controller;

class AuthController extends Controller
{

    public function registerAction()
    {
        $email = $this->request->getPost('email);
        $password = $this->request->getPost('password);
        
        // [..] Data validation
    
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Register the new user
        
        try {
            $user = $auth->register($email, $password);
        } catch (\Exception $e) {
            if ($e instanceof \UnexpectedValueException) {
                // The email has already been taken, handle the exception
            } else {
                // Handle other exception
            }
        }

        [...] // It is up to you to comunicate the confirmation code to the user
    }
    
    public function confirmAction($idUser, $confirmationCode)
    {
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Confirm the user
        
        try {
            $user = $auth->confirm($idUser, $confirmationCode);
        } catch (\Exception $e) {
            if ($e instanceof \EntityNotFoundException) {
                // User not found. Handle the exception
            } else {
                // Wrong confirmation code. Handle other exception
            }
        }

        [...]
    }
    
    public function loginAction()
    {
        $email = $this->request->getPost('email);
        $password = $this->request->getPost('password);
        
        // [..] Data validation
    
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Perform login
        
        try {
            $user = $auth->attemptLogin($email, $password);
        } catch (\Exception $e) {
            if ($e instanceof \MicheleAngioni\PhalconAuth\Exceptions\EntityBannedException) {
                // The user is banned. Handle exception
            } else {
                // Handle wrong credentials exception
            }
        }

        [...]
    }
    
    public function logoutAction()
    {
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Perform logout
        $auth->logout();

        [...]
    }
    
    public function getPasswordTokenAction($idUser)
    {
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Get the reset password token
        
        try {
            $token = $auth->getResetPasswordToken($idUser);
        } catch (\Exception $e) {
            if ($e instanceof \MicheleAngioni\PhalconAuth\Exceptions\EntityNotFoundException) {
                // User not found. Handle the exception
            } else {
                // Authable entity is not confirmed yet, it cannot reset the password. Handle the exception
            }
        }

        [...]
    }
    
    public function resetPasswordAction($idUser, $resetToken)
    {
        $password = $this->request->getPost('newPassword);
                    
        // [..] Data validation
    
        // Retrieve Auth Service
        $auth = $this->getDI()->get('auth');
        
        // Get the reset password token
        
        try {
            $token = $auth->resetPassword($idUser, $resetToken, $newPassword);
        } catch (\Exception $e) {
            if ($e instanceof \MicheleAngioni\PhalconAuth\Exceptions\EntityNotFoundException) {
                // User not found. Handle the exception
            } else {
                // Authable entity is not confirmed or the token is wrong. Handle the exception
            }
        }

        [...]
    }
}

登录后,用户 ID 和电子邮件将被保存到会话中。

高级用户注册

当注册新用户时,您可以传递一个包含其他参数的数组以及一个包含您想要在用户表中唯一的参数的数组

$auth->register($email, $password, $parameters = [], $uniqueParameters = [], $addConfirmationCode = true));

自定义登录

您可以通过修改其他方法参数来自定义登录设置

$auth->attemptLogin($email, $password, $saveSession = true, $rememberMe = false);

设置“记住我”后登录

通过“记住我”进行身份验证后,只需使用以下方法

if ($auth->hasRememberMe()) {
    $auth->loginWithRememberMe();
}

从会话中检索登录用户信息

$auth->getIdentity(); // Returns an array with 'id' and 'email' keys

检索已验证的用户

$auth->getAuth();

通过用户 ID 手动登录

$auth->authById($id);

自定义行为

当定义 Auth 服务时,您可以传递一个选项数组。以下是所有可用选项的列表

    /**
     * Authentication
     */
     $options = [
        'rememberMeDuration' => 1096000 // Optional, default: 604800 (1 week)
     ];
     
    $di->set('auth', function () {
        return \MicheleAngioni\PhalconAuthAuth(new \MyApp\Users(), $options);
    });

贡献指南

Phalcon Auth 遵循 PSR-1、PSR-2 和 PSR-4 PHP 编码标准,以及语义版本控制。

欢迎 pull requests。

许可证

Phalcon Auth 是在 MIT 许可证条款下分发的免费软件。