PHPackages                             rafalmasiarek/authkit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. rafalmasiarek/authkit

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

rafalmasiarek/authkit
=====================

Lightweight and extensible PHP authentication library

v1.2.0(6mo ago)014MITPHPPHP &gt;=8.0

Since Jul 9Pushed 6mo agoCompare

[ Source](https://github.com/rafalmasiarek/php-AuthKit)[ Packagist](https://packagist.org/packages/rafalmasiarek/authkit)[ RSS](/packages/rafalmasiarek-authkit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (2)Versions (9)Used By (0)

AuthKit
=======

[](#authkit)

AuthKit is a lightweight, extensible PHP authentication library with:

- Registration &amp; login with secure password hashing
- Server-side **session tokens** (UUID) stored in DB with optional **TTL**
- Pluggable storage backend (**PDO** reference implementation)
- Optional **hooks** for policy &amp; audit (rate-limit, IP checks, logging, etc.)
- Flexible user model (`User::get($fields)` / `User::getAll()`); helpers `getId()`, `getEmail()`
- Admin features: **force logout** by user/token/email

> Designed for apps using Slim/Laminas/Symfony or plain PHP. Works with SQLite and MySQL.

---

🚀 Installation
--------------

[](#-installation)

```
composer require rafalmasiarek/authkit
```

Your `composer.json` should map:

```
{
  "autoload": {
    "psr-4": {
      "AuthKit\\": "src/"
    }
  }
}
```

Then:

```
composer dump-autoload -o
```

---

💾 Storage Model (Users &amp; Sessions)
--------------------------------------

[](#-storage-model-users--sessions)

AuthKit separates **users** from **sessions**. After a successful login, a random **UUID v4 token** is generated and stored in the `sessions` table. The token may have an **expiration** (`expires_at`, optional). The token is also saved in `$_SESSION[$sessionKey]` (default `auth_token`) to reference the DB session.

### Tables

[](#tables)

- `users` — app user records (email, password hash, flags, custom fields)
- `sessions` — active logins (user\_id, token, created\_at, expires\_at, optional IP/UA)

You’ll need both tables.

---

### SQLite DDL

[](#sqlite-ddl)

```
PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    name TEXT NULL,
    active INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TRIGGER IF NOT EXISTS users_updated_at
AFTER UPDATE ON users
BEGIN
    UPDATE users SET updated_at = datetime('now') WHERE id = NEW.id;
END;

CREATE TABLE IF NOT EXISTS sessions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    token TEXT NOT NULL UNIQUE,        -- UUID v4
    ip TEXT NULL,
    user_agent TEXT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    expires_at TEXT NULL,              -- NULL = no expiry
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
```

---

### MySQL DDL

[](#mysql-ddl)

```
CREATE TABLE IF NOT EXISTS users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(254) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  name VARCHAR(190) NULL,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS sessions (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  token CHAR(36) NOT NULL UNIQUE,          -- UUID v4
  ip VARCHAR(45) NULL,                     -- IPv4/IPv6
  user_agent TEXT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  expires_at DATETIME NULL,
  CONSTRAINT fk_sessions_user
    FOREIGN KEY (user_id) REFERENCES users(id)
    ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE INDEX idx_sessions_user_id ON sessions(user_id);
CREATE INDEX idx_sessions_expires_at ON sessions(expires_at);
```

---

🧩 Storage Contract (PDO reference)
----------------------------------

[](#-storage-contract-pdo-reference)

```
interface UserStorageInterface {
    public function findByEmail(string $email): ?\AuthKit\User;
    public function findByToken(string $token): ?\AuthKit\User;
    public function createUser(string $email, string $passwordHash, array $fields = []): \AuthKit\User;
    public function updateUser(\AuthKit\User $user, array $updates): \AuthKit\User;

    public function storeToken(\AuthKit\User $user, string $token, ?DateTime $expiresAt): void;
    public function deleteToken(string $token): int;

    public function deleteTokensByUserId(int $userId): int;
    // Optional: delete all except current
    // public function deleteTokensByUserIdExcept(int $userId, string $exceptToken): int;
}
```

---

🔧 Bootstrapping
---------------

[](#-bootstrapping)

```
use AuthKit\Auth;
use AuthKit\Storage\PdoUserStorage;

$pdo = new PDO('sqlite:/path/to/authkit.sqlite');
$storage = new PdoUserStorage($pdo);

// TTL semantics: 3600 = 1 hour; 0 = no expiry
$auth = new Auth($storage, hook: null, ttlSeconds: 3600);

// Optionally:
$auth->setSessionKey('auth_token');
$auth->setThrowExceptions(false);
```

---

🧠 API
-----

[](#-api)

### Register

[](#register)

```
register(string $email, string $password, array $customFields = [], array $additionalChecks = []): User|string|null
```

### Login

[](#login)

```
login(string $email, string $password, array $additionalChecks = []): ?string
```

### Current User

[](#current-user)

```
getUser(): ?User
isLoggedIn(): bool
```

### Logout

[](#logout)

```
logout(): void
```

### Force Logout

[](#force-logout)

```
forceLogoutUser(User|int $userOrId, ?string $reason = null): int
forceLogoutEmail(string $email, ?string $reason = null): int
forceLogoutToken(string $token, ?string $reason = null): int
```

---

🪝 Hooks
-------

[](#-hooks)

```
interface HookInterface {
    public function onBeforeRegister(string $email, string $password, array $fields): true|string;
    public function onRegisterSuccess(User $user): void;
    public function onRegisterFailure(string $email, \Throwable $e): void;

    public function onBeforeLogin(User $user): true|string;
    public function onLoginSuccess(User $user): void;
    public function onLoginFailure(string $email, \AuthKit\Exception\AuthException $e): void;

    public function onLogout(User $user): void;
    public function onLogoutExpired(): void;
    public function onUserActive(User $user): void;
    public function onUserUpdated(User $user, array $changedFields): void;

    public function onLogoutForced(int $userId, ?string $reason, int $count): void;
}
```

---

📦 Examples
----------

[](#-examples)

A runnable demo with SQLite forms is under `examples/sqlite-forms`:

```
examples/sqlite-forms/
├── bootstrap.php
├── schema.sql
├── index.php
├── account.php
├── logout.php
└── admin.php

```

Run:

```
php -S 127.0.0.1:8080 -t examples/sqlite-forms
```

The example will create `authkit.sqlite` on first run.

---

License
-------

[](#license)

MIT

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance72

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~29 days

Total

5

Last Release

186d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/17765d36dfdee9f4179c94861184464cb4282d224e9db7fa86b4dff6005c166c?d=identicon)[rafalmasiarek](/maintainers/rafalmasiarek)

---

Top Contributors

[![rafalmasiarek](https://avatars.githubusercontent.com/u/36776423?v=4)](https://github.com/rafalmasiarek "rafalmasiarek (6 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rafalmasiarek-authkit/health.svg)

```
[![Health](https://phpackages.com/badges/rafalmasiarek-authkit/health.svg)](https://phpackages.com/packages/rafalmasiarek-authkit)
```

###  Alternatives

[vonage/jwt

A standalone package for creating JWTs for Vonage APIs

424.1M4](/packages/vonage-jwt)[amocrm/amocrm-api-library

amoCRM API Client

182728.5k6](/packages/amocrm-amocrm-api-library)[microsoft/kiota-authentication-phpleague

Authentication provider for Kiota using the PHP League OAuth 2.0 client to authenticate against the Microsoft Identity platform

153.2M7](/packages/microsoft-kiota-authentication-phpleague)[telesign/telesign

TeleSign SDK

162.1M2](/packages/telesign-telesign)[allyans3/protobuf-steam-auth

description

219.7k3](/packages/allyans3-protobuf-steam-auth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
