Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
riculum committed Apr 15, 2022
1 parent 3059814 commit 5155349
Show file tree
Hide file tree
Showing 17 changed files with 442 additions and 2 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea/
/config/.env
/vendor
composer.lock
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 Riculum
Copyright (c) 2021 Riculum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
121 changes: 120 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,120 @@
# PHP-Auth
# PHP-Auth
A complete user authentication library written in PHP

## Installation
Use the package manager [composer](https://getcomposer.org) to install the library.
```bash
composer require riculum/php-auth
```

## Initial setup
### Credentials
The basic database settings can be set through environment variables. Add a `.env` file in the root of your project. Make sure the `.env` file is added to your `.gitignore` so it is not checked-in the code. By default, the library looks for the following variables:

* DB_HOST
* DB_NAME
* DB_USERNAME
* DB_PASSWORD
* DB_PREFIX

More information how to use environment variables [here](https://github.com/vlucas/phpdotenv)

### Database
```sql
CREATE TABLE IF NOT EXISTS user (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
uuid VARCHAR(50) NOT NULL UNIQUE,
firstname VARCHAR(50) NOT NULL,
lastname VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
token VARCHAR(255) NOT NULL,
attempts TINYINT NOT NULL DEFAULT 0,
online TINYINT NOT NULL DEFAULT 0,
verified TINYINT NOT NULL DEFAULT 0,
enabled TINYINT NOT NULL DEFAULT 1,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
)
```

*Note: We recommend to set a database prefix*

### Configuration
Import vendor/autoload.php and load the `.env` settings
```php
require_once 'vendor/autoload.php';

use Auth\Core\Authentication as Auth;

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
```

## Usage
### Registration
Use an associative array with user data to register a new user
```php
$user = array(
'firstname' => 'John',
'lastname' => 'Doe',
'email' => '[email protected]', //must be unique
'password' => '$2y$10$jNtkQSKNni2ELyoi9Y/lpedy7v92FYzqz5ePm1M6jPGY9hb8TCmAq',
'token' => md5(uniqid(rand(), true))
);

try {
echo Auth::register($user);
} catch (UserAlreadyExistsException $e) {
echo 'User with the specified email address already exists';
} catch (Exception $e) {
echo "Something went wrong";
}
```

### Login
```php
try {
Auth::login('[email protected]', '123456');
echo 'Login successful';
} catch (InvalidEmailException | InvalidPasswordException $e) {
echo 'Email or Password are wrong';
} catch(UserNotEnabledException $e) {
echo 'User account has been deactivated';
} catch (TooManyAttemptsException $e) {
echo 'Too many failed login attempts';
} catch (Exception $e) {
echo "Something went wrong";
}
```

### Verify
```php
if (Auth::verify()) {
echo "Authorization successful";
} else {
echo "Authorization failed";
}
```
### Logout
```php
try {
Auth::logout();
} catch (Exception $e) {
echo 'Something went wrong';
}
```

## Bugreport & Contribution
If you find a bug, please either create a ticket in github, or initiate a pull request

## Versioning
We adhere to semantic (major.minor.patch) versioning (https://semver.org/). This means that:

* Patch (x.x.patch) versions fix bugs
* Minor (x.minor.x) versions introduce new, backwards compatible features or improve existing code.
* Major (major.x.x) versions introduce radical changes which are not backwards compatible.

In your automation or procedure you can always safely update patch & minor versions without the risk of your application failing.


24 changes: 24 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "riculum/php-auth",
"description": "A complete user authentication library written in PHP",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Riculum",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"Auth\\" : "./"
}
},
"require": {
"vlucas/phpdotenv": "^5.3",
"riculum/php-pdo": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9"
}
}
5 changes: 5 additions & 0 deletions config/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DB_HOST=
DB_NAME=
DB_USERNAME=
DB_PASSWORD=
DB_PREFIX=
78 changes: 78 additions & 0 deletions core/Authentication.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
namespace Auth\Core;

use Auth\Exceptions\InvalidEmailException;
use Auth\Exceptions\InvalidPasswordException;
use Auth\Exceptions\TooManyAttemptsException;
use Auth\Exceptions\UserAlreadyExistsException;
use Auth\Exceptions\UserNotEnabledException;

class Authentication
{
private const MAX_LOGIN_ATTEMPTS = 5;

/**
* @throws UserAlreadyExistsException
*/
static function register(array $user): ?int
{
return User::addUser($user);
}

/**
* @throws InvalidEmailException
* @throws InvalidPasswordException
* @throws TooManyAttemptsException
* @throws UserNotEnabledException
*/
static function login(string $email, string $password): bool
{
$currentUser = User::getUserByEmail($email);

if (empty($currentUser)) {
throw new InvalidEmailException('E-Mail address could not be found');
}

if (password_verify($password, $currentUser['password']) && $currentUser['attempts'] < self::MAX_LOGIN_ATTEMPTS && $currentUser['enabled'] == 1) {
User::login($currentUser['id']);
} else if ($currentUser['enabled'] != 1) {
throw new UserNotEnabledException('User account has been deactivated');
} else if ($currentUser['attempts'] >= self::MAX_LOGIN_ATTEMPTS) {
throw new TooManyAttemptsException('Too many failed login attempts');
} else {
User::setUser($currentUser['id'], ['attempts' => $currentUser['attempts'] + 1]);
throw new InvalidPasswordException('Incorrect Password');
}

return true;
}

static function logout()
{
if (!empty(Session::getUserId())) {
User::logout();
}
}

static function verify(): bool
{
$sessionToken = Session::getUserToken();
$sessionUserId = Session::getUserId();

if (empty($sessionUserId) || empty($sessionToken)) {
return false;
}

$userToken = User::getUser($sessionUserId)['token'];

if (empty($userToken)) {
return false;
}

if ($sessionToken === $userToken) {
return true;
}

return false;
}
}
44 changes: 44 additions & 0 deletions core/Session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
namespace Auth\Core;

if (session_status() == PHP_SESSION_NONE) {
session_start();
}

class Session {

public static function destroySession()
{
session_destroy();
}

/**
* @return string|null
*/
static function getUserToken(): ?string
{
return $_SESSION['userToken'] ?? null;
}

/**
* @return int|null
*/
static function getUserId(): ?int
{
return $_SESSION['userId'] ?? null;
}

/**
* @param string $token
*/
static function setUserToken(string $token)
{
$_SESSION['userToken'] = $token;
}


static function setUserId(int $id)
{
$_SESSION['userId'] = $id;
}
}
Loading

0 comments on commit 5155349

Please sign in to comment.