forked from SocialiteProviders/Providers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProvider.php
More file actions
97 lines (79 loc) · 2.38 KB
/
Provider.php
File metadata and controls
97 lines (79 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace SocialiteProviders\TelegramWebApp;
use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;
class Provider extends AbstractProvider
{
/**
* Unique Provider Identifier.
*/
public const IDENTIFIER = 'TELEGRAMWEBAPP';
/**
* {@inheritdoc}
*/
public static function additionalConfigKeys(): array
{
return [];
}
protected function getAuthUrl($state): string
{
return null;
}
protected function getTokenUrl(): string
{
return null;
}
/**
* {@inheritdoc}
*/
protected function getUserByToken($token)
{
return null;
}
/**
* {@inheritdoc}
*/
protected function mapUserToObject(array $user)
{
$name = trim(sprintf('%s %s', $user['first_name'] ?? '', $user['last_name'] ?? ''));
return (new User())->setRaw($user)->map([
'id' => $user['id'],
'nickname' => $user['username'] ?? $user['first_name'],
'name' => !empty($name) ? $name : null,
'avatar' => $user['photo_url'] ?? null,
]);
}
/**
* {@inheritdoc}
*/
public function user()
{
$data = $this->request->query();
if (!$this->validateTelegramHash($data)) {
throw new InvalidArgumentException('Invalid Telegram WebApp data');
}
$userString = $data['user'] ?? null;
if (!$userString) {
throw new InvalidArgumentException('User data not found in Telegram WebApp response');
}
$telegramUser = json_decode($userString, true);
if (!$telegramUser) {
throw new InvalidArgumentException('Invalid user data format');
}
return $this->mapUserToObject($telegramUser);
}
private function validateTelegramHash(array $data): bool
{
$sign = $data['hash'];
$checkString = collect($data)
->except('hash')
->sortKeys()
->transform(fn ($v, $k) => "$k=$v")
->join("\n");
$secret = hash_hmac('sha256', $this->clientSecret, 'WebAppData', true);
$calculatedHash = bin2hex(hash_hmac('sha256', $checkString, $secret, true));
return hash_equals($sign, $calculatedHash);
}
}