Golem Auth
, (*1)
Simple authentication storage library., (*2)
This library only handles the storage of authentication data.
It does not handle the authentication itself or storage/retrieval of user data., (*3)
Install
Via Composer, (*4)
``` bash
$ composer require golem/auth, (*5)
## Usage
You must have a user model that implements `Golem\Auth\Authenticatable`.
The `getAuthId` method must return a unique identifier for the user.
This can be an auto-incrementing primary key, a uuid, a unique email address or username, or any other field that can be used to uniquely identify a user.
``` php
use Golem\Auth\Authenticatable;
class User implements Authenticatable
{
public $id;
public $name;
public $email;
public function getAuthId()
{
return $this->id;
}
}
Your repository or database model must implement Golem\Auth\UserRepository
., (*6)
The findUserById
method must return the user object that implements Golem\Auth\Authenticatable
for the given value of the field returned by getAuthId
., (*7)
It should throw a RuntimeException if the user is not found., (*8)
``` php
class UserRepository implements \Golem\Auth\UserRepository
{
public function findUserById($id)
{
// or whatever you need to do to pull a user record
$data = $this->database->fetchRow('SELECT * from users WHERE id = ?', [$id]);
if (!$data) {
throw new \RuntimeException('User not found.');
}
return new User($data);
}
}, (*9)
You now can use the Golem Auth library.
``` php
// Use the native php session
session_start();
$storage = new \Golem\Auth\NativeSession();
// get an instance of your user repository however you need to
$userRepository = new UserRepository($database_connection);
$auth = new \Golem\Auth($storage, $userRepository);
Logging in a User
You must pull a user record and check the credentials yourself. This is not part of Golem Auth.
I recommend using the password_hash, and password_verify functions to check credentials., (*10)
``` php
// Should return a User instance that implements Golem\Auth\Authenticatable
$user = $userRepository->getByCredentials($email, $password);, (*11)
// Store the user login
$auth->login($user);, (*12)
### Checking for a logged in User
``` php
if ($auth->loggedIn()) {
// The user is logged in
}
if (!$auth->loggedIn()) {
// The user is not logged in
}
Getting the user object for the currently logged in user
``` php
// The first time this is called a fresh user record will be pulled from the UserRepository.
// Any further calls will return the existing record.
// If there is no logged in user this will return null.
// If the logged in user cannot be pulled a RuntimeException will be thrown.
$user = $auth->user();, (*13)
// Returns just the user identifier
// This does not pull anything from the UserRepository
$id = $auth->getUserId();, (*14)
### Logging out the user
``` php
$auth->logout();
Testing
bash
$ composer test
, (*15)
License
The MIT License (MIT). Please see License File for more information., (*16)