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