@linked.cm/capacitor 0.0.0-stage → 0.2.0
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/.changeset/README.md +20 -0
- package/.changeset/config.json +14 -0
- package/.github/workflows/pr.yml +27 -0
- package/.github/workflows/publish.yml +32 -0
- package/CHANGELOG.md +38 -0
- package/lib/esm/auth/SocialLoginClient.d.ts +40 -0
- package/lib/esm/auth/SocialLoginClient.js +240 -0
- package/lib/esm/auth/SocialLoginClient.js.map +1 -0
- package/lib/esm/backend.d.ts +26 -0
- package/lib/esm/backend.js +302 -0
- package/lib/esm/backend.js.map +1 -0
- package/lib/esm/components/LocationEnabler.d.ts +6 -0
- package/lib/esm/components/LocationEnabler.js +48 -0
- package/lib/esm/components/LocationEnabler.js.map +1 -0
- package/lib/esm/components/LocationEnabler.module.css +6 -0
- package/lib/esm/components/SafeAreaContainer.d.ts +10 -0
- package/lib/esm/components/SafeAreaContainer.js +36 -0
- package/lib/esm/components/SafeAreaContainer.js.map +1 -0
- package/lib/esm/components/SafeAreaContainer.module.css +39 -0
- package/lib/esm/components/SignInWithWhatsapp.d.ts +9 -0
- package/lib/esm/components/SignInWithWhatsapp.js +86 -0
- package/lib/esm/components/SignInWithWhatsapp.js.map +1 -0
- package/lib/esm/components/SignInWithWhatsapp.module.css +92 -0
- package/lib/esm/components/SigninWithAppleButton.d.ts +13 -0
- package/lib/esm/components/SigninWithAppleButton.js +45 -0
- package/lib/esm/components/SigninWithAppleButton.js.map +1 -0
- package/lib/esm/components/SigninWithAppleButton.module.css +22 -0
- package/lib/esm/components/SigninWithFacebookButton.d.ts +13 -0
- package/lib/esm/components/SigninWithFacebookButton.js +46 -0
- package/lib/esm/components/SigninWithFacebookButton.js.map +1 -0
- package/lib/esm/components/SigninWithFacebookButton.module.css +22 -0
- package/lib/esm/components/SigninWithGoogleButton.d.ts +13 -0
- package/lib/esm/components/SigninWithGoogleButton.js +47 -0
- package/lib/esm/components/SigninWithGoogleButton.js.map +1 -0
- package/lib/esm/components/SigninWithGoogleButton.module.css +22 -0
- package/lib/esm/data/lincd-capacitor.json +20 -0
- package/lib/esm/hooks/useAutomaticUpdates.d.ts +22 -0
- package/lib/esm/hooks/useAutomaticUpdates.js +270 -0
- package/lib/esm/hooks/useAutomaticUpdates.js.map +1 -0
- package/lib/esm/hooks/useCapacitor.d.ts +12 -0
- package/lib/esm/hooks/useCapacitor.js +68 -0
- package/lib/esm/hooks/useCapacitor.js.map +1 -0
- package/lib/esm/hooks/useNativeAppUpdate.d.ts +3 -0
- package/lib/esm/hooks/useNativeAppUpdate.js +68 -0
- package/lib/esm/hooks/useNativeAppUpdate.js.map +1 -0
- package/lib/esm/index.d.ts +13 -0
- package/lib/esm/index.js +16 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/ontologies/lincd-capacitor.d.ts +30 -0
- package/lib/esm/ontologies/lincd-capacitor.js +28 -0
- package/lib/esm/ontologies/lincd-capacitor.js.map +1 -0
- package/lib/esm/ontologies/lincd-capacitor.register.d.ts +1 -0
- package/lib/esm/ontologies/lincd-capacitor.register.js +15 -0
- package/lib/esm/ontologies/lincd-capacitor.register.js.map +1 -0
- package/lib/esm/package.d.ts +10 -0
- package/lib/esm/package.js +6 -0
- package/lib/esm/package.js.map +1 -0
- package/lib/esm/shapes/LocationUpdateAction.d.ts +11 -0
- package/lib/esm/shapes/LocationUpdateAction.js +34 -0
- package/lib/esm/shapes/LocationUpdateAction.js.map +1 -0
- package/lib/esm/shapes/index.d.ts +2 -0
- package/lib/esm/shapes/index.js +5 -0
- package/lib/esm/shapes/index.js.map +1 -0
- package/lib/esm/types.d.ts +12 -0
- package/lib/esm/types.js +1 -0
- package/lib/esm/types.js.map +1 -0
- package/lib/esm/utils/helper.d.ts +14 -0
- package/lib/esm/utils/helper.js +39 -0
- package/lib/esm/utils/helper.js.map +1 -0
- package/package.json +103 -4
- package/readme.md +50 -0
- package/renovate.json +4 -0
- package/tests/social-login-client.test.mjs +99 -0
- package/tsconfig-esm.json +9 -0
- package/README.md +0 -3
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';
|
|
2
|
+
import { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';
|
|
3
|
+
import { LocationUpdateAction } from './shapes/LocationUpdateAction.js';
|
|
4
|
+
import { AdministrativeArea } from '@_linked/schema/shapes/AdministrativeArea';
|
|
5
|
+
import { Auth } from '@_linked/auth/utils/auth';
|
|
6
|
+
import { offAccountWillBeRemoved, onAccountWillBeRemoved, } from '@_linked/auth/utils/events';
|
|
7
|
+
import { UserAccount } from '@_linked/sioc/shapes/UserAccount';
|
|
8
|
+
import { AuthCredential } from '@_linked/auth/shapes/AuthCredential';
|
|
9
|
+
import { telephoneToWebID } from '@_linked/auth/utils/webID';
|
|
10
|
+
import { normalizeTelephone } from './utils/helper.js';
|
|
11
|
+
export default class CapacitorBackendProvider extends BackendProvider {
|
|
12
|
+
constructor() {
|
|
13
|
+
super(...arguments);
|
|
14
|
+
this.accountShape = UserAccount;
|
|
15
|
+
this.userShape = SchemaPerson;
|
|
16
|
+
this.onAccountRemoved = async (account) => {
|
|
17
|
+
const person = account.accountOf;
|
|
18
|
+
if (person) {
|
|
19
|
+
// The location action is optional. Delete by its relation so accounts
|
|
20
|
+
// without location history do not pass `null` into an ID-based delete.
|
|
21
|
+
await LocationUpdateAction.deleteWhere((action) => action.agent.equals(person));
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
async setupBeforeControllers() {
|
|
26
|
+
//if defined, take the values from the environment variables to define the shapes for the account and user
|
|
27
|
+
await this.assignEnvPathToField('AUTH_ACCOUNT_TYPE', 'accountShape');
|
|
28
|
+
await this.assignEnvPathToField('AUTH_USER_TYPE', 'userShape');
|
|
29
|
+
onAccountWillBeRemoved(this.onAccountRemoved);
|
|
30
|
+
}
|
|
31
|
+
dispose() {
|
|
32
|
+
offAccountWillBeRemoved(this.onAccountRemoved);
|
|
33
|
+
}
|
|
34
|
+
async validateOTPWhatsapp(phoneIdentifier, OPT_Input) {
|
|
35
|
+
try {
|
|
36
|
+
if (!phoneIdentifier) {
|
|
37
|
+
console.log('No phone number provided');
|
|
38
|
+
return { error: 'No phone number provided' };
|
|
39
|
+
}
|
|
40
|
+
const normalizedPhone = normalizeTelephone(phoneIdentifier);
|
|
41
|
+
const legacyPhone = String(phoneIdentifier || '').trim();
|
|
42
|
+
if (!normalizedPhone) {
|
|
43
|
+
console.log('No valid phone number provided');
|
|
44
|
+
return { error: 'No phone number provided' };
|
|
45
|
+
}
|
|
46
|
+
if (!OPT_Input) {
|
|
47
|
+
console.log('No OTP code provided');
|
|
48
|
+
return { error: 'No OTP code provided' };
|
|
49
|
+
}
|
|
50
|
+
if (this.request.session.otp.toString() !== OPT_Input) {
|
|
51
|
+
console.log('OTP code is incorrect');
|
|
52
|
+
return { error: 'OTP code is incorrect' };
|
|
53
|
+
}
|
|
54
|
+
return await Auth.login(this, async () => {
|
|
55
|
+
const telephoneWebId = telephoneToWebID(normalizedPhone);
|
|
56
|
+
// first, try to find account by telephone-based webID (for new users)
|
|
57
|
+
let account = await UserAccount.select((ua) => [
|
|
58
|
+
ua.email,
|
|
59
|
+
ua.accountOf.select((p) => [
|
|
60
|
+
p.givenName,
|
|
61
|
+
p.familyName,
|
|
62
|
+
p.telephone,
|
|
63
|
+
]),
|
|
64
|
+
])
|
|
65
|
+
.where((ua) => {
|
|
66
|
+
return ua.accountOf.equals({
|
|
67
|
+
id: telephoneWebId,
|
|
68
|
+
});
|
|
69
|
+
})
|
|
70
|
+
.one();
|
|
71
|
+
if (account && account.accountOf) {
|
|
72
|
+
console.log(`Found account by telephone-based webID for phone number ${phoneIdentifier}`);
|
|
73
|
+
return {
|
|
74
|
+
account,
|
|
75
|
+
person: account.accountOf,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
// if not found, try to find by telephone property (for old users with normal ID)
|
|
79
|
+
console.log(`Account not found by webID, searching by telephone property for ${normalizedPhone}`);
|
|
80
|
+
account = await UserAccount.select((ua) => [
|
|
81
|
+
ua.email,
|
|
82
|
+
ua.accountOf.select((p) => [
|
|
83
|
+
p.givenName,
|
|
84
|
+
p.familyName,
|
|
85
|
+
p.telephone,
|
|
86
|
+
]),
|
|
87
|
+
])
|
|
88
|
+
.where((ua) => {
|
|
89
|
+
// Try normalized phone first, but also support legacy stored strings.
|
|
90
|
+
return ua.accountOf.telephone
|
|
91
|
+
.equals(normalizedPhone)
|
|
92
|
+
.or(ua.accountOf.telephone.equals(legacyPhone));
|
|
93
|
+
})
|
|
94
|
+
.one();
|
|
95
|
+
if (account && account.accountOf) {
|
|
96
|
+
console.log(`Found account by telephone property for phone number ${phoneIdentifier}`);
|
|
97
|
+
return {
|
|
98
|
+
account,
|
|
99
|
+
person: account.accountOf,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
console.warn(`Could not find any account for phone number ${normalizedPhone} (tried webID: ${telephoneWebId} and telephone property)`);
|
|
103
|
+
return null;
|
|
104
|
+
}, async () => {
|
|
105
|
+
const telephoneWebId = telephoneToWebID(normalizedPhone);
|
|
106
|
+
// create a new user by telephone webID
|
|
107
|
+
const user = await this.userShape.create({
|
|
108
|
+
__id: telephoneWebId,
|
|
109
|
+
givenName: '',
|
|
110
|
+
familyName: '',
|
|
111
|
+
telephone: normalizedPhone,
|
|
112
|
+
});
|
|
113
|
+
if (!user) {
|
|
114
|
+
console.error('Error creating user by telephone webID: ' + telephoneWebId);
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
// create a new credential for the user
|
|
118
|
+
const newCredential = await AuthCredential.create({
|
|
119
|
+
credentialOf: {
|
|
120
|
+
id: user.id,
|
|
121
|
+
},
|
|
122
|
+
telephone: normalizedPhone,
|
|
123
|
+
});
|
|
124
|
+
if (!newCredential) {
|
|
125
|
+
console.error('Error creating credential by telephone webID: ' + telephoneWebId);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
const account = await this.accountShape.create({
|
|
129
|
+
email: '',
|
|
130
|
+
accountOf: user,
|
|
131
|
+
});
|
|
132
|
+
if (!account) {
|
|
133
|
+
console.warn('Creating new account by telephone webID: ' +
|
|
134
|
+
telephoneWebId +
|
|
135
|
+
' failed');
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
account: account,
|
|
140
|
+
person: user,
|
|
141
|
+
};
|
|
142
|
+
}, 'Whatsapp. Phonenumber: ' + phoneIdentifier);
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
console.error('validateOTPWhatsapp failed:', err);
|
|
146
|
+
return {
|
|
147
|
+
error: 'Sign-in failed. Please try again.',
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async generateOTPWhatsapp(phoneNumber) {
|
|
152
|
+
const session = this.request.session;
|
|
153
|
+
const baseUrl = 'https://waba-v2.360dialog.io';
|
|
154
|
+
const bearerToken = this.getBearerToken();
|
|
155
|
+
const API_KEY = process.env.WA_D360_API_KEY;
|
|
156
|
+
const otp = this.generateOTP();
|
|
157
|
+
const message = `Your OTP for Whatsapp Auth is ${otp}`;
|
|
158
|
+
console.log('OTP', message);
|
|
159
|
+
// Save the OTP
|
|
160
|
+
session.otp = otp;
|
|
161
|
+
const url = `${baseUrl}/messages`;
|
|
162
|
+
try {
|
|
163
|
+
const response = await this.sendMessage(url, bearerToken, API_KEY, otp, phoneNumber);
|
|
164
|
+
const data = await response.json();
|
|
165
|
+
return { data };
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
console.error('Error sending message:', error.message);
|
|
169
|
+
throw error; // Propagate the error for handling at a higher level
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async getBearerToken() {
|
|
173
|
+
const username = process.env.WA_D360_USERNAME;
|
|
174
|
+
const password = process.env.WA_D360_PASSWORD;
|
|
175
|
+
if (!username || !password) {
|
|
176
|
+
throw new Error('WA_D360_USERNAME and WA_D360_PASSWORD are required to request a WhatsApp token');
|
|
177
|
+
}
|
|
178
|
+
const url = 'https://hub.360dialog.io/api/v2/token';
|
|
179
|
+
try {
|
|
180
|
+
const response = await fetch(url, {
|
|
181
|
+
method: 'POST',
|
|
182
|
+
headers: {
|
|
183
|
+
'Content-Type': 'application/json',
|
|
184
|
+
},
|
|
185
|
+
body: JSON.stringify({
|
|
186
|
+
username,
|
|
187
|
+
password,
|
|
188
|
+
}),
|
|
189
|
+
});
|
|
190
|
+
const data = await response.json();
|
|
191
|
+
return data.access_token;
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
console.error('Error getting access token:', error.message);
|
|
195
|
+
throw error; // Propagate the error for handling at a higher level
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
generateOTP() {
|
|
199
|
+
return Math.floor(100000 + Math.random() * 900000);
|
|
200
|
+
}
|
|
201
|
+
async sendMessage(url, bearerToken, apiKey, otp, phoneNumber) {
|
|
202
|
+
const templateNamespace = process.env.WA_D360_TEMPLATE_NAMESPACE;
|
|
203
|
+
const templateName = process.env.WA_D360_TEMPLATE_NAME;
|
|
204
|
+
if (!templateNamespace || !templateName) {
|
|
205
|
+
throw new Error('WA_D360_TEMPLATE_NAMESPACE and WA_D360_TEMPLATE_NAME are required to send a WhatsApp code');
|
|
206
|
+
}
|
|
207
|
+
const payload = {
|
|
208
|
+
messaging_product: 'whatsapp',
|
|
209
|
+
to: phoneNumber,
|
|
210
|
+
type: 'template',
|
|
211
|
+
template: {
|
|
212
|
+
namespace: templateNamespace,
|
|
213
|
+
name: templateName,
|
|
214
|
+
language: {
|
|
215
|
+
code: 'en',
|
|
216
|
+
policy: 'deterministic',
|
|
217
|
+
},
|
|
218
|
+
components: [
|
|
219
|
+
{
|
|
220
|
+
type: 'body',
|
|
221
|
+
parameters: [
|
|
222
|
+
{
|
|
223
|
+
type: 'text',
|
|
224
|
+
text: otp,
|
|
225
|
+
},
|
|
226
|
+
],
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
type: 'button',
|
|
230
|
+
sub_type: 'url',
|
|
231
|
+
index: 0,
|
|
232
|
+
parameters: [
|
|
233
|
+
{
|
|
234
|
+
type: 'text',
|
|
235
|
+
text: otp.toString(),
|
|
236
|
+
},
|
|
237
|
+
],
|
|
238
|
+
},
|
|
239
|
+
],
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
const response = await fetch(url, {
|
|
243
|
+
method: 'POST',
|
|
244
|
+
headers: {
|
|
245
|
+
'Content-Type': 'application/json',
|
|
246
|
+
Authorization: `bearer ${bearerToken}`,
|
|
247
|
+
'D360-API-KEY': apiKey,
|
|
248
|
+
},
|
|
249
|
+
body: JSON.stringify(payload),
|
|
250
|
+
});
|
|
251
|
+
return response;
|
|
252
|
+
}
|
|
253
|
+
async getUserLocationAction(user) {
|
|
254
|
+
const locationAction = await LocationUpdateAction.select((la) => {
|
|
255
|
+
return [la.agent];
|
|
256
|
+
})
|
|
257
|
+
.where((la) => {
|
|
258
|
+
return la.agent.equals({
|
|
259
|
+
id: user.id,
|
|
260
|
+
});
|
|
261
|
+
})
|
|
262
|
+
.one();
|
|
263
|
+
return locationAction;
|
|
264
|
+
}
|
|
265
|
+
async updateUserLocation(latitude, longitude) {
|
|
266
|
+
const auth = this.request.linkedAuth;
|
|
267
|
+
if (!auth || !auth.userAccount) {
|
|
268
|
+
console.warn('No user authenticated.');
|
|
269
|
+
return Auth.enforceSignedIn();
|
|
270
|
+
}
|
|
271
|
+
const user = auth.user;
|
|
272
|
+
// find existing instance for the login person
|
|
273
|
+
const locationAction = await this.getUserLocationAction(user);
|
|
274
|
+
// if not found, create one and set person property and location, then .save()
|
|
275
|
+
if (!locationAction) {
|
|
276
|
+
const newPlace = await AdministrativeArea.create({
|
|
277
|
+
latitude: latitude.toString(),
|
|
278
|
+
longitude: longitude.toString(),
|
|
279
|
+
});
|
|
280
|
+
const newLocationAction = await LocationUpdateAction.create({
|
|
281
|
+
location: {
|
|
282
|
+
id: newPlace.id,
|
|
283
|
+
},
|
|
284
|
+
agent: {
|
|
285
|
+
id: user.id,
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
return newLocationAction;
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
// if existing one found, update location
|
|
292
|
+
const existingLocationAction = await LocationUpdateAction.update(locationAction, {
|
|
293
|
+
location: {
|
|
294
|
+
latitude: latitude.toString(),
|
|
295
|
+
longitude: longitude.toString(),
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
return existingLocationAction;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
//# sourceMappingURL=backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.js","sourceRoot":"","sources":["../../src/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,6CAA6C,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,MAAM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,eAAe;IAArE;;QACS,iBAAY,GAAuB,WAAW,CAAC;QAC/C,cAAS,GAAwB,YAAY,CAAC;QACpC,qBAAgB,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B,CAAC,MAAM,CAAC;gBAC/C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE;gBAC7B,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;aAChC,CAAC,CAAC;YAEH,MAAM,iBAAiB,GAAG,MAAM,oBAAoB,CAAC,MAAM,CAAC;gBAC1D,QAAQ,EAAE;oBACR,EAAE,EAAE,QAAQ,CAAC,EAAE;iBAChB;gBACD,KAAK,EAAE;oBACL,EAAE,EAAE,IAAI,CAAC,EAAE;iBACZ;aACF,CAAC,CAAC;YACH,OAAO,iBAAiB,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,yCAAyC;YACzC,MAAM,sBAAsB,GAAG,MAAO,oBAA4B,CAAC,MAAM,CACvE,cAAc,EACd;gBACE,QAAQ,EAAE;oBACR,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE;oBAC7B,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;iBAChC;aACF,CACF,CAAC;YACF,OAAO,sBAAsB,CAAC;QAChC,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { LocationUpdateAction } from './shapes/LocationUpdateAction.js';\nimport { AdministrativeArea } from '@_linked/schema/shapes/AdministrativeArea';\nimport { Auth } from '@_linked/auth/utils/auth';\nimport {\n offAccountWillBeRemoved,\n onAccountWillBeRemoved,\n} from '@_linked/auth/utils/events';\nimport { UserAccount } from '@_linked/sioc/shapes/UserAccount';\nimport { AuthCredential } from '@_linked/auth/shapes/AuthCredential';\nimport { telephoneToWebID } from '@_linked/auth/utils/webID';\nimport type { UserAccountData, UserData } from '@_linked/auth/types/auth';\nimport { normalizeTelephone } from './utils/helper.js';\n\nexport default class CapacitorBackendProvider extends BackendProvider {\n public accountShape: typeof UserAccount = UserAccount;\n public userShape: typeof SchemaPerson = SchemaPerson;\n private readonly onAccountRemoved = async (account: UserAccountData) => {\n const person = account.accountOf;\n\n if (person) {\n // The location action is optional. Delete by its relation so accounts\n // without location history do not pass `null` into an ID-based delete.\n await LocationUpdateAction.deleteWhere((action) =>\n action.agent.equals(person)\n );\n }\n };\n\n async setupBeforeControllers() {\n //if defined, take the values from the environment variables to define the shapes for the account and user\n await this.assignEnvPathToField('AUTH_ACCOUNT_TYPE', 'accountShape');\n await this.assignEnvPathToField('AUTH_USER_TYPE', 'userShape');\n\n onAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n dispose() {\n offAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n async validateOTPWhatsapp(phoneIdentifier, OPT_Input) {\n try {\n if (!phoneIdentifier) {\n console.log('No phone number provided');\n return { error: 'No phone number provided' };\n }\n\n const normalizedPhone = normalizeTelephone(phoneIdentifier);\n const legacyPhone = String(phoneIdentifier || '').trim();\n if (!normalizedPhone) {\n console.log('No valid phone number provided');\n return { error: 'No phone number provided' };\n }\n\n if (!OPT_Input) {\n console.log('No OTP code provided');\n return { error: 'No OTP code provided' };\n }\n\n if (this.request.session.otp.toString() !== OPT_Input) {\n console.log('OTP code is incorrect');\n return { error: 'OTP code is incorrect' };\n }\n\n return await Auth.login(\n this,\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // first, try to find account by telephone-based webID (for new users)\n let account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n return ua.accountOf.equals({\n id: telephoneWebId,\n });\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone-based webID for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n // if not found, try to find by telephone property (for old users with normal ID)\n console.log(\n `Account not found by webID, searching by telephone property for ${normalizedPhone}`\n );\n account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n // Try normalized phone first, but also support legacy stored strings.\n return ua.accountOf.telephone\n .equals(normalizedPhone)\n .or(ua.accountOf.telephone.equals(legacyPhone));\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone property for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n console.warn(\n `Could not find any account for phone number ${normalizedPhone} (tried webID: ${telephoneWebId} and telephone property)`\n );\n return null;\n },\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // create a new user by telephone webID\n const user = await (this.userShape as any).create({\n __id: telephoneWebId,\n givenName: '',\n familyName: '',\n telephone: normalizedPhone,\n });\n\n if (!user) {\n console.error(\n 'Error creating user by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n // create a new credential for the user\n const newCredential = await AuthCredential.create({\n credentialOf: {\n id: user.id,\n },\n telephone: normalizedPhone,\n });\n\n if (!newCredential) {\n console.error(\n 'Error creating credential by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n const account = await (this.accountShape as any).create({\n email: '',\n accountOf: user,\n });\n\n if (!account) {\n console.warn(\n 'Creating new account by telephone webID: ' +\n telephoneWebId +\n ' failed'\n );\n return null;\n }\n\n return {\n account: account,\n person: user,\n };\n },\n 'Whatsapp. Phonenumber: ' + phoneIdentifier\n );\n } catch (err) {\n console.error('validateOTPWhatsapp failed:', err);\n return {\n error: 'Sign-in failed. Please try again.',\n };\n }\n }\n\n async generateOTPWhatsapp(phoneNumber) {\n const session = this.request.session;\n const baseUrl = 'https://waba-v2.360dialog.io';\n const bearerToken = this.getBearerToken();\n const API_KEY = process.env.WA_D360_API_KEY;\n\n const otp = this.generateOTP();\n const message = `Your OTP for Whatsapp Auth is ${otp}`;\n console.log('OTP', message);\n\n // Save the OTP\n session.otp = otp;\n\n const url = `${baseUrl}/messages`;\n\n try {\n const response = await this.sendMessage(\n url,\n bearerToken,\n API_KEY,\n otp,\n phoneNumber\n );\n const data = await response.json();\n return { data };\n } catch (error) {\n console.error('Error sending message:', error.message);\n throw error; // Propagate the error for handling at a higher level\n }\n }\n\n async getBearerToken() {\n const username = process.env.WA_D360_USERNAME;\n const password = process.env.WA_D360_PASSWORD;\n if (!username || !password) {\n throw new Error(\n 'WA_D360_USERNAME and WA_D360_PASSWORD are required to request a WhatsApp token'\n );\n }\n const url = 'https://hub.360dialog.io/api/v2/token';\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n username,\n password,\n }),\n });\n const data = await response.json();\n return data.access_token;\n } catch (error) {\n console.error('Error getting access token:', error.message);\n throw error; // Propagate the error for handling at a higher level\n }\n }\n\n generateOTP() {\n return Math.floor(100000 + Math.random() * 900000);\n }\n\n async sendMessage(url, bearerToken, apiKey, otp, phoneNumber) {\n const templateNamespace = process.env.WA_D360_TEMPLATE_NAMESPACE;\n const templateName = process.env.WA_D360_TEMPLATE_NAME;\n if (!templateNamespace || !templateName) {\n throw new Error(\n 'WA_D360_TEMPLATE_NAMESPACE and WA_D360_TEMPLATE_NAME are required to send a WhatsApp code'\n );\n }\n const payload = {\n messaging_product: 'whatsapp',\n to: phoneNumber,\n type: 'template',\n template: {\n namespace: templateNamespace,\n name: templateName,\n language: {\n code: 'en',\n policy: 'deterministic',\n },\n components: [\n {\n type: 'body',\n parameters: [\n {\n type: 'text',\n text: otp,\n },\n ],\n },\n {\n type: 'button',\n sub_type: 'url',\n index: 0,\n parameters: [\n {\n type: 'text',\n text: otp.toString(),\n },\n ],\n },\n ],\n },\n };\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `bearer ${bearerToken}`,\n 'D360-API-KEY': apiKey,\n },\n body: JSON.stringify(payload),\n });\n\n return response;\n }\n\n async getUserLocationAction(user: UserData) {\n const locationAction = await LocationUpdateAction.select((la) => {\n return [la.agent];\n })\n .where((la) => {\n return la.agent.equals({\n id: user.id,\n });\n })\n .one();\n\n return locationAction;\n }\n\n async updateUserLocation(latitude: number, longitude: number) {\n const auth = this.request.linkedAuth;\n if (!auth || !auth.userAccount) {\n console.warn('No user authenticated.');\n return Auth.enforceSignedIn();\n }\n const user = auth.user;\n\n // find existing instance for the login person\n const locationAction = await this.getUserLocationAction(user);\n\n // if not found, create one and set person property and location, then .save()\n if (!locationAction) {\n const newPlace = await AdministrativeArea.create({\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n });\n\n const newLocationAction = await LocationUpdateAction.create({\n location: {\n id: newPlace.id,\n },\n agent: {\n id: user.id,\n },\n });\n return newLocationAction;\n } else {\n // if existing one found, update location\n const existingLocationAction = await (LocationUpdateAction as any).update(\n locationAction,\n {\n location: {\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n },\n }\n );\n return existingLocationAction;\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import React, { useState } from 'react';
|
|
2
|
+
import { Geolocation } from '@capacitor/geolocation';
|
|
3
|
+
import { Label } from '@_linked/primitives/components/Label';
|
|
4
|
+
import { Switch } from '@_linked/primitives/components/Switch';
|
|
5
|
+
import style from './LocationEnabler.module.css';
|
|
6
|
+
import { useAuth } from '@_linked/auth/hooks/useAuth';
|
|
7
|
+
import { LocationUpdateAction } from '../shapes/LocationUpdateAction.js';
|
|
8
|
+
export const LocationEnabler = ({ onEnableLocationChange, }) => {
|
|
9
|
+
const auth = useAuth();
|
|
10
|
+
const userAccount = auth.userAccount;
|
|
11
|
+
const [enableLocation, setEnableLocation] = useState(Boolean(userAccount === null || userAccount === void 0 ? void 0 : userAccount.enabledLocationServices));
|
|
12
|
+
const getLocation = async () => {
|
|
13
|
+
try {
|
|
14
|
+
const coordinates = await Geolocation.getCurrentPosition();
|
|
15
|
+
if (coordinates) {
|
|
16
|
+
try {
|
|
17
|
+
const { latitude, longitude } = coordinates.coords;
|
|
18
|
+
const result = await LocationUpdateAction.updateUserLocation(latitude, longitude);
|
|
19
|
+
if (result && userAccount) {
|
|
20
|
+
userAccount.enabledLocationServices = true;
|
|
21
|
+
onEnableLocationChange === null || onEnableLocationChange === void 0 ? void 0 : onEnableLocationChange(true);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
console.error('update location error:', err);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
console.warn('request permission error:', err);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const handleEnableLocation = (checked) => {
|
|
34
|
+
setEnableLocation(checked);
|
|
35
|
+
if (!checked) {
|
|
36
|
+
if (userAccount) {
|
|
37
|
+
userAccount.enabledLocationServices = false;
|
|
38
|
+
}
|
|
39
|
+
onEnableLocationChange === null || onEnableLocationChange === void 0 ? void 0 : onEnableLocationChange(false);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
getLocation();
|
|
43
|
+
};
|
|
44
|
+
return (React.createElement("div", { className: style.row },
|
|
45
|
+
React.createElement(Label, { htmlFor: "enable-location-services" }, "Enable location services"),
|
|
46
|
+
React.createElement(Switch, { id: "enable-location-services", checked: Boolean(enableLocation), onCheckedChange: handleEnableLocation })));
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=LocationEnabler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"LocationEnabler.js","sourceRoot":"","sources":["../../../src/components/LocationEnabler.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,KAAK,MAAM,8BAA8B,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,M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IAAI,WAAW,EAAE,CAAC;gBAChB,WAAW,CAAC,uBAAuB,GAAG,KAAK,CAAC;YAC9C,CAAC;YACD,sBAAsB,aAAtB,sBAAsB,uBAAtB,sBAAsB,CAAG,KAAK,CAAC,CAAC;YAChC,OAAO;QACT,CAAC;QACD,WAAW,EAAE,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,CACL,6BAAK,SAAS,EAAE,KAAK,CAAC,GAAG;QACvB,oBAAC,KAAK,IAAC,OAAO,EAAC,0BAA0B,+BAAiC;QAC1E,oBAAC,MAAM,IACL,EAAE,EAAC,0BAA0B,EAC7B,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,EAChC,eAAe,EAAE,oBAAoB,GACrC,CACE,CACP,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useState } from 'react';\nimport { Geolocation } from '@capacitor/geolocation';\nimport { Label } from '@_linked/primitives/components/Label';\nimport { Switch } from '@_linked/primitives/components/Switch';\nimport style from './LocationEnabler.module.css';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport { LocationUpdateAction } from '../shapes/LocationUpdateAction.js';\n\ninterface LocationEnablerProps {\n onEnableLocationChange?: (enabled: boolean) => void;\n}\n\nexport const LocationEnabler = ({\n onEnableLocationChange,\n}: LocationEnablerProps) => {\n const auth = useAuth<any, any>();\n const userAccount = auth.userAccount;\n const [enableLocation, setEnableLocation] = useState<boolean>(\n Boolean(userAccount?.enabledLocationServices)\n );\n const getLocation = async () => {\n try {\n const coordinates = await Geolocation.getCurrentPosition();\n if (coordinates) {\n try {\n const { latitude, longitude } = coordinates.coords;\n const result = await LocationUpdateAction.updateUserLocation(\n latitude,\n longitude\n );\n\n if (result && userAccount) {\n userAccount.enabledLocationServices = true;\n onEnableLocationChange?.(true);\n }\n } catch (err) {\n console.error('update location error:', err);\n }\n }\n } catch (err) {\n console.warn('request permission error:', err);\n }\n };\n const handleEnableLocation = (checked: boolean) => {\n setEnableLocation(checked);\n if (!checked) {\n if (userAccount) {\n userAccount.enabledLocationServices = false;\n }\n onEnableLocationChange?.(false);\n return;\n }\n getLocation();\n };\n\n return (\n <div className={style.row}>\n <Label htmlFor=\"enable-location-services\">Enable location services</Label>\n <Switch\n id=\"enable-location-services\"\n checked={Boolean(enableLocation)}\n onCheckedChange={handleEnableLocation}\n />\n </div>\n );\n};\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import React, { ReactNode } from 'react';
|
|
2
|
+
interface SafeAreaContainerProps {
|
|
3
|
+
children: ReactNode;
|
|
4
|
+
color?: string;
|
|
5
|
+
resetTop?: boolean;
|
|
6
|
+
resetBottom?: boolean;
|
|
7
|
+
fullScreenRoutes?: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare const SafeAreaContainer: ({ children, color, resetTop, resetBottom, fullScreenRoutes, }: SafeAreaContainerProps) => React.JSX.Element;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import React, { useEffect } from 'react';
|
|
2
|
+
import style from './SafeAreaContainer.module.css';
|
|
3
|
+
import { Capacitor } from '@capacitor/core';
|
|
4
|
+
import { SafeArea } from 'capacitor-plugin-safe-area';
|
|
5
|
+
import { useLocation } from 'react-router-dom';
|
|
6
|
+
import { cl } from '@_linked/react/utils/ClassNames';
|
|
7
|
+
export const SafeAreaContainer = ({ children, color, resetTop = false, resetBottom = false, fullScreenRoutes, }) => {
|
|
8
|
+
/**
|
|
9
|
+
* apply safearea for ios and android
|
|
10
|
+
*/
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
if (Capacitor.isNativePlatform()) {
|
|
13
|
+
SafeArea.getSafeAreaInsets().then(({ insets }) => {
|
|
14
|
+
for (const [key, value] of Object.entries(insets)) {
|
|
15
|
+
document.documentElement.style.setProperty(`--safe-area-${key}`, `${value}px`);
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}, []);
|
|
20
|
+
let location = useLocation();
|
|
21
|
+
let backgroundColor = color;
|
|
22
|
+
if (fullScreenRoutes) {
|
|
23
|
+
const isFullScreen = fullScreenRoutes.some((route) => location.pathname.startsWith(route));
|
|
24
|
+
backgroundColor = isFullScreen ? 'transparent' : color;
|
|
25
|
+
}
|
|
26
|
+
// check has color
|
|
27
|
+
const styles = {};
|
|
28
|
+
if (backgroundColor) {
|
|
29
|
+
styles['backgroundColor'] = backgroundColor;
|
|
30
|
+
}
|
|
31
|
+
return (React.createElement("div", { className: cl(style.root, resetTop && style.resetTop, resetBottom && style.resetBottom) },
|
|
32
|
+
!resetTop && (React.createElement("div", { className: cl(style.safearea, style['top']), style: styles })),
|
|
33
|
+
React.createElement("div", null, children),
|
|
34
|
+
!resetBottom && (React.createElement("div", { className: cl(style.safearea, style['bottom']), style: styles }))));
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=SafeAreaContainer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SafeAreaContainer.js","sourceRoot":"","sources":["../../../src/components/SafeAreaContainer.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAa,SAAS,EAAE,MAAM,OAAO,CAAC;AACpD,OAAO,KAAK,MAAM,gCAAgC,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AAUrD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,EAChC,QAAQ,EACR,KAAK,EACL,QAAQ,GAAG,KAAK,EAChB,WAAW,GAAG,KAAK,EACnB,gBAAgB,GACO,EAAE,EAAE;IAC3B;;OAEG;IACH,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,SAAS,CAAC,gBAAgB,EAAE,EAAE,CAAC;YACjC,QAAQ,CAAC,iBAAiB,EAAE,CAAC,I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Q,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,GAAI,CACvE,CACG,CACP,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { ReactNode, useEffect } from 'react';\nimport style from './SafeAreaContainer.module.css';\nimport { Capacitor } from '@capacitor/core';\nimport { SafeArea } from 'capacitor-plugin-safe-area';\nimport { useLocation } from 'react-router-dom';\nimport { cl } from '@_linked/react/utils/ClassNames';\n\ninterface SafeAreaContainerProps {\n children: ReactNode;\n color?: string;\n resetTop?: boolean;\n resetBottom?: boolean;\n fullScreenRoutes?: string[];\n}\n\nexport const SafeAreaContainer = ({\n children,\n color,\n resetTop = false,\n resetBottom = false,\n fullScreenRoutes,\n}: SafeAreaContainerProps) => {\n /**\n * apply safearea for ios and android\n */\n useEffect(() => {\n if (Capacitor.isNativePlatform()) {\n SafeArea.getSafeAreaInsets().then(({ insets }) => {\n for (const [key, value] of Object.entries(insets)) {\n document.documentElement.style.setProperty(\n `--safe-area-${key}`,\n `${value}px`\n );\n }\n });\n }\n }, []);\n\n let location = useLocation();\n\n let backgroundColor = color;\n if (fullScreenRoutes) {\n const isFullScreen = fullScreenRoutes.some((route) =>\n location.pathname.startsWith(route)\n );\n backgroundColor = isFullScreen ? 'transparent' : color;\n }\n // check has color\n const styles = {};\n if (backgroundColor) {\n styles['backgroundColor'] = backgroundColor;\n }\n\n return (\n <div\n className={cl(\n style.root,\n resetTop && style.resetTop,\n resetBottom && style.resetBottom\n )}\n >\n {/* remove background safearea if resetTop is true */}\n {!resetTop && (\n <div className={cl(style.safearea, style['top'])} style={styles} />\n )}\n <div>{children}</div>\n {/* remove background safearea if resetBottom is true */}\n {!resetBottom && (\n <div className={cl(style.safearea, style['bottom'])} style={styles} />\n )}\n </div>\n );\n};\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
:root {
|
|
2
|
+
--ld-safearea-z-index: 1045;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
.root {
|
|
6
|
+
position: relative;
|
|
7
|
+
min-height: 100vh;
|
|
8
|
+
|
|
9
|
+
/*safearea for handle padding side on mobile*/
|
|
10
|
+
padding-top: var(--safe-area-top);
|
|
11
|
+
padding-right: var(--safe-area-right);
|
|
12
|
+
padding-left: var(--safe-area-left);
|
|
13
|
+
padding-bottom: var(--safe-area-bottom);
|
|
14
|
+
|
|
15
|
+
&.resetTop {
|
|
16
|
+
padding-top: 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
&.resetBottom {
|
|
20
|
+
padding-bottom: 0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
.safearea {
|
|
25
|
+
position: fixed;
|
|
26
|
+
left: 0;
|
|
27
|
+
width: 100%;
|
|
28
|
+
z-index: var(--ld-safearea-z-index);
|
|
29
|
+
|
|
30
|
+
&.top {
|
|
31
|
+
top: 0;
|
|
32
|
+
height: var(--safe-area-top);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
&.bottom {
|
|
36
|
+
bottom: 0;
|
|
37
|
+
height: var(--safe-area-bottom);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { Button } from '@_linked/primitives/components/Button';
|
|
3
|
+
import 'react-international-phone/style.css';
|
|
4
|
+
interface SigninWithWhatsappButton extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {
|
|
5
|
+
label?: string;
|
|
6
|
+
onSuccess: (data: boolean) => void;
|
|
7
|
+
}
|
|
8
|
+
export declare const SigninWithWhatsappButton: ({ label, className, onSuccess, ...buttonProps }: SigninWithWhatsappButton) => React.JSX.Element;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import style from './SignInWithWhatsapp.module.css';
|
|
3
|
+
import { Button } from '@_linked/primitives/components/Button';
|
|
4
|
+
import { cl } from '@_linked/react/utils/ClassNames';
|
|
5
|
+
import { packageName } from '../package.js';
|
|
6
|
+
import { Server } from '@_linked/server-utils/utils/Server';
|
|
7
|
+
import { InputOTP, InputOTPGroup, InputOTPSlot, REGEXP_ONLY_DIGITS, } from '@_linked/primitives/components/InputOTP';
|
|
8
|
+
import { PhoneInput } from 'react-international-phone';
|
|
9
|
+
import 'react-international-phone/style.css';
|
|
10
|
+
import libphone from 'google-libphonenumber';
|
|
11
|
+
import { useAuth } from '@_linked/auth/hooks/useAuth';
|
|
12
|
+
import { asset } from '@_linked/core/utils/LinkedFileStorage';
|
|
13
|
+
import { useTranslate } from '@tolgee/react';
|
|
14
|
+
const PhoneNumberUtil = libphone.PhoneNumberUtil;
|
|
15
|
+
export const SigninWithWhatsappButton = ({ label = 'Sign in with Whatsapp', className, onSuccess, ...buttonProps }) => {
|
|
16
|
+
const phoneUtil = PhoneNumberUtil.getInstance();
|
|
17
|
+
const isPhoneValid = (phoneNumber) => {
|
|
18
|
+
try {
|
|
19
|
+
return phoneUtil.isValidNumber(phoneUtil.parseAndKeepRawInput(phoneNumber));
|
|
20
|
+
}
|
|
21
|
+
catch (_a) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const [otpField, setOTPField] = React.useState(false);
|
|
26
|
+
const [phoneNumber, setPhoneNumber] = React.useState('');
|
|
27
|
+
const [phoneNumberField, setPhoneNumberField] = React.useState(false);
|
|
28
|
+
const [isLoading, setLoading] = React.useState(false);
|
|
29
|
+
const [showPhoneError, setShowPhoneError] = React.useState(false);
|
|
30
|
+
const isValid = isPhoneValid(phoneNumber);
|
|
31
|
+
const auth = useAuth();
|
|
32
|
+
const { t } = useTranslate();
|
|
33
|
+
const prefix = 'signIn';
|
|
34
|
+
const validateOTP = (phone, otp) => {
|
|
35
|
+
if (!phone || !otp)
|
|
36
|
+
return;
|
|
37
|
+
Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then((response) => {
|
|
38
|
+
if (response && response.auth) {
|
|
39
|
+
auth.updateAuth({
|
|
40
|
+
auth: response.auth,
|
|
41
|
+
accessToken: response.accessToken,
|
|
42
|
+
refreshToken: response.refreshToken,
|
|
43
|
+
});
|
|
44
|
+
onSuccess(true);
|
|
45
|
+
}
|
|
46
|
+
else if (response === null || response === void 0 ? void 0 : response.error) {
|
|
47
|
+
alert(response.error);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
onSuccess(false);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
const sendWhatsappMessage = (phone) => {
|
|
55
|
+
if (!isValid) {
|
|
56
|
+
setShowPhoneError(true);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
setShowPhoneError(false);
|
|
60
|
+
setLoading(true);
|
|
61
|
+
Server.call(packageName, 'generateOTPWhatsapp', phone)
|
|
62
|
+
.then(() => {
|
|
63
|
+
setOTPField(true);
|
|
64
|
+
})
|
|
65
|
+
.catch(() => {
|
|
66
|
+
alert('Could not send the code. Please try again.');
|
|
67
|
+
})
|
|
68
|
+
.finally(() => {
|
|
69
|
+
setLoading(false);
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
return (React.createElement(React.Fragment, null, !otpField && !phoneNumberField ? (React.createElement(Button, { type: "button", className: cl(style.root, className), onClick: () => setPhoneNumberField(true), variant: "outline", ...buttonProps },
|
|
73
|
+
React.createElement("img", { src: asset('/images/wa_icon.png'), alt: "", className: style.WhatsappIcon }),
|
|
74
|
+
t(prefix + '.whatsapp', label))) : isLoading ? (React.createElement("img", { src: asset('/images/loading.gif'), className: style.loading, alt: "loading" })) : phoneNumberField && !otpField ? (React.createElement("div", { className: style.phoneStep },
|
|
75
|
+
React.createElement("div", { className: style.phoneRow },
|
|
76
|
+
React.createElement(PhoneInput, { className: style.phoneInput, defaultCountry: "us", value: phoneNumber, onChange: (nextPhone) => setPhoneNumber(nextPhone), inputProps: {
|
|
77
|
+
placeholder: '+1 555 123 4567',
|
|
78
|
+
} }),
|
|
79
|
+
React.createElement("button", { type: "button", className: style.signButton, "aria-label": "Send code", onClick: () => sendWhatsappMessage(phoneNumber) },
|
|
80
|
+
React.createElement("img", { src: asset('/images/signButton.png'), alt: "" }))),
|
|
81
|
+
showPhoneError && !isValid ? (React.createElement("div", { className: style.phoneError }, "Phone is not valid")) : null)) : (React.createElement(React.Fragment, null,
|
|
82
|
+
React.createElement("h3", null, "Enter your OTP code"),
|
|
83
|
+
React.createElement(InputOTP, { maxLength: 6, pattern: REGEXP_ONLY_DIGITS, inputMode: "numeric", autoComplete: "one-time-code", onComplete: (otp) => validateOTP(phoneNumber, otp) },
|
|
84
|
+
React.createElement(InputOTPGroup, null, Array.from({ length: 6 }, (_, index) => (React.createElement(InputOTPSlot, { key: index, index: index })))))))));
|
|
85
|
+
};
|
|
86
|
+
//# sourceMappingURL=SignInWithWhatsapp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SignInWithWhatsapp.js","sourceRoot":"","sources":["../../../src/components/SignInWithWhatsapp.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,MAAM,iCAAiC,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EACL,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,qCAAqC,CAAC;AAC7C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,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AwB,CAAC,EAAE,GAAG,EAAC,EAAE,GAAG,CAC7C,CACL;QACL,cAAc,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAC5B,6BAAK,SAAS,EAAE,KAAK,CAAC,UAAU,yBAA0B,CAC3D,CAAC,CAAC,CAAC,IAAI,CACJ,CACP,CAAC,CAAC,CAAC,CACF;QACE,sDAA4B;QAC5B,oBAAC,QAAQ,IACP,SAAS,EAAE,CAAC,EACZ,OAAO,EAAE,kBAAkB,EAC3B,SAAS,EAAC,SAAS,EACnB,YAAY,EAAC,eAAe,EAC5B,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,WAAW,EAAE,GAAG,CAAC;YAElD,oBAAC,aAAa,QACX,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CACvC,oBAAC,YAAY,IAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAI,CAC3C,CAAC,CACY,CACP,CACV,CACJ,CACA,CACJ,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport style from './SignInWithWhatsapp.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { packageName } from '../package.js';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSlot,\n REGEXP_ONLY_DIGITS,\n} from '@_linked/primitives/components/InputOTP';\nimport { PhoneInput } from 'react-international-phone';\nimport 'react-international-phone/style.css';\nimport libphone from 'google-libphonenumber';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport { asset } from '@_linked/core/utils/LinkedFileStorage';\nimport { useTranslate } from '@tolgee/react';\n\nconst PhoneNumberUtil = libphone.PhoneNumberUtil;\n\ninterface SigninWithWhatsappButton\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n onSuccess: (data: boolean) => void;\n}\n\nexport const SigninWithWhatsappButton = ({\n label = 'Sign in with Whatsapp',\n className,\n onSuccess,\n ...buttonProps\n}: SigninWithWhatsappButton) => {\n const phoneUtil = PhoneNumberUtil.getInstance();\n const isPhoneValid = (phoneNumber: string) => {\n try {\n return phoneUtil.isValidNumber(\n phoneUtil.parseAndKeepRawInput(phoneNumber)\n );\n } catch {\n return false;\n }\n };\n const [otpField, setOTPField] = React.useState(false);\n const [phoneNumber, setPhoneNumber] = React.useState('');\n const [phoneNumberField, setPhoneNumberField] = React.useState(false);\n const [isLoading, setLoading] = React.useState(false);\n const [showPhoneError, setShowPhoneError] = React.useState(false);\n const isValid = isPhoneValid(phoneNumber);\n\n const auth = useAuth();\n const { t } = useTranslate();\n const prefix = 'signIn';\n\n const validateOTP = (phone: string, otp: string) => {\n if (!phone || !otp) return;\n Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then(\n (response) => {\n if (response && response.auth) {\n auth.updateAuth({\n auth: response.auth,\n accessToken: response.accessToken,\n refreshToken: response.refreshToken,\n });\n onSuccess(true);\n } else if (response?.error) {\n alert(response.error);\n } else {\n onSuccess(false);\n }\n }\n );\n };\n\n const sendWhatsappMessage = (phone: string) => {\n if (!isValid) {\n setShowPhoneError(true);\n return;\n }\n setShowPhoneError(false);\n setLoading(true);\n Server.call(packageName, 'generateOTPWhatsapp', phone)\n .then(() => {\n setOTPField(true);\n })\n .catch(() => {\n alert('Could not send the code. Please try again.');\n })\n .finally(() => {\n setLoading(false);\n });\n };\n\n return (\n <>\n {!otpField && !phoneNumberField ? (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n onClick={() => setPhoneNumberField(true)}\n variant=\"outline\"\n {...buttonProps}\n >\n <img\n src={asset('/images/wa_icon.png')}\n alt=\"\"\n className={style.WhatsappIcon}\n />\n {t(prefix + '.whatsapp', label)}\n </Button>\n ) : isLoading ? (\n <img\n src={asset('/images/loading.gif')}\n className={style.loading}\n alt=\"loading\"\n />\n ) : phoneNumberField && !otpField ? (\n <div className={style.phoneStep}>\n <div className={style.phoneRow}>\n <PhoneInput\n className={style.phoneInput}\n defaultCountry=\"us\"\n value={phoneNumber}\n onChange={(nextPhone) => setPhoneNumber(nextPhone)}\n inputProps={{\n placeholder: '+1 555 123 4567',\n }}\n />\n <button\n type=\"button\"\n className={style.signButton}\n aria-label=\"Send code\"\n onClick={() => sendWhatsappMessage(phoneNumber)}\n >\n <img src={asset('/images/signButton.png')} alt=\"\" />\n </button>\n </div>\n {showPhoneError && !isValid ? (\n <div className={style.phoneError}>Phone is not valid</div>\n ) : null}\n </div>\n ) : (\n <>\n <h3>Enter your OTP code</h3>\n <InputOTP\n maxLength={6}\n pattern={REGEXP_ONLY_DIGITS}\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n onComplete={(otp) => validateOTP(phoneNumber, otp)}\n >\n <InputOTPGroup>\n {Array.from({ length: 6 }, (_, index) => (\n <InputOTPSlot key={index} index={index} />\n ))}\n </InputOTPGroup>\n </InputOTP>\n </>\n )}\n </>\n );\n};\n"]}
|