@gofreego/tsutils 0.1.13 → 0.1.14

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/dist/index.js CHANGED
@@ -1281,169 +1281,169 @@ function formatDate(date, options = {
1281
1281
  const dateObj = typeof date === "string" || typeof date === "number" ? new Date(date) : date;
1282
1282
  return new Intl.DateTimeFormat("en-US", options).format(dateObj);
1283
1283
  }
1284
- function getCookie(name) {
1285
- if (typeof document === "undefined") return null;
1286
- const value = `; ${document.cookie}`;
1287
- const parts = value.split(`; ${name}=`);
1288
- if (parts.length === 2) return parts.pop()?.split(";").shift() || null;
1289
- return null;
1290
- }
1291
- function decodeJWT(token) {
1292
- try {
1293
- const base64Url = token.split(".")[1];
1294
- if (!base64Url) return null;
1295
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
1296
- const jsonPayload = decodeURIComponent(
1297
- window.atob(base64).split("").map(function(c) {
1298
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
1299
- }).join("")
1300
- );
1301
- return JSON.parse(jsonPayload);
1302
- } catch (e) {
1303
- return null;
1284
+
1285
+ // src/auth/sessionManager.ts
1286
+ var SESSION_KEY = "session_details";
1287
+ var SessionManager = class _SessionManager {
1288
+ constructor(client, key = SESSION_KEY) {
1289
+ this.cache = null;
1290
+ this.client = client;
1291
+ this.key = key;
1304
1292
  }
1305
- }
1306
- var AuthContext = react.createContext({
1307
- isAuthenticated: false,
1308
- isLoading: true
1309
- });
1310
- var AuthProvider = ({
1311
- cookieName = "authorization",
1312
- redirectUrl,
1313
- children,
1314
- onAuthFail,
1315
- onAuthSuccess,
1316
- loadingElement = null
1317
- }) => {
1318
- const [authState, setAuthState] = react.useState({
1319
- isAuthenticated: false,
1320
- isLoading: true
1321
- // starts loading until cookie check completes
1322
- });
1323
- const [authFailed, setAuthFailed] = react.useState(false);
1324
- react.useEffect(() => {
1325
- const verifyAuth = () => {
1326
- const token = getCookie(cookieName);
1327
- if (!token) {
1328
- handleFail();
1329
- return;
1330
- }
1331
- const decoded = decodeJWT(token);
1332
- if (!decoded) {
1333
- handleFail();
1334
- return;
1335
- }
1336
- if (decoded.exp) {
1337
- const expirationDate = new Date(decoded.exp * 1e3);
1338
- if (expirationDate < /* @__PURE__ */ new Date()) {
1339
- handleFail();
1340
- return;
1341
- }
1342
- }
1343
- setAuthState({
1344
- isAuthenticated: true,
1345
- isLoading: false
1346
- });
1347
- if (onAuthSuccess) {
1348
- onAuthSuccess();
1349
- }
1350
- };
1351
- verifyAuth();
1352
- }, [cookieName]);
1353
- const handleFail = () => {
1354
- setAuthState({
1355
- isAuthenticated: false,
1356
- isLoading: false
1357
- });
1358
- setAuthFailed(true);
1359
- if (onAuthFail) {
1360
- onAuthFail();
1361
- } else if (redirectUrl && typeof window !== "undefined") {
1362
- window.location.href = redirectUrl;
1293
+ static getInstance(client) {
1294
+ if (!_SessionManager.instance) {
1295
+ _SessionManager.instance = new _SessionManager(client);
1363
1296
  }
1364
- };
1365
- if (authState.isLoading || authFailed && !onAuthFail) {
1366
- return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: loadingElement });
1297
+ return _SessionManager.instance;
1367
1298
  }
1368
- if (authFailed && onAuthFail) {
1369
- return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children });
1299
+ save(session) {
1300
+ this.cache = session;
1301
+ LocalStorage.setItem(this.key, session);
1302
+ this.setAuthToken(session.accessToken);
1303
+ }
1304
+ patch(updates) {
1305
+ const current = this.get();
1306
+ if (!current) return;
1307
+ const updated = { ...current, ...updates };
1308
+ this.cache = updated;
1309
+ LocalStorage.setItem(this.key, updated);
1310
+ if (updates.accessToken) {
1311
+ this.setAuthToken(updates.accessToken);
1312
+ }
1313
+ }
1314
+ clear() {
1315
+ this.cache = null;
1316
+ LocalStorage.removeItem(this.key);
1317
+ this.clearAuthToken();
1318
+ }
1319
+ get() {
1320
+ if (this.cache !== null) return this.cache;
1321
+ this.cache = LocalStorage.getItem(this.key);
1322
+ return this.cache;
1323
+ }
1324
+ getAccessToken() {
1325
+ return this.get()?.accessToken || void 0;
1326
+ }
1327
+ getRefreshToken() {
1328
+ return this.get()?.refreshToken || void 0;
1329
+ }
1330
+ getSessionId() {
1331
+ return this.get()?.sessionId || void 0;
1332
+ }
1333
+ isAuthenticated() {
1334
+ const session = this.get();
1335
+ if (!session?.accessToken) return false;
1336
+ return Number(session.expiresAt) > Date.now() / 1e3;
1337
+ }
1338
+ initialize() {
1339
+ const session = this.get();
1340
+ if (session?.accessToken && Number(session.expiresAt) > Date.now() / 1e3) {
1341
+ this.setAuthToken(session.accessToken);
1342
+ } else {
1343
+ this.clear();
1344
+ }
1345
+ }
1346
+ setAuthToken(token) {
1347
+ this.client.setDefaultHeader("Authorization", `Bearer ${token}`);
1348
+ }
1349
+ clearAuthToken() {
1350
+ this.client.removeDefaultHeader("Authorization");
1370
1351
  }
1371
- return /* @__PURE__ */ jsxRuntime.jsx(AuthContext.Provider, { value: authState, children });
1372
- };
1373
- var useAuth = () => {
1374
- return react.useContext(AuthContext);
1375
1352
  };
1376
1353
 
1377
- // src/auth/PermissionManager.ts
1378
- var PERMISSIONS_STORAGE_KEY = "auth_permissions";
1379
- var PermissionManager = class {
1380
- /**
1381
- * Saves an array of permission strings to local storage.
1382
- * @param permissions Array of permission strings.
1383
- */
1384
- static setPermissions(permissions) {
1385
- this.cachedPermissions = new Set(permissions);
1386
- if (typeof window === "undefined") return;
1387
- try {
1388
- localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
1389
- } catch (error) {
1390
- console.error("Failed to save permissions to localStorage", error);
1354
+ // src/auth/AuthService.ts
1355
+ var BASE_URL = "/openauth/v1";
1356
+ var AuthService = class _AuthService {
1357
+ constructor(client) {
1358
+ this.client = client;
1359
+ this.sessionManager = SessionManager.getInstance(client);
1360
+ }
1361
+ static getInstance(client) {
1362
+ if (!_AuthService.instance) {
1363
+ _AuthService.instance = new _AuthService(client);
1391
1364
  }
1365
+ return _AuthService.instance;
1392
1366
  }
1393
- /**
1394
- * Retrieves the currently stored permissions from local storage or memory cache.
1395
- * @returns Array of permission strings, or an empty array if none exist.
1396
- */
1397
- static getPermissions() {
1398
- if (this.cachedPermissions !== null) {
1399
- return Array.from(this.cachedPermissions);
1367
+ async signIn(request) {
1368
+ const response = await this.client.post(
1369
+ `${BASE_URL}/auth/signin`,
1370
+ request
1371
+ );
1372
+ if (response.data.accessToken) {
1373
+ this.sessionManager.save(response.data);
1374
+ }
1375
+ return response.data;
1376
+ }
1377
+ async refreshToken(request) {
1378
+ const refreshToken = this.sessionManager.getRefreshToken();
1379
+ if (!refreshToken) {
1380
+ throw new Error("No refresh token available");
1381
+ }
1382
+ const response = await this.client.post(
1383
+ `${BASE_URL}/auth/refresh`,
1384
+ { refreshToken, ...request }
1385
+ );
1386
+ if (response.data.accessToken) {
1387
+ this.sessionManager.patch({
1388
+ accessToken: response.data.accessToken,
1389
+ refreshToken: response.data.refreshToken
1390
+ });
1400
1391
  }
1401
- if (typeof window === "undefined") return [];
1392
+ return response.data;
1393
+ }
1394
+ async logout(request) {
1402
1395
  try {
1403
- const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
1404
- if (!stored) {
1405
- this.cachedPermissions = /* @__PURE__ */ new Set();
1406
- return [];
1407
- }
1408
- const parsed = JSON.parse(stored);
1409
- const permissionsArray = Array.isArray(parsed) ? parsed : [];
1410
- this.cachedPermissions = new Set(permissionsArray);
1411
- return permissionsArray;
1412
- } catch (error) {
1413
- console.error("Failed to parse permissions from localStorage", error);
1414
- this.cachedPermissions = /* @__PURE__ */ new Set();
1415
- return [];
1396
+ request.sessionId = this.sessionManager.getSessionId();
1397
+ const response = await this.client.post(
1398
+ `${BASE_URL}/auth/logout`,
1399
+ request || {}
1400
+ );
1401
+ return response.data;
1402
+ } finally {
1403
+ this.sessionManager.clear();
1416
1404
  }
1417
1405
  }
1418
- /**
1419
- * Clears all stored permissions from memory and local storage.
1420
- */
1421
- static clearPermissions() {
1422
- this.cachedPermissions = null;
1423
- if (typeof window === "undefined") return;
1424
- localStorage.removeItem(PERMISSIONS_STORAGE_KEY);
1406
+ async generateLoginToken(request) {
1407
+ const response = await this.client.put(
1408
+ `${BASE_URL}/auth/login-token`,
1409
+ request ?? {}
1410
+ );
1411
+ return response.data;
1425
1412
  }
1426
- /**
1427
- * Checks whether the given permission string exists in the currently stored permissions.
1428
- * @param permission The permission string to check for.
1429
- * @returns True if the permission exists, false otherwise.
1430
- */
1431
- static hasPermission(permission) {
1432
- if (this.cachedPermissions === null) {
1433
- this.getPermissions();
1413
+ async signInWithLoginToken(request) {
1414
+ const response = await this.client.post(
1415
+ `${BASE_URL}/auth/signin-with-token`,
1416
+ request
1417
+ );
1418
+ if (response.data.accessToken) {
1419
+ this.sessionManager.save(response.data);
1434
1420
  }
1435
- return this.cachedPermissions.has(permission);
1421
+ return response.data;
1422
+ }
1423
+ isAuthenticated() {
1424
+ return this.sessionManager.isAuthenticated();
1425
+ }
1426
+ getAccessToken() {
1427
+ return this.sessionManager.getAccessToken();
1428
+ }
1429
+ getSessionDetails() {
1430
+ return this.sessionManager.get();
1431
+ }
1432
+ getSessionId() {
1433
+ return this.sessionManager.getSessionId();
1434
+ }
1435
+ initializeAuth() {
1436
+ this.sessionManager.initialize();
1436
1437
  }
1437
1438
  };
1438
- PermissionManager.cachedPermissions = null;
1439
1439
 
1440
- exports.AuthProvider = AuthProvider;
1440
+ exports.AuthService = AuthService;
1441
1441
  exports.ConfirmDialog = ConfirmDialog;
1442
1442
  exports.HttpClient = HttpClient;
1443
1443
  exports.LocalStorage = LocalStorage;
1444
1444
  exports.NotificationProvider = NotificationProvider;
1445
- exports.PermissionManager = PermissionManager;
1446
1445
  exports.ReadmeViewer = ReadmeViewer_default;
1446
+ exports.SessionManager = SessionManager;
1447
1447
  exports.SidebarLayout = SidebarLayout;
1448
1448
  exports.ThemeProvider = ThemeProvider;
1449
1449
  exports.ThemeToggle = ThemeToggle;
@@ -1463,7 +1463,6 @@ exports.spacing = spacing;
1463
1463
  exports.throttle = throttle;
1464
1464
  exports.tokens = tokens_exports;
1465
1465
  exports.transition = transition;
1466
- exports.useAuth = useAuth;
1467
1466
  exports.useNotification = useNotification;
1468
1467
  exports.useTheme = useTheme;
1469
1468
  exports.zIndex = zIndex;