96 lines
2.6 KiB
PHP
96 lines
2.6 KiB
PHP
<?php
|
|
namespace Core;
|
|
|
|
use App\Models\ApiModel;
|
|
use App\Models\ClientSession;
|
|
use Defuse\Crypto\Crypto;
|
|
use Defuse\Crypto\Key;
|
|
|
|
class Token
|
|
{
|
|
public static function generate($id)
|
|
{
|
|
// $user = ApiModel::fetch('users', [
|
|
// ['id', '=', $id]
|
|
// ]);
|
|
// $token = Hash::make($user['full_name'] . $user['salt'], $user['salt']);
|
|
|
|
// Token exists for x seconds
|
|
$expires = 60;
|
|
// Talk to database
|
|
// Get salt
|
|
$user = ApiModel::fetch('users', [
|
|
['id', '=', $id]
|
|
]);
|
|
$salt = $user['salt'];
|
|
// Get hash string
|
|
$session = ClientSession::fetch(['uid' => $id]);
|
|
$hash_string = $session['id'].$session['ip_address'];
|
|
// Create array
|
|
$array_token = [
|
|
'uid' => $id,
|
|
'expires' => time() + $expires,
|
|
'token' => Hash::make($hash_string, $salt)
|
|
];
|
|
// Convert array to string and to base64
|
|
$token = serialize($array_token);
|
|
$token = base64_encode($token);
|
|
// Create a key
|
|
$key = Key::loadFromAsciiSafeString($salt);
|
|
// Encrypt token
|
|
$token = Crypto::encrypt($token, $key);
|
|
// Configure token (\$id.token)
|
|
// Convert id to base64
|
|
$id = base64_encode($id);
|
|
$token = '\$'.$id.'.'.$token;
|
|
|
|
return $token;
|
|
}
|
|
|
|
public static function validate($token)
|
|
{
|
|
$request_token = self::fetch($token);
|
|
|
|
$exploded = explode('.', $token);
|
|
$id = self::getId($exploded[0]);
|
|
|
|
$user = ApiModel::fetch('users', [
|
|
['id', '=', $id]
|
|
]);
|
|
$salt = $user['salt'];
|
|
$session = ClientSession::fetch(['uid' => $id]);
|
|
$hash_string = $session['id'].$session['ip_address'];
|
|
$server_token = Hash::make($hash_string, $salt);
|
|
|
|
if ($request_token['expires'] >= time() && $request_token['token'] == $server_token) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public static function fetch($token)
|
|
{
|
|
// Get id and token
|
|
$exploded = explode('.', $token);
|
|
$id = self::getId($exploded[0]);
|
|
$token = $exploded[1];
|
|
|
|
$user = ApiModel::fetch('users', [
|
|
['id', '=', $id]
|
|
]);
|
|
|
|
$key = $user['salt'];
|
|
$key = Key::loadFromAsciiSafeString($key);
|
|
$token = Crypto::decrypt($token, $key);
|
|
$token = base64_decode($token);
|
|
$token = unserialize($token);
|
|
|
|
return $token;
|
|
}
|
|
|
|
public static function getId($raw_id)
|
|
{
|
|
return base64_decode(substr_replace($raw_id, '', 0, 2));
|
|
}
|
|
}
|