omnibiofex 2.8.5 → 4.0.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/src/user.js ADDED
@@ -0,0 +1,94 @@
1
+ const Conf = require('conf');
2
+
3
+ const config = new Conf({
4
+ projectName: 'omnibiofex',
5
+ schema: {
6
+ token: { type: 'string' },
7
+ refreshToken: { type: 'string' },
8
+ expiresAt: { type: 'number' },
9
+ userEmail: { type: 'string' },
10
+ userUid: { type: 'string' },
11
+ userName: { type: 'string' }
12
+ }
13
+ });
14
+
15
+ function base64UrlDecode(str) {
16
+ let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
17
+ while (base64.length % 4) base64 += '=';
18
+ return Buffer.from(base64, 'base64').toString('utf8');
19
+ }
20
+
21
+ function decodeToken() {
22
+ const token = config.get('token');
23
+ if (!token) return null;
24
+ try {
25
+ const parts = token.split('.');
26
+ if (parts.length !== 3) return null;
27
+ const data = JSON.parse(base64UrlDecode(parts[1]));
28
+ return {
29
+ uid: data.user_id || data.sub,
30
+ email: data.email,
31
+ exp: data.exp,
32
+ name: data.name
33
+ };
34
+ } catch (error) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function getCurrentUserUid() {
40
+ return config.get('userUid') || decodeToken()?.uid || null;
41
+ }
42
+
43
+ function getCurrentUserEmail() {
44
+ return config.get('userEmail') || decodeToken()?.email || null;
45
+ }
46
+
47
+ function getCurrentUserName() {
48
+ return config.get('userName') || decodeToken()?.name || null;
49
+ }
50
+
51
+ function getToken() {
52
+ return config.get('token');
53
+ }
54
+
55
+ function getRefreshToken() {
56
+ return config.get('refreshToken');
57
+ }
58
+
59
+ function setToken(token, refreshToken, expiresAt, userInfo = {}) {
60
+ config.set('token', token);
61
+ if (refreshToken) config.set('refreshToken', refreshToken);
62
+ if (expiresAt) config.set('expiresAt', expiresAt);
63
+ if (userInfo.email) config.set('userEmail', userInfo.email);
64
+ if (userInfo.uid) config.set('userUid', userInfo.uid);
65
+ if (userInfo.name) config.set('userName', userInfo.name);
66
+ }
67
+
68
+ function clearTokens() {
69
+ config.delete('token');
70
+ config.delete('refreshToken');
71
+ config.delete('expiresAt');
72
+ config.delete('userEmail');
73
+ config.delete('userUid');
74
+ config.delete('userName');
75
+ }
76
+
77
+ function isTokenExpired() {
78
+ const expiresAt = config.get('expiresAt');
79
+ if (!expiresAt) return true;
80
+ return expiresAt < Math.floor(Date.now() / 1000);
81
+ }
82
+
83
+ module.exports = {
84
+ config,
85
+ decodeToken,
86
+ getCurrentUserUid,
87
+ getCurrentUserEmail,
88
+ getCurrentUserName,
89
+ getToken,
90
+ getRefreshToken,
91
+ setToken,
92
+ clearTokens,
93
+ isTokenExpired
94
+ };