Skip to content

Instantly share code, notes, and snippets.

@okaufmann
Last active February 7, 2018 00:52
Show Gist options
  • Save okaufmann/28fd45d6c91107380953123c2e1e4e03 to your computer and use it in GitHub Desktop.
Save okaufmann/28fd45d6c91107380953123c2e1e4e03 to your computer and use it in GitHub Desktop.
TelegramLoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
class TelegramLoginController extends Controller
{
public function callback(Request $request)
{
$requestData = $this->exctractVerifiedRequestData($request);
dd($requestData);
}
/**
* Extracts the data if the request was signed correctly.
* Original example from https://gist.github.com/anonymous/6516521b1fb3b464534fbc30ea3573c2
*
* @param $request
* @return mixed
*/
public function exctractVerifiedRequestData(Request $request)
{
abort_unless($this->isRequestDataSigned($request), Response::HTTP_UNAUTHORIZED);
$requestData = $request->except(['hash', 'hash_date']);
$requestData['hash_date'] = Carbon::createFromTimestampUTC($request->input('auth_date'));
return $requestData;
}
/**
* Verifies the given data array is coming from Telegram.
*
* @param Request $request
* @return bool
*/
private function isRequestDataSigned(Request $request): bool
{
$hashPassword = config('services.telegram-bot-api.token');
$checksum = $request->input('hash');
$dataCheckString = $this->convertToKeyValueString($request);
// hash the password with
$secretKey = hash('sha256', $hashPassword, true);
// hash the converted payload whith the hashed password (that is what telegram does on their site)
$checkHash = hash_hmac('sha256', $dataCheckString, $secretKey);
// if the same hash was calculated, the payload is signed correctly and valid
if (strcmp($checkHash, $checksum) !== 0) {
return false;
}
// if auth date is older than one hour, abort
$authDate = Carbon::createFromTimestampUTC($request->input('auth_date'));
if (Carbon::now()->greaterThanOrEqualTo($authDate->addHour())) {
return false;
}
return true;
}
/**
* Convert the given array in a key=value line by line string.
*
* @param Request $request
* @return string
*/
private function convertToKeyValueString(Request $request): string
{
$data = $request->except(['hash']);
$dataCheckArr = [];
foreach ($data as $key => $value) {
$dataCheckArr[] = $key.'='.$value;
}
sort($dataCheckArr);
$keyValueString = implode("\n", $dataCheckArr);
return $keyValueString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment