UNPKG

@srfoster/one-backend-react

Version:

React components and hooks for One Backend authentication and data management

946 lines (929 loc) 44.6 kB
import { jsx, jsxs, Fragment } from 'react/jsx-runtime'; import { createContext, useReducer, useMemo, useEffect, useContext, useState } from 'react'; import axios from 'axios'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var OneBackendClient = /** @class */ (function () { function OneBackendClient(config) { var _this = this; this.token = null; this.config = config; this.api = axios.create({ baseURL: OneBackendClient.API_URL, headers: { 'Content-Type': 'application/json', }, }); // Add request interceptor to include auth token this.api.interceptors.request.use(function (config) { if (_this.token) { config.headers.Authorization = "Bearer ".concat(_this.token); } return config; }); // Load token from localStorage if available if (typeof window !== 'undefined') { var storedToken = localStorage.getItem("onebackend_token_".concat(this.config.appId)); if (storedToken) { this.token = storedToken; } } } OneBackendClient.prototype.setToken = function (token) { this.token = token; if (typeof window !== 'undefined') { if (token) { localStorage.setItem("onebackend_token_".concat(this.config.appId), token); } else { localStorage.removeItem("onebackend_token_".concat(this.config.appId)); } } }; OneBackendClient.prototype.getToken = function () { return this.token; }; // JWT decoding utility (simple, no signature verification on client) OneBackendClient.prototype.decodeJWT = function (token) { try { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(window.atob(base64) .split('') .map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join('')); return JSON.parse(jsonPayload); } catch (error) { console.error('Error decoding JWT:', error); return null; } }; // Check if token is expired OneBackendClient.prototype.isTokenExpired = function (payload) { var now = Math.floor(Date.now() / 1000); return payload.exp < now; }; // Get current user from stored token OneBackendClient.prototype.getCurrentUser = function () { var token = this.getToken(); if (!token) return null; var payload = this.decodeJWT(token); if (!payload || this.isTokenExpired(payload)) { // Token is invalid or expired, clear it this.setToken(null); return null; } // Convert JWT payload to User object var user = { id: payload.userId, email: payload.email, appId: payload.appId, roles: payload.roles, isActive: true, // Assume active if token is valid createdAt: '', // JWT doesn't contain these updatedAt: '', }; return user; }; // Authentication methods OneBackendClient.prototype.register = function (data) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post('/auth/register', __assign(__assign({}, data), { appId: this.config.appId }))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.login = function (credentials) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post('/auth/login', __assign(__assign({}, credentials), { appId: this.config.appId }))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.logout = function () { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post('/auth/logout')]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.refreshToken = function () { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post('/auth/refresh')]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; // CRUD operations OneBackendClient.prototype.getRecords = function (resourceType, options) { return __awaiter(this, void 0, void 0, function () { var params, response; return __generator(this, function (_a) { switch (_a.label) { case 0: params = new URLSearchParams(); if (options === null || options === void 0 ? void 0 : options.page) params.append('page', options.page.toString()); if (options === null || options === void 0 ? void 0 : options.limit) params.append('limit', options.limit.toString()); if (options === null || options === void 0 ? void 0 : options.filters) { Object.entries(options.filters).forEach(function (_a) { var key = _a[0], value = _a[1]; params.append("filter[".concat(key, "]"), value); }); } return [4 /*yield*/, this.api.get("/api/".concat(this.config.appId, "/").concat(resourceType, "?").concat(params.toString()))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.getRecord = function (resourceType, id) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.get("/api/".concat(this.config.appId, "/").concat(resourceType, "/").concat(id))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.createRecord = function (resourceType, request) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post("/api/".concat(this.config.appId, "/").concat(resourceType), request)]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.updateRecord = function (resourceType, id, request) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.put("/api/".concat(this.config.appId, "/").concat(resourceType, "/").concat(id), request)]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.deleteRecord = function (resourceType, id) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.delete("/api/".concat(this.config.appId, "/").concat(resourceType, "/").concat(id))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.deleteRecords = function (resourceType, ids) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.delete("/api/".concat(this.config.appId, "/").concat(resourceType), { data: { ids: ids } })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; // File operations OneBackendClient.prototype.getUploadUrl = function (fileName, fileType) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.post("/files/".concat(this.config.appId, "/upload-url"), { fileName: fileName, fileType: fileType, })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.getDownloadUrl = function (fileId) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.get("/files/".concat(this.config.appId, "/download-url/").concat(fileId))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; OneBackendClient.prototype.deleteFile = function (fileId) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.api.delete("/files/".concat(this.config.appId, "/").concat(fileId))]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; // Upload file to S3 using presigned URL OneBackendClient.prototype.uploadFile = function (file) { return __awaiter(this, void 0, void 0, function () { var uploadUrlResponse, _a, uploadUrl, fileId, key; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.getUploadUrl(file.name, file.type)]; case 1: uploadUrlResponse = _b.sent(); if (!uploadUrlResponse.success || !uploadUrlResponse.data) { throw new Error('Failed to get upload URL'); } _a = uploadUrlResponse.data, uploadUrl = _a.uploadUrl, fileId = _a.fileId, key = _a.key; // Upload to S3 return [4 /*yield*/, axios.put(uploadUrl, file, { headers: { 'Content-Type': file.type, }, })]; case 2: // Upload to S3 _b.sent(); return [2 /*return*/, { fileId: fileId, key: key }]; } }); }); }; OneBackendClient.API_URL = 'https://0xyjq9punk.execute-api.us-west-2.amazonaws.com/dev'; return OneBackendClient; }()); var AuthContext = createContext(undefined); var authReducer = function (state, action) { switch (action.type) { case 'SET_LOADING': return __assign(__assign({}, state), { isLoading: action.payload }); case 'SET_AUTH': return __assign(__assign({}, state), { user: action.payload.user, token: action.payload.token, isAuthenticated: true, isLoading: false }); case 'CLEAR_AUTH': return __assign(__assign({}, state), { user: null, token: null, isAuthenticated: false, isLoading: false }); case 'SET_USER': return __assign(__assign({}, state), { user: action.payload }); default: return state; } }; var AuthProvider = function (_a) { var children = _a.children, config = _a.config; var _b = useReducer(authReducer, { user: null, token: null, isLoading: true, isAuthenticated: false, }), state = _b[0], dispatch = _b[1]; var client = useMemo(function () { return new OneBackendClient(config); }, [config]); useEffect(function () { // Check if user is already authenticated var user = client.getCurrentUser(); if (user) { var token = client.getToken(); if (token) { dispatch({ type: 'SET_AUTH', payload: { user: user, token: token } }); } else { dispatch({ type: 'SET_LOADING', payload: false }); } } else { dispatch({ type: 'SET_LOADING', payload: false }); } }, []); // Empty dependency array - only run once on mount var login = function (email, password) { return __awaiter(void 0, void 0, void 0, function () { var response, _a, token, user, error_1; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, 3, 4]); dispatch({ type: 'SET_LOADING', payload: true }); return [4 /*yield*/, client.login({ email: email, password: password })]; case 1: response = _b.sent(); if (response.success && response.data) { _a = response.data, token = _a.token, user = _a.user; client.setToken(token); dispatch({ type: 'SET_AUTH', payload: { user: user, token: token } }); return [2 /*return*/, true]; } return [2 /*return*/, false]; case 2: error_1 = _b.sent(); console.error('Login error:', error_1); return [2 /*return*/, false]; case 3: dispatch({ type: 'SET_LOADING', payload: false }); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var register = function (email, password, firstName, lastName) { return __awaiter(void 0, void 0, void 0, function () { var response, _a, token, user, error_2; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, 3, 4]); dispatch({ type: 'SET_LOADING', payload: true }); return [4 /*yield*/, client.register({ email: email, password: password, appId: config.appId, firstName: firstName, lastName: lastName, })]; case 1: response = _b.sent(); if (response.success && response.data) { _a = response.data, token = _a.token, user = _a.user; client.setToken(token); dispatch({ type: 'SET_AUTH', payload: { user: user, token: token } }); return [2 /*return*/, true]; } return [2 /*return*/, false]; case 2: error_2 = _b.sent(); console.error('Registration error:', error_2); return [2 /*return*/, false]; case 3: dispatch({ type: 'SET_LOADING', payload: false }); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var logout = function () { client.setToken(null); dispatch({ type: 'CLEAR_AUTH' }); }; var value = __assign(__assign({}, state), { login: login, register: register, logout: logout, client: client }); return jsx(AuthContext.Provider, { value: value, children: children }); }; var useAuth = function () { var context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }; var useData = function (resourceType) { var client = useAuth().client; var _a = useState([]), data = _a[0], setData = _a[1]; var _b = useState(false), loading = _b[0], setLoading = _b[1]; var _c = useState(null), error = _c[0], setError = _c[1]; var _d = useState({ page: 1, limit: 20, total: 0, hasMore: false, }), pagination = _d[0], setPagination = _d[1]; var fetchData = function () { var args_1 = []; for (var _i = 0; _i < arguments.length; _i++) { args_1[_i] = arguments[_i]; } return __awaiter(void 0, __spreadArray([], args_1, true), void 0, function (page, limit, filters) { var response, err_1; if (page === void 0) { page = 1; } if (limit === void 0) { limit = 20; } return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setLoading(true); setError(null); return [4 /*yield*/, client.getRecords(resourceType, { page: page, limit: limit, filters: filters })]; case 1: response = _a.sent(); if (response.success && response.data) { setData(response.data.items); setPagination(response.data.pagination); } else { setError(response.message || 'Failed to fetch data'); } return [3 /*break*/, 4]; case 2: err_1 = _a.sent(); setError(err_1 instanceof Error ? err_1.message : 'An error occurred'); return [3 /*break*/, 4]; case 3: setLoading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var createRecord = function (request) { return __awaiter(void 0, void 0, void 0, function () { var response_1, err_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setLoading(true); setError(null); return [4 /*yield*/, client.createRecord(resourceType, request)]; case 1: response_1 = _a.sent(); if (response_1.success && response_1.data) { // Add to local state setData(function (prev) { return __spreadArray([response_1.data], prev, true); }); return [2 /*return*/, response_1.data]; } else { setError(response_1.message || 'Failed to create record'); return [2 /*return*/, null]; } case 2: err_2 = _a.sent(); setError(err_2 instanceof Error ? err_2.message : 'An error occurred'); return [2 /*return*/, null]; case 3: setLoading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var updateRecord = function (id, request) { return __awaiter(void 0, void 0, void 0, function () { var response_2, err_3; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setLoading(true); setError(null); return [4 /*yield*/, client.updateRecord(resourceType, id, request)]; case 1: response_2 = _a.sent(); if (response_2.success && response_2.data) { // Update local state setData(function (prev) { return prev.map(function (item) { return item.id === id ? response_2.data : item; }); }); return [2 /*return*/, response_2.data]; } else { setError(response_2.message || 'Failed to update record'); return [2 /*return*/, null]; } case 2: err_3 = _a.sent(); setError(err_3 instanceof Error ? err_3.message : 'An error occurred'); return [2 /*return*/, null]; case 3: setLoading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var deleteRecord = function (id) { return __awaiter(void 0, void 0, void 0, function () { var response, err_4; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setLoading(true); setError(null); return [4 /*yield*/, client.deleteRecord(resourceType, id)]; case 1: response = _a.sent(); if (response.success) { // Remove from local state setData(function (prev) { return prev.filter(function (item) { return item.id !== id; }); }); return [2 /*return*/, true]; } else { setError(response.message || 'Failed to delete record'); return [2 /*return*/, false]; } case 2: err_4 = _a.sent(); setError(err_4 instanceof Error ? err_4.message : 'An error occurred'); return [2 /*return*/, false]; case 3: setLoading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var deleteRecords = function (ids) { return __awaiter(void 0, void 0, void 0, function () { var response, deletedIds_1, err_5, errorMessage; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setLoading(true); setError(null); return [4 /*yield*/, client.deleteRecords(resourceType, ids)]; case 1: response = _a.sent(); if (response.success && response.data) { deletedIds_1 = response.data.details.deletedIds; setData(function (prev) { return prev.filter(function (item) { return !deletedIds_1.includes(item.id); }); }); return [2 /*return*/, { success: true, deleted: response.data.deleted, failed: response.data.failed, details: response.data.details }]; } else { setError(response.message || 'Failed to delete records'); return [2 /*return*/, { success: false, deleted: 0, failed: ids.length }]; } case 2: err_5 = _a.sent(); errorMessage = err_5 instanceof Error ? err_5.message : 'An error occurred'; setError(errorMessage); return [2 /*return*/, { success: false, deleted: 0, failed: ids.length }]; case 3: setLoading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var refresh = function () { fetchData(pagination.page, pagination.limit); }; useEffect(function () { fetchData(); }, [resourceType]); return { data: data, loading: loading, error: error, pagination: pagination, fetchData: fetchData, createRecord: createRecord, updateRecord: updateRecord, deleteRecord: deleteRecord, deleteRecords: deleteRecords, refresh: refresh, }; }; var useFileUpload = function () { var client = useAuth().client; var _a = useState(false), uploading = _a[0], setUploading = _a[1]; var _b = useState(null), error = _b[0], setError = _b[1]; var uploadFile = function (file) { return __awaiter(void 0, void 0, void 0, function () { var result, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); setUploading(true); setError(null); return [4 /*yield*/, client.uploadFile(file)]; case 1: result = _a.sent(); return [2 /*return*/, result]; case 2: err_1 = _a.sent(); setError(err_1 instanceof Error ? err_1.message : 'Upload failed'); return [2 /*return*/, null]; case 3: setUploading(false); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var getDownloadUrl = function (fileId) { return __awaiter(void 0, void 0, void 0, function () { var response, err_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); setError(null); return [4 /*yield*/, client.getDownloadUrl(fileId)]; case 1: response = _a.sent(); if (response.success && response.data) { return [2 /*return*/, response.data.downloadUrl]; } else { setError(response.message || 'Failed to get download URL'); return [2 /*return*/, null]; } case 2: err_2 = _a.sent(); setError(err_2 instanceof Error ? err_2.message : 'An error occurred'); return [2 /*return*/, null]; case 3: return [2 /*return*/]; } }); }); }; var deleteFile = function (fileId) { return __awaiter(void 0, void 0, void 0, function () { var response, err_3; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); setError(null); return [4 /*yield*/, client.deleteFile(fileId)]; case 1: response = _a.sent(); if (response.success) { return [2 /*return*/, true]; } else { setError(response.message || 'Failed to delete file'); return [2 /*return*/, false]; } case 2: err_3 = _a.sent(); setError(err_3 instanceof Error ? err_3.message : 'An error occurred'); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; return { uploadFile: uploadFile, getDownloadUrl: getDownloadUrl, deleteFile: deleteFile, uploading: uploading, error: error, }; }; var LoginForm = function (_a) { var onSuccess = _a.onSuccess, onError = _a.onError, className = _a.className; var _b = useAuth(), login = _b.login, isLoading = _b.isLoading; var _c = useState(''), email = _c[0], setEmail = _c[1]; var _d = useState(''), password = _d[0], setPassword = _d[1]; var _e = useState(''), error = _e[0], setError = _e[1]; var handleSubmit = function (e) { return __awaiter(void 0, void 0, void 0, function () { var errorMsg, success, errorMsg; return __generator(this, function (_a) { switch (_a.label) { case 0: e.preventDefault(); setError(''); if (!email || !password) { errorMsg = 'Please fill in all fields'; setError(errorMsg); onError === null || onError === void 0 ? void 0 : onError(errorMsg); return [2 /*return*/]; } return [4 /*yield*/, login(email, password)]; case 1: success = _a.sent(); if (success) { onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(); } else { errorMsg = 'Invalid email or password'; setError(errorMsg); onError === null || onError === void 0 ? void 0 : onError(errorMsg); } return [2 /*return*/]; } }); }); }; return (jsxs("form", { onSubmit: handleSubmit, className: className, children: [jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "email", style: { display: 'block', marginBottom: '0.5rem' }, children: "Email" }), jsx("input", { type: "email", id: "email", value: email, onChange: function (e) { return setEmail(e.target.value); }, required: true, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "password", style: { display: 'block', marginBottom: '0.5rem' }, children: "Password" }), jsx("input", { type: "password", id: "password", value: password, onChange: function (e) { return setPassword(e.target.value); }, required: true, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), error && (jsx("div", { style: { color: 'red', marginBottom: '1rem', fontSize: '0.875rem' }, children: error })), jsx("button", { type: "submit", disabled: isLoading, style: { width: '100%', padding: '0.75rem', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: isLoading ? 'not-allowed' : 'pointer', opacity: isLoading ? 0.6 : 1, }, children: isLoading ? 'Logging in...' : 'Login' })] })); }; var RegisterForm = function (_a) { var onSuccess = _a.onSuccess, onError = _a.onError, className = _a.className, _b = _a.showNameFields, showNameFields = _b === void 0 ? true : _b; var _c = useAuth(), register = _c.register, isLoading = _c.isLoading; var _d = useState({ email: '', password: '', confirmPassword: '', firstName: '', lastName: '', }), formData = _d[0], setFormData = _d[1]; var _e = useState(''), error = _e[0], setError = _e[1]; var handleChange = function (e) { setFormData(function (prev) { var _a; return (__assign(__assign({}, prev), (_a = {}, _a[e.target.name] = e.target.value, _a))); }); }; var handleSubmit = function (e) { return __awaiter(void 0, void 0, void 0, function () { var errorMsg, errorMsg, success, errorMsg; return __generator(this, function (_a) { switch (_a.label) { case 0: e.preventDefault(); setError(''); if (!formData.email || !formData.password) { errorMsg = 'Email and password are required'; setError(errorMsg); onError === null || onError === void 0 ? void 0 : onError(errorMsg); return [2 /*return*/]; } if (formData.password !== formData.confirmPassword) { errorMsg = 'Passwords do not match'; setError(errorMsg); onError === null || onError === void 0 ? void 0 : onError(errorMsg); return [2 /*return*/]; } return [4 /*yield*/, register(formData.email, formData.password, formData.firstName || undefined, formData.lastName || undefined)]; case 1: success = _a.sent(); if (success) { onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(); } else { errorMsg = 'Registration failed. Please try again.'; setError(errorMsg); onError === null || onError === void 0 ? void 0 : onError(errorMsg); } return [2 /*return*/]; } }); }); }; return (jsxs("form", { onSubmit: handleSubmit, className: className, children: [showNameFields && (jsxs(Fragment, { children: [jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "firstName", style: { display: 'block', marginBottom: '0.5rem' }, children: "First Name" }), jsx("input", { type: "text", id: "firstName", name: "firstName", value: formData.firstName, onChange: handleChange, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "lastName", style: { display: 'block', marginBottom: '0.5rem' }, children: "Last Name" }), jsx("input", { type: "text", id: "lastName", name: "lastName", value: formData.lastName, onChange: handleChange, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] })] })), jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "email", style: { display: 'block', marginBottom: '0.5rem' }, children: "Email *" }), jsx("input", { type: "email", id: "email", name: "email", value: formData.email, onChange: handleChange, required: true, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "password", style: { display: 'block', marginBottom: '0.5rem' }, children: "Password *" }), jsx("input", { type: "password", id: "password", name: "password", value: formData.password, onChange: handleChange, required: true, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), jsxs("div", { style: { marginBottom: '1rem' }, children: [jsx("label", { htmlFor: "confirmPassword", style: { display: 'block', marginBottom: '0.5rem' }, children: "Confirm Password *" }), jsx("input", { type: "password", id: "confirmPassword", name: "confirmPassword", value: formData.confirmPassword, onChange: handleChange, required: true, disabled: isLoading, style: { width: '100%', padding: '0.5rem', border: '1px solid #ccc', borderRadius: '4px', } })] }), error && (jsx("div", { style: { color: 'red', marginBottom: '1rem', fontSize: '0.875rem' }, children: error })), jsx("button", { type: "submit", disabled: isLoading, style: { width: '100%', padding: '0.75rem', backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px', cursor: isLoading ? 'not-allowed' : 'pointer', opacity: isLoading ? 0.6 : 1, }, children: isLoading ? 'Creating Account...' : 'Register' })] })); }; export { AuthProvider, LoginForm, OneBackendClient, RegisterForm, useAuth, useData, useFileUpload }; //# sourceMappingURL=index.esm.js.map