@nitra/cap 1.0.1 → 1.0.2

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.
package/README.md CHANGED
@@ -3,3 +3,4 @@
3
3
  | Папка | Описание |
4
4
  |-----------------------------|--------------------------------------------------------|
5
5
  | [app-update](./app-apdate/) | Проверка и установка новой версии приложения в маркете |
6
+ | [save-token](./save-token/) | Отримання та збереження push токену |
package/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export * from './app-update'
2
+ export * from './save-token'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nitra/cap",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Nitra capacitor components",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -17,7 +17,9 @@
17
17
  },
18
18
  "homepage": "https://github.com/nitra/cap",
19
19
  "dependencies": {
20
+ "@capacitor-firebase/messaging": "^6.1.0",
20
21
  "@capacitor/core": "^6.1.2",
21
- "@capawesome/capacitor-app-update": "^6.0.0"
22
+ "@capawesome/capacitor-app-update": "^6.0.0",
23
+ "firebase": "^10.13.1"
22
24
  }
23
25
  }
@@ -0,0 +1,84 @@
1
+ # Receiving and Saving User Push Tokens
2
+
3
+ ## Description
4
+
5
+ This library is designed to handle obtaining and saving Firebase push tokens on the client side. It supports both mobile platforms (via Capacitor) and web platforms. The main function, `saveToken`, retrieves a push token from Firebase, stores it locally, and sends it to your server.
6
+
7
+ This library interacts with Firebase for token management and Capacitor to check the platform and permissions. It ensures that push tokens are properly handled, regardless of whether the platform is iOS, Android, or Web.
8
+
9
+ ## API
10
+
11
+ ### `saveToken()`
12
+
13
+ ```typescript
14
+ saveToken() => Promise<void>
15
+ ```
16
+
17
+ ## usage with Vite
18
+ ### Set vapid key : ``` import.meta.env.VITE_VAPID_KEY ```
19
+ ### Set host url of the notify project: ``` import.meta.env.VITE_NOTIFY_URL ```
20
+ The ```notify project``` is a server-side component designed to handle API requests for saving user push tokens. It uses the Fastify framework and JWT-based security for authentication.
21
+ ### Or set for local dev: ```import.meta.env.VITE_LOCALHOST```
22
+
23
+ ### Set the name of your app: ```import.meta.env.VITE_APP```
24
+
25
+ ## usage the library
26
+ ### To use this package, you should add this code to your project where you want to provide push notifications
27
+
28
+ ```typescript
29
+ initializeApp({
30
+ apiKey: import.meta.env.VITE_API_KEY,
31
+ authDomain: import.meta.env.VITE_AUTH_DOMAIN,
32
+ projectId: import.meta.env.VITE_PROJECT_ID,
33
+ storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
34
+ messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
35
+ appId: import.meta.env.VITE_APP_ID
36
+ })
37
+ ```
38
+ ### This code will initialize firebase
39
+
40
+ ## example in node
41
+ ### Using function after login
42
+ ```jsx
43
+ <template>
44
+ <n-code @token-checked="saveToken" />
45
+ </template>
46
+
47
+ <script setup>
48
+ import NCode from '@nitra/abie-components/auth/NCode.vue'
49
+ import { saveToken } from '@nitra/cap'
50
+
51
+ await saveToken()
52
+ </script>
53
+
54
+ <route lang="yaml">
55
+ meta:
56
+ layout: blank
57
+ </route>
58
+
59
+ ```
60
+
61
+ ## Environment Variable Validation with Vite
62
+ ### To ensure that required environment variables are set, add the following to your vite.config.js
63
+ ```typescript
64
+ import { requireEnvVar } from '@nitra/vite-check-env'
65
+
66
+ export default {
67
+ plugins: [
68
+ requireEnvVar([
69
+ 'VITE_API_KEY',
70
+ 'VITE_AUTH_DOMAIN',
71
+ 'VITE_PROJECT_ID'
72
+ 'VITE_STORAGE_BUCKET',
73
+ 'VITE_MESSAGING_SENDER_ID',
74
+ 'VITE_APP_ID',
75
+ 'VITE_VAPID_KEY',
76
+ 'VITE_NOTIFY_URL',
77
+ 'VITE_APP'])
78
+ ]
79
+ }
80
+ ```
81
+ ### Install the plugin in the project directory
82
+ ```typescript
83
+ yarn add -D @nitra/vite-check-env
84
+ ```
@@ -0,0 +1,3 @@
1
+ import { getMessaging } from 'firebase/messaging/sw'
2
+ // eslint-disable-next-line no-unused-vars
3
+ const messaging = getMessaging()
@@ -0,0 +1,92 @@
1
+ import { Capacitor } from '@capacitor/core'
2
+ import { FirebaseMessaging } from '@capacitor-firebase/messaging'
3
+ import { getToken } from '@nitra/vite-boot/token'
4
+
5
+ /**
6
+ * Save the Firebase push token for a given app and platform.
7
+ * @returns {Promise<void>}
8
+ */
9
+ export async function saveToken() {
10
+ try {
11
+ if (localStorage.getItem('pushToken')) {
12
+ console.log('Push Token is already exists.')
13
+
14
+ return
15
+ }
16
+
17
+ if (!Capacitor.isPluginAvailable('FirebaseMessaging')) {
18
+ console.error('FirebaseMessaging plugin is not available')
19
+
20
+ return
21
+ }
22
+
23
+ let permissions = await FirebaseMessaging.checkPermissions()
24
+
25
+ if (permissions.receive !== 'granted') {
26
+ console.warn('Permissions are not granted, try to request permissions...')
27
+
28
+ let permissionsRequest = await FirebaseMessaging.requestPermissions()
29
+
30
+ if (permissionsRequest.receive !== 'granted') {
31
+ console.error('Permissions are not granted, exiting...')
32
+
33
+ return
34
+ }
35
+ }
36
+
37
+ const pushToken = Capacitor.isNativePlatform()
38
+ ? await FirebaseMessaging.getToken() // For iOS/Android
39
+ : await getWebPushToken()
40
+
41
+ if (!pushToken?.token && typeof pushToken?.token !== 'string') {
42
+ console.error('Token is undefined exiting...')
43
+
44
+ return
45
+ }
46
+
47
+ await sendTokenToServer(pushToken.token)
48
+ } catch (error) {
49
+ console.error('Error while saving push token:', error)
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Get the Firebase push token for web platform.
55
+ * @returns {Promise<object>} Web Push token
56
+ */
57
+ async function getWebPushToken() {
58
+ const serviceWorkerRegistration = await navigator.serviceWorker.register('src/firebase-messaging-sw.js', {
59
+ type: 'module'
60
+ })
61
+
62
+ return FirebaseMessaging.getToken({
63
+ vapidKey: import.meta.env.VITE_VAPID_KEY,
64
+ serviceWorkerRegistration
65
+ })
66
+ }
67
+
68
+ /**
69
+ * Send the Firebase push token to the server.
70
+ * @param {string} pushToken - The push token returned by Firebase Messaging.
71
+ * @returns {Promise<void>}
72
+ */
73
+ async function sendTokenToServer(pushToken) {
74
+ const host = import.meta.env.VITE_NOTIFY_URL ?? import.meta.env.VITE_LOCALHOST
75
+
76
+ const response = await fetch(`${host}/save-user`, {
77
+ method: 'POST',
78
+ headers: {
79
+ 'Content-Type': 'application/json',
80
+ authorization: `Bearer ${getToken()}`
81
+ },
82
+ body: JSON.stringify({
83
+ platform: Capacitor.getPlatform(),
84
+ app: import.meta.env.VITE_APP,
85
+ token: pushToken
86
+ })
87
+ })
88
+
89
+ if (response.ok) {
90
+ localStorage.setItem('pushToken', pushToken)
91
+ }
92
+ }