This repository was archived by the owner on Apr 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
add nodejs example #4
Open
nocell
wants to merge
3
commits into
VKCOM:master
Choose a base branch
from
nocell:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,11 @@ | ||
| # vk-apps-launch-params | ||
|
|
||
| Пример работы с параметрами запуска: | ||
| * [PHP](#php) | ||
| * [Java (1.8)](#java1p8) | ||
| * [Python 3](#python3) | ||
|
|
||
| - [PHP](#php) | ||
| - [Java (1.8)](#java1p8) | ||
| - [Python 3](#python3) | ||
| - [Node.js](#nodejs) | ||
|
|
||
| <a name="php"/> | ||
|
|
||
|
|
@@ -24,9 +27,9 @@ foreach ($query_params as $name => $value) { | |
| $sign_params[$name] = $value; | ||
| } | ||
|
|
||
| ksort($sign_params); // Сортируем массив по ключам | ||
| ksort($sign_params); // Сортируем массив по ключам | ||
| $sign_params_query = http_build_query($sign_params); // Формируем строку вида "param_name1=value¶m_name2=value" | ||
| $sign = rtrim(strtr(base64_encode(hash_hmac('sha256', $sign_params_query, $client_secret, true)), '+/', '-_'), '='); // Получаем хеш-код от строки, используя защищеный ключ приложения. Генерация на основе метода HMAC. | ||
| $sign = rtrim(strtr(base64_encode(hash_hmac('sha256', $sign_params_query, $client_secret, true)), '+/', '-_'), '='); // Получаем хеш-код от строки, используя защищеный ключ приложения. Генерация на основе метода HMAC. | ||
|
|
||
| $status = $sign === $query_params['sign']; // Сравниваем полученную подпись со значением параметра 'sign' | ||
|
|
||
|
|
@@ -144,3 +147,47 @@ status = is_valid(query=query_params, secret=client_secret) | |
|
|
||
| print("ok" if status else "fail") | ||
| ``` | ||
|
|
||
| <a name="nodejs"/> | ||
|
|
||
| ## Пример проверки подписи на Node.js | ||
|
|
||
| ```javascript | ||
| const fs = require('fs') //модуль для ФС | ||
| const crypto = require('crypto') //модуль для криптографии Nodejs | ||
| const { stringify, parse } = require('querystring') //методы для парсинга строки | ||
|
|
||
| const URL = | ||
| '?vk_user_id=494075&vk_app_id=6736218&vk_is_app_user=1&vk_are_notifications_enabled=1&vk_language=ru&vk_access_token_settings=&vk_platform=android&sign=exTIBPYTrAKDTHLLm2AwJkmcVcvFCzQUNyoa6wAjvW6k', | ||
| CLIENT_SECRET = 'wvl68m4dR1UpLrVRli' | ||
|
|
||
| const isVKParam = e => e[0].startsWith('vk_') | ||
|
|
||
| const checkVKQueryParamsSign = params => { | ||
| const listOfParams = Object.entries(params) //перевод в обьекта параметро в список | ||
| .filter(isVKParam) //фильтрация параметров VK | ||
| .sort((a, b) => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Было бы круто вынести лямбда функции для filter и sort в отдельные методы, так код чище и читабельнее будет |
||
| if (a[0] < b[0]) { | ||
| return -1 | ||
| } | ||
| if (a[0] > b[0]) { | ||
| return 1 | ||
| } | ||
| return 0 | ||
| }) //сортировка по алфавиту | ||
| const paramsStr = stringify( | ||
| listOfParams.reduce((obj, [k, v]) => ({ ...obj, [k]: v }), {}) | ||
| ) //перевод параметров в строковый вид | ||
|
|
||
| const hmac = crypto.createHmac('sha256', CLIENT_SECRET) //инициализация генератора подписи | ||
| hmac.update(paramsStr) //добавление строки с параметрами | ||
| const sign = hmac | ||
| .digest('base64') | ||
| .replace(/\+/g, '-') | ||
|
tsivarev marked this conversation as resolved.
|
||
| .replace(/\//g, '_') | ||
| .replace(/=/g, '') //генерация подписи | ||
| return sign === params.sign //сравнение подписей | ||
| } | ||
|
|
||
| console.log(checkVKQueryParamsSign(parse(URL))) | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А что такое e?