@pyrocancode/react-native-vk-auth 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +103 -137
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,18 +1,14 @@
1
1
  # @pyrocancode/react-native-vk-auth
2
2
 
3
- React Native VK ID Auth.
4
-
5
- Форк библиотеки [@devsomersets/react-native-vk-auth](https://www.npmjs.com/package/@devsomersets/react-native-vk-auth) ([исходный репозиторий](https://github.com/somersets/react-native-vk-auth), автор Nikita Likhachev). Разработка ведётся в [pyrocancode/react-native-vk-auth](https://github.com/pyrocancode/react-native-vk-auth).
3
+ Тонкая обёртка над **VK ID SDK** для React Native: **OAuth 2.1**, нативные модули iOS и Android. Репозиторий: [pyrocancode/react-native-vk-auth](https://github.com/pyrocancode/react-native-vk-auth).
6
4
 
7
5
  ## Installation
8
6
 
9
- Из npm (после публикации пакета):
10
-
11
7
  ```sh
12
8
  npm install @pyrocancode/react-native-vk-auth
13
9
  ```
14
10
 
15
- Установка напрямую из GitHub:
11
+ Альтернатива установка из GitHub (конкретная ветка или коммит):
16
12
 
17
13
  ```sh
18
14
  npm install github:pyrocancode/react-native-vk-auth
@@ -88,21 +84,25 @@ cd ios && pod install
88
84
  }
89
85
  ```
90
86
 
91
- Затем в Typescript необходимо импортировать класс Linking при помощи которого вы сможете подписаться на события открытия ссылок и в месте обработки ссылок вызвать метод openURL у класса VK.
92
- ```javascript
87
+ Подключите `Linking` из React Native и `VK` из этого пакета в обработчике вызывайте `VK.openURL`, чтобы завершить OAuth-поток после возврата из клиента VK.
88
+
89
+ ```tsx
90
+ import { Linking } from 'react-native';
91
+ import { VK } from '@pyrocancode/react-native-vk-auth';
92
+
93
93
  React.useEffect(() => {
94
- Linking.getInitialURL().then((url) => {
95
- if (url) {
96
- handleOpenURL({'url': url});
97
- }
98
- }).catch(err => {
99
- console.warn('An error occurred', err);
100
- });
101
- Linking.addEventListener('url', handleOpenURL);
102
- });
94
+ Linking.getInitialURL()
95
+ .then((url) => {
96
+ if (url) handleOpenURL({ url });
97
+ })
98
+ .catch((err) => console.warn('getInitialURL', err));
99
+
100
+ const sub = Linking.addEventListener('url', handleOpenURL);
101
+ return () => sub.remove();
102
+ }, []);
103
103
 
104
104
  function handleOpenURL(event: { url: string }) {
105
- VK.openURL(event.url);
105
+ VK.openURL(event.url);
106
106
  }
107
107
  ```
108
108
 
@@ -146,148 +146,118 @@ dependencies { }
146
146
  <string name="vk_account_manager_id" translatable="false">your.package.account</string>
147
147
  ```
148
148
 
149
- ## Minimal common setup guide:
150
- 1. Initialization
151
-
152
- ```javascript
153
- import { VK, VKID } from 'react-native-superappkit-pub';
154
-
155
- // must be initialized only once
156
- let logo = Image.resolveAssetSource(require('./sample_logo.png'));
157
- let vkid = new VKID(
158
- 'Superappkit pub',
159
- '1.0',
160
- logo,
161
- {
162
- serviceUserAgreement: 'https://help.mail.ru/legal/terms/common/ua',
163
- servicePrivacyPolicy: 'https://help.mail.ru/legal/terms/common/privacy',
164
- serviceSupport: null,
165
- },
166
- new SilentTokenExchanger()
149
+ ## Минимальный общий сценарий (JS)
150
+
151
+ Инициализация выполняется **один раз** при старте приложения. Используйте `VK`, `VKID` и при необходимости `VKOneTapButton` из `@pyrocancode/react-native-vk-auth`.
152
+
153
+ ### 1. Инициализация
154
+
155
+ ```tsx
156
+ import { Image } from 'react-native';
157
+ import { VK, VKID } from '@pyrocancode/react-native-vk-auth';
158
+
159
+ const logo = Image.resolveAssetSource(require('./assets/logo.png'));
160
+
161
+ const vkid = new VKID(
162
+ 'Моё приложение',
163
+ '1.0.0',
164
+ logo,
165
+ {
166
+ serviceUserAgreement: 'https://example.com/terms',
167
+ servicePrivacyPolicy: 'https://example.com/privacy',
168
+ serviceSupport: null,
169
+ }
167
170
  );
168
171
 
169
172
  VK.initialize(
170
- {
171
- credentials: {
172
- clientId: 'your-client-id',
173
- clientSecret: 'your-client-secret',
174
- },
175
- mode: VK.Mode.DEBUG,
173
+ {
174
+ credentials: {
175
+ clientId: 'YOUR_CLIENT_ID',
176
+ clientSecret: 'YOUR_CLIENT_SECRET',
176
177
  },
177
- vkid
178
+ mode: VK.Mode.DEBUG,
179
+ },
180
+ vkid
178
181
  );
179
182
  ```
180
183
 
181
- 2. Auth
182
- ```javascript
183
- // App.tsx
184
-
185
- // 1. Silent Token Exchanger
186
- class SilentTokenExchanger implements VKID.SilentTokenExchanger {
187
- exchange(silentData: VKID.SilentToken): Promise<VKID.TokenExchangeResult<VKID.AccessToken, Error>> {
188
- return fetch('your_endpoint_for_exchange_token', {
189
- method: 'POST',
190
- headers: {'Content-Type': 'application/json; charset=UTF-8'},
191
- })
192
- .then((response) => response.json())
193
- .then((body) => {
194
- let accessToken = 'received access_token';
195
- let userId = 'received user_id';
196
- let result: VKID.TokenExchangeResult = {
197
- ok: true,
198
- accessToken: {
199
- token: new VKID.Token(accessToken),
200
- userID: new VKID.UserID(userId),
201
- }
202
- };
203
- return result;
204
- });
205
- }
206
- }
184
+ ### 2. Подписка на авторизацию и выход
185
+
186
+ ```tsx
187
+ vkid.setOnAuthChanged({
188
+ onAuthorized(payload) {
189
+ // OAuth 2.1: access token и идентификатор пользователя VK
190
+ console.log(payload.accessToken, payload.userId, payload.profile);
191
+ },
192
+ onLogout() {
193
+ console.log('Пользователь вышел');
194
+ },
195
+ onAuthFailed(message) {
196
+ console.warn(message);
197
+ },
198
+ });
199
+ ```
207
200
 
208
- //2. Set observer for auth state changing
209
- vkid.setOnAuthChanged(new class implements VKID.AuthChangedCallback {
210
- onAuth(userSession: VKID.Session.UserSession): void {
211
- if (userSession instanceof VKID.Session.Authorized) {
212
- // user was successfuly authorized, so show authorized flow or get user profile info
213
- userSession.userProfile.then((profileInfo) => {
214
- setProfileInfo("Profile info: " + profileInfo.userID.value + " " + profileInfo.firstName);
215
- })
216
- }
217
- }
201
+ ### 3. Кнопка One Tap или ручной старт
218
202
 
219
- onLogout(): void {
220
- // logout
221
- }
222
- })
203
+ ```tsx
204
+ import { Button } from 'react-native';
205
+ import { VKOneTapButton, VKID } from '@pyrocancode/react-native-vk-auth';
223
206
 
224
- // 2.1 Use One Tap Loggin button
225
- import { VKOneTapButton } from 'react-native-superappkit-pub';
207
+ // В разметке
226
208
  <VKOneTapButton />
227
209
 
228
- // 2.2 OR use start auth manually
229
- <Button title={'Auth by VK'} onPress={() => auth()} />
230
- function auth() {
231
- vkid.startAuth();
232
- }
210
+ // Или кнопка «Войти через VK»
211
+ <Button title="Войти через VK" onPress={() => vkid.startAuth()} />
233
212
 
234
- // You may use force close
213
+ // Принудительно закрыть экран авторизации
235
214
  function forceCloseAuth() {
236
- vkid.closeAuth();
215
+ vkid.closeAuth();
237
216
  }
238
217
 
239
- // Logout
240
218
  function logout() {
241
- vkid.logout();
219
+ vkid.logout();
242
220
  }
243
221
 
244
- // Check is logged in
245
- async function isLoggedIn() {
246
- let sessions = await vkid.getUserSessions();
247
- let isLoggedIn = sessions.some((session) => session instanceof VKID.UserSession.Authorized)
222
+ async function checkLoggedIn() {
223
+ const sessions = await vkid.userSessions();
224
+ return sessions.some((s) => s instanceof VKID.Session.Authorized);
248
225
  }
249
226
  ```
250
227
 
251
- ### One Tap Button customization
252
- ```javascript
253
- import { VKOneTapButton, VKOneTapButtonSpace } from 'react-native-superappkit-pub';
228
+ ### Кастомизация One Tap
229
+
230
+ ```tsx
231
+ import { VKOneTapButton, VKOneTapButtonSpace } from '@pyrocancode/react-native-vk-auth';
232
+
254
233
  <VKOneTapButton
255
- style={styles.vkView}
256
- backgroundStyle={{
257
- style: VKOneTapButtonSpace.BgColor.CUSTOM, /* or 'BLUE' (default) or 'WHITE' */
258
- customVkIconColor: '#your-color-if-using-custom-style',
259
- customBackgroundColor: '#your-color-if-using-custom-style',
260
- customTextColor: '#your-color-if-using-custom-style'
261
- }}
262
- iconGravity={
263
- // 'START' (by default) or 'TEXT'
264
- VKOneTapButtonSpace.IconGravity.START
265
- }
266
- firstLineFieldType={
267
- // 'NONE' (by default) or 'ACTION' or 'PHONE'
268
- VKOneTapButtonSpace.LineFieldType.ACTION
269
- }
270
- secondLineFieldType={
271
- // 'NONE' (by default) or 'ACTION' or 'PHONE'
272
- VKOneTapButtonSpace.LineFieldType.PHONE
273
- }
274
- texts={{
275
- noUserText: 'Login as VK',
276
- actionText: 'Login as {firstName} {lastName}', /* {firstName} and {lastName} are templates that will be replaced by real user names */
277
- phoneText: 'With phone {phone}', /* {phone} is a template that will be replaced by user phone */
278
- }}
279
- oneLineTextSize={ 16 }
280
- firstLineTextSize={ 16 }
281
- secondLineTextSize={ 14 }
282
- avatarSize={ 64 }
283
- iconSize={ 64 }
284
- progressSize={ 56 }
234
+ style={styles.vkView}
235
+ backgroundStyle={{
236
+ style: VKOneTapButtonSpace.BgColor.CUSTOM,
237
+ customVkIconColor: '#fff',
238
+ customBackgroundColor: '#0077FF',
239
+ customTextColor: '#fff',
240
+ }}
241
+ iconGravity={VKOneTapButtonSpace.IconGravity.START}
242
+ firstLineFieldType={VKOneTapButtonSpace.LineFieldType.ACTION}
243
+ secondLineFieldType={VKOneTapButtonSpace.LineFieldType.PHONE}
244
+ texts={{
245
+ noUserText: 'Войти через VK',
246
+ actionText: 'Продолжить как {firstName} {lastName}',
247
+ phoneText: 'Телефон {phone}',
248
+ }}
249
+ oneLineTextSize={16}
250
+ firstLineTextSize={16}
251
+ secondLineTextSize={14}
252
+ avatarSize={64}
253
+ iconSize={64}
254
+ progressSize={56}
285
255
  />
286
256
  ```
287
257
 
288
258
  ## Usage
289
259
 
290
- Раздел в разработке.
260
+ После настройки iOS/Android (см. выше) используйте API из раздела «Минимальный общий сценарий»: `VK.initialize`, `vkid.setOnAuthChanged`, `vkid.startAuth` / `VKOneTapButton`, `VK.openURL` для deep link.
291
261
 
292
262
  ## Contributing
293
263
 
@@ -295,8 +265,4 @@ See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the
295
265
 
296
266
  ## License
297
267
 
298
- [MIT](LICENSE). Исходный код Nikita Likhachev (2022); изменения и сопровождение форка — pyrocancode (2026). См. полный текст в файле `LICENSE`.
299
-
300
- ---
301
-
302
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
268
+ [MIT](LICENSE). См. полный текст в файле `LICENSE`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrocancode/react-native-vk-auth",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Тонкая обёртка над VK ID SDK для React Native: OAuth 2.1, нативные модули iOS и Android.",
5
5
  "main": "src/index.tsx",
6
6
  "module": "src/index.tsx",