Giter Club home page Giter Club logo

frontegg-react's Introduction


Frontegg Logo

Frontegg React.js

Frontegg is a web platform where SaaS companies can set up their fully managed, scalable and brand aware - SaaS features and integrate them into their SaaS portals in up to 5 lines of code.

Installation

Use the package manager npm to install frontegg React.JS library.

npm install @frontegg/react react-router-dom

Configuration

Wrap your root component with Frontegg Provider:

import React from 'react';
import ReactDOM from 'react-dom'; // For react 17
// For react 18: import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

import { FronteggProvider } from '@frontegg/react';

const contextOptions = {
  baseUrl: 'https://[YOUR_SUBDOMAIN].frontegg.com',
  clientId: '[YOUR-CLIENT-ID]'
};

// For react 18: 
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(
ReactDOM.render(
    <FronteggProvider contextOptions={contextOptions} hostedLoginBox={true}>
        <App />
    </FronteggProvider>,
    document.getElementById('root')
);

In order to get your subDomain and clientId, visit our portal.

Redirect to login

Using the Frontegg useAuth hook, you can determine whether a user is authenticated or not. If the user is not authenticated, you can redirect the user to login via the useLoginWithRedirect hook as shown below.

import './App.css';
// import { useEffect } from 'react';
import { ContextHolder } from '@frontegg/rest-api';
import { useAuth, useLoginWithRedirect } from '@frontegg/react';

function App() {
  const { user, isAuthenticated } = useAuth();
  const loginWithRedirect = useLoginWithRedirect();

  // Uncomment this to redirect to login automatically
  // useEffect(() => {
  //   if (!isAuthenticated) {
  //     loginWithRedirect();
  //   }
  // }, [isAuthenticated, loginWithRedirect]);

  const logout = () => {
    const baseUrl = ContextHolder.getContext().baseUrl;
    window.location.href = `${baseUrl}/oauth/logout?post_logout_redirect_uri=${window.location}`;
  };

  return (
    <div className='App'>
      {isAuthenticated ? (
        <div>
          <div>
            <img src={user?.profilePictureUrl} alt={user?.name} />
          </div>
          <div>
            <span>Logged in as: {user?.name}</span>
          </div>
          <div>
            <button onClick={() => alert(user.accessToken)}>What is my access token?</button>
          </div>
          <div>
            <button onClick={() => logout()}>Click to logout</button>
          </div>
        </div>
      ) : (
        <div>
          <button onClick={() => loginWithRedirect()}>Click me to login</button>
        </div>
      )}
    </div>
  );
}

export default App;

Integrate Admin Portal

Opening the Admin Portal is available via the following code snippet.

import { AdminPortal } from '@frontegg/react'

const handleClick = () => {
  AdminPortal.show();
};

<button onClick={handleClick}>Settings</button>

frontegg-react's People

Contributors

amirjaron avatar ataliarefua avatar aviadmizrachi avatar chen-frontegg avatar davidantoon avatar dependabot[bot] avatar doregg avatar eldad-frontegg avatar erano067 avatar fookoo avatar frontegg-david avatar github-actions[bot] avatar guy-frontegg avatar ihigani avatar isra-frontegg avatar itamar-frontegg avatar kikar avatar mariavlasov avatar maxarnaut avatar maxarnautfrontegg avatar ofriros avatar ppliszczynski avatar rotemzif1 avatar royi-frontegg avatar sdemjanenko avatar serslon avatar snyk-bot avatar tomerfrontegg avatar tomerk97 avatar yuvalotem1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

frontegg-react's Issues

[BUG] Logging out and then logging in caused log-out loop

Describe the bug
In case someone logs out - the UI redirects him to the login page. However upon login successfully, the UI redirects him to /logout and then it's back to log-in loop.

To Reproduce
Steps to reproduce the behavior:

  1. Log out using the react /logout route.
  2. Log back in.
  3. It will log you out again.

Expected behavior
It should re-direct you to the home page ("/") after a successful login.

Additional context
frontegg react version 1.6.0

[BUG] @frontegg/redux-store/toolkit/index.js is ESM not CommonJS

I ran into an error in Jest when this file was loaded:

.../node_modules/@frontegg/redux-store/toolkit/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { bindActionCreators, combineReducers, configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (node_modules/@frontegg/react-hooks/index.cjs.js:9:15)

I can probably get around this in my Jest config, but its likely that since this file is ESM, users may run into issues.

Question: How to redirect to Login page after session timeout

Hello,
In my app, when frontegg session ends, a blank page is currently being displayed to the user.
The expected behaviour is that the user will be redirected to frontegg login page so I wanted to know if the SDK provides a way of doing it?

Thanks.

[BUG] New version causes breaking

Describe the bug
When updating react-auth with npm install we get the following errors:
Attempted import error: 'MenuItem' is not exported from '@frontegg/react-core'.
Attempted import error: 'SocialLoginsProviders' is not exported from '@frontegg/rest-api'.

To Reproduce
Steps to reproduce the behavior:

  1. install frontegg/react-auth v.1.10.0
  2. See error

Expected behavior
No breaking

Screenshots
Screen Shot 2020-11-29 at 18 20 09

[BUG] keepSessionAlive does not behave as expected

Describe the bug
From the documentation:

const authOptions = {
 // keepSessionAlive: true // Uncomment this in order to maintain the session alive
};

I understood that this should maintain the authenticated session across refreshes and browser restarts.
However, this doesn't seem to work. The app always restarts with no data in the auth store.

To Reproduce
Steps to reproduce the behavior:

  1. Follow the Login Box Integration Tutorial
  2. Login to application
  3. Refresh the "logged in as" view.
  4. Login page shows up again.

Expected behavior
After refresh you still see the "logged in as" view.

Additional context
At the moment I implemented a workaround which manually stores the user object in storage at point of login:

    const isAuthenticated = useIsAuthenticated();
    const user = useAuthUserOrNull();
    if (localStorage.getItem('TEST-USER') === null && isAuthenticated && user) {
        localStorage.setItem('TEST-USER', JSON.stringify(user));
    }

And uses it when available in construction of the provider:

    const localUser = localStorage.getItem('TEST-USER');
    const isAuthenticated = localUser !== null;

    const authOptions = {
        user: isAuthenticated ? JSON.parse(localUser) : null,
        isAuthenticated,
    };
...
    return (
        <FronteggProvider
            contextOptions={contextOptions}
            hostedLoginBox={true}
            authOptions={authOptions}
        >
            {children}
        </FronteggProvider>
    );

I also invalidated the storage when logging out:

    const logout = () => {
        localStorage.removeItem('TEST-USER')
        const baseUrl = ContextHolder.getContext().baseUrl;
        window.location.href = `${baseUrl}/oauth/logout?post_logout_redirect_uri=${window.location}`;
    };

but since I don't have a hook on 401s from the session endpoint, I cannot invalidate it when it expires or is malformed.

[BUG] When baseUrl is undefined the application just redirects endlessly

Describe the bug
Endless redirects when baseUrl is undefined.
The redirect URLs switch from:

https://<tenant>.frontegg.com/oauth/authorize?response_type=code&client_id=INVALID-CLIENT-ID&scope=openid+email+profile&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth%2Fcallback&code_challenge=******&code_challenge_method=S256&nonce=*****

to:

http://localhost:3000/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/undefined/oauth/authorize?response_type=code&client_id=INVALID-CLIENT-ID&scope=openid+email+profile&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth%2Fcallback&code_challenge=******&code_challenge_method=S256&nonce=******

and every second the URL is added with another /oauth/authorize at the end.

I know I should fill in the baseUrl but believe it should fail early instead of DDOSing your API.

To Reproduce

const contextOptions = {
  baseUrl: undefined,
};

ReactDOM.render(
  <StrictMode>
     <BrowserRouter>
        <FronteggProvider contextOptions={contextOptions}>
            <App />
        </FronteggProvider>
    </BrowserRouter>
  </StrictMode>,
  document.getElementById('root')
);

Expected behavior
Error screen?

Query params lost on protected route

Describe the bug
Query params lost on protected route

To Reproduce
Add <ProtectedRoute exact path='/private' component={Private} /> route
Navigate to /private?query1=value1

Expected behavior
A redirection to /account/login will be made while keeping the query params on the URL

[BUG] @frontegg/react-hooks setinterval with a low time interval

Describe the bug

setInterval(function () {
            if (uriRef.current !== window.location.pathname) {
                uriRef.current = window.location.pathname;
                setUri(document.location.pathname);
            }
        }, 50);

Expected behavior
Increase it's time to 250 at least
And also clearInterval and removeEventListener

[BUG] Missing dependency warning @frontegg/rest-api

Describe the bug
When trying to build a project that includes @frontegg/react we're seeing a missing dependency build warning:

Error: "@frontegg/rest-api" is imported by "../../../node_modules/@frontegg/js/HostedLogin/index.js", but could not be resolved โ€“ treating it as an external dependency.

To Reproduce

  1. Create a project with the @frontegg/react dependency
  2. Fail or log build warnings
  3. A warning appears for a missing dependency for @frontegg/rest-api

Expected behavior
No missing dependency warnings.

Additional context
It looks like there is a reference to @frontegg/rest-api in the yarn.lock file in @frontegg/react but it is not referenced in the package.json.

[BUG] @frontegg/react-auth Rendered more hooks than during the previous render

Describe the bug

After enabling Google reCAPTCHA there's following error when opening login page:

Error: Minified React error #310; visit https://reactjs.org/docs/error-decoder.html?invariant=310 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at ao (react-dom.production.min.js:158)
    at Object.xo [as useCallback] (react-dom.production.min.js:168)
    at t.useCallback (react.production.min.js:22)
    at W (index.esm.js:161)
    ...

It seems to happen only in the production build. The part of the stacktrace captured by Sentry.io shows that the error occurred in node_modules/@frontegg/react-auth/index.esm.js file:

// Error
// Rendered more hooks than during the previous render.

// ./node_modules/@frontegg/react-auth/index.esm.js in c at line 161:28

return () => unload(policy === null || policy === void 0 ? void 0 : policy.siteKey);
  }, [policy === null || policy === void 0 ? void 0 : policy.enabled, policy === null || policy === void 0 ? void 0 : policy.siteKey]);
  if (!(policy === null || policy === void 0 ? void 0 : policy.enabled) || !(policy === null || policy === void 0 ? void 0 : policy.siteKey)) {
      return null;
  }
  const handleCallback = useCallback((token) => {
      setValue(token, false);
  }, [setValue]);
  if (!policy || !policy.enabled)
      return null;
  return React.createElement(ReCaptcha, { ref: recaptchaRef, sitekey: policy === null || policy === void 0 ? void 0 : policy.siteKey

To Reproduce
Steps to reproduce the behavior:

  1. Enable Google reCAPTCHA in the Frontegg admin console
  2. Go to login page

[BUG] Package.json module property points to non-existent file

When building an app using snowpack I hit the error:

[snowpack] Cannot find module '/Users/stephen/Code/permiso/arbiter/frontend/node_modules/@frontegg/react-hooks/index.esm.js' from '/Users/stephen/Code/permiso/arbiter/frontend/node_modules/snowpack/lib'

Upon inspecting the package.json file in node_modules/@frontegg/react-hooks I noticed that the module key points to index.esm.js but that file does not exist in node_modules/@frontegg/react-hooks.

[BUG] AdminPortal.show() won't open admin box at first time, but it does on the second time

Describe the bug
A clear and concise description of what the bug is.

AdminPortal.show() doesn't pop up the admin-box at first click, but it does on the second click. I'm also getting a warning from history.ts

You are trying to block a POP navigation to a location that was not created by @remix-run/router. The block will fail silently in production, but in general you should do all navigation with the router (instead of using window.history.pushState directly) to avoid this situation.

To Reproduce
Steps to reproduce the behavior:

  1. Create a button
  2. Embed AdminPortal.show on button click
  3. Click the button. At first, it won't pop up the admin box.
  4. Click the button again for the second time. This time it opens the admin box

Expected behavior
A clear and concise description of what you expected to happen.

It should open the admin box at first click

Screenshots
If applicable, add screenshots to help explain your problem.
Screen Shot 2023-09-05 at 9 33 16 AM

Additional context
Add any other context about the problem here.

[BUG] react-auth is missing formik dependency

Describe the bug
When building my app with v1.25.0 I run into the error:

'useField' is not exported by node_modules/formik/dist/formik.esm.js, imported by node_modules/@frontegg/react-auth/index.esm.js

I don't see any reference to formik in react-auth's package.json: https://github.com/frontegg/frontegg-react/blob/master/packages/auth/package.json

Formik is used at: https://github.com/frontegg/frontegg-react/blob/master/packages/auth/src/components/FReCaptcha.tsx#L3 and may be used in other places as well.

[BUG] Access token does not being refreshed properly

Describe the bug
The access token does not getting refresh correctly, I saw only one call for /refresh in my session.

To Reproduce
Steps to reproduce the behavior:

  1. Login using frontegg
  2. Wait for JWT expiration (without refreshing the page)

Expected behavior
Frontegg should automatically refresh my refresh-token if it's getting expired.

Additional context
Version 1.3.0

[BUG] Uploading profile picture does not work in the server side

Describe the bug
I can not upload a profile picture because of error 500 from the server.
I get as a response:
{"statusCode":500,"message":"failed to upload profile image","error":"Internal Server Error"}

To Reproduce
Steps to reproduce the behavior:

  1. Go to profile page
  2. Upload new profile image
  3. Click update profile
  4. See error

Additional context
Frontegg-react 1.6.0

[BUG] empty error messages on login

React embedded login seems to produce empty error messages, and doesn't seem to be sending any network requests:

Screen Shot 2022-08-03 at 9 35 01 PM

I haven't been able to debug further than this yet.

[BUG] Removing role for a user which has 1 role does not work

Describe the bug
In case a user has 1 role, and I revoke this role from him - I get him as "pending approval" (I saw the other issue), however, the role does not get deleted.

To Reproduce
Steps to reproduce the behavior:

  1. Go to team management
  2. Click on a user with 1 role
  3. Remove this error

Expected behavior
The role should be revoked.

Additional context
frontegg-react 1.6.0

[BUG]

Describe the bug
I'm adding secure access to a new app created by create-react-app but i'm getting

Failed to compile.

./node_modules/@frontegg/react-auth/index.esm.js
Attempted import error: 'enableES5' is not exported from 'immer' (imported as 'J').

To Reproduce

  1. npx create-react-app app-name --template typescript
  2. npx @frontegg/react-cli init
  3. wrap App:
const AppWithFrontegg = withFrontegg(App)

ReactDOM.render(
  <React.StrictMode>
    <AppWithFrontegg />
  </React.StrictMode>,
  document.getElementById('root')
);
  1. npm start

Screenshots

image

```

PlayerIDAddress=0x70F050
BattleListAddress=0x76A48C
HealthAddress=0x70E000
MaxManaAddress=0x57045C
ManaAddress=0x57048C
TabsBaseAddress=0x570744
XORAddress=0x570458
MaxHealthAddress=0x70E048
AmmunitionCountAddress=0x7B147C
AmmunitionTypeAddress=0x7B1480
WeaponCountAddress=0x7B14FC
WeaponTypeAddress=0x7B1500
LevelAddress=0x570470
ExperienceAddress=0x570460
ClassicClientName=Tibia
Tibia11Name=client
Tibia11XPos=Qt5Core.dll + 004555C8 > 8 > 134 > 24 > 18
Tibia11YPos=Qt5Core.dll + 004555C8 > 8 > 134 > 24 > 1C
Tibia11ZPos=Qt5Core.dll + 004555C8 > 8 > 134 > 24 > 20
Tibia11MyHP=[2] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 18
Tibia11MyMaxHP=[2] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 1A
Tibia11Experience=[8] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 28
Tibia11Level=[2] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 30
Tibia11MyMana=[2] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 60
Tibia11MyMaxMana=[2] Qt5Core.dll + 004555C8 > 8 > 124 > 60 > 62

[BUG] Local React builds take much longer with @frontegg/react package

Describe the bug
Comparing two states of the app development, first one is without @frontegg packages imported nor used in the code, second is with the @frontegg/react added to project and imported in code, with LoginBox used.
The LoginBox is used in an embedded configuration.

  • App is created in create-react-app,
  • React is "17.0.2",
  • @frontegg/react is "5.0.15"

To Reproduce
Steps to reproduce the behavior:

  1. start the local development server
  2. apply any insignificant change to code (e.g. insert a comment or console.log)
  3. observe the amount of time to rebuild/ hot reload the app in the console
  4. Time to reload takes a lot of time (approx. 11+ secs)

Expected behavior
There should be no major increases in reload time with Frontegg, I think that ~1-2 secs extra could be acceptable.

Additional context
In case you need additional info, I'm happy to help

[BUG] - Integrating with <React.StrictMode> causes each URL to be loaded twice

Describe the bug
Integrating FronteggProvider with <React.StrictMode> causes each request to be sent twice

To Reproduce
Steps to reproduce the behavior:

  1. Wrap your react application with <React.StrictMode>
  2. Refresh
    ==> Each request from frontegg to the backend is sent twice

Expected behavior
The request should be sent only once

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context
Add any other context about the problem here.

[BUG] how should i integrate with RouterProvider of React Router V6?

Describe the bug
i integrate with RouterProvider of React Router V6, and it report an error: You cannot render a inside another . You should never have more than one in your app.

To Reproduce

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <FronteggProvider contextOptions={contextOptions} hostedLoginBox={true} authOptions={authOptions}>
      <RouterProvider router={createBrowserRouter(Routes)}></RouterProvider>
    </FronteggProvider>
  </React.StrictMode>,
);

Screenshots
image

[FEATURE] Allow updating API Tokens table headers

Currently it's possible to update much of the UI via i18next. One part that isn't customizable is the API Tokens table headers found here:

import { ApiTokensActions, getApiTokensTableCells } from './components/ApiTokensTebleCell';
export const prefixCls = 'fe-api-tokens';
export const tableColumnsTenant = [
{
accessor: 'clientId',
Header: 'Client Id',
sortable: true,
Cell: getApiTokensTableCells('clientId'),
},
{
accessor: 'description',
Header: 'Description',
sortable: true,
Cell: getApiTokensTableCells('Description'),
},
{
accessor: 'createdByUserId',
Header: 'Created By',
sortable: true,
Cell: getApiTokensTableCells('createdByUserId'),
},
{
accessor: 'createdAt',
Header: 'Created At',
sortable: true,
Cell: getApiTokensTableCells('createdAt'),
},
{
id: 'actions',
minWidth: '3.25rem',
maxWidth: '3.25rem',
Cell: ApiTokensActions,
},
];
export const tableColumnsUser = [
{
accessor: 'clientId',
Header: 'Client Id',
sortable: true,
Cell: getApiTokensTableCells('clientId'),
},
{
accessor: 'description',
Header: 'Description',
sortable: true,
Cell: getApiTokensTableCells('Description'),
},
{
accessor: 'createdAt',
Header: 'Created At',
sortable: true,
Cell: getApiTokensTableCells('createdAt'),
},
{
id: 'actions',
minWidth: '3.25rem',
maxWidth: '3.25rem',
Cell: ApiTokensActions,
},
];

It would be great to be able to customize this part of the UI as well.

[BUG] Circular depedency when using vite and frontegg-react

Describe the bug
Running vite build fails on a npm package that depends on @frontegg/frontegg-react v5.0.50 with error:

Error: Circular dependency: ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/SignUp/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js

To Reproduce
Have a JavaScript npm package similar to the following template:

{
  ...
  "type": "module",
  "scripts": {
    "build": "vite build",
  },
  "dependencies": {
    "@frontegg/react": "v5.0.50",
  },
  "devDependencies": {
    "vite": "^4.4.9",
  }
  ...

Have the following code in your package source files:

import { FronteggProvider, useAuth, useLoginWithRedirect } from '@frontegg/react'

Expected behavior
I expect vite build to run without issues.

Additional context

Here is the build error log:

Circular dependency: ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/SignUp/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js
error during build:
Error: Circular dependency: ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/SignUp/saga.js -> ../../../node_modules/@frontegg/redux-store/auth/LoginState/saga.js
    at Object.onwarn (file:///home/../services/users/frontend-user/vite.config.ts.timestamp-1694170546515-ab39cd971c5ef.mjs:16:31)
    at onwarn (file:///home/../node_modules/@vitejs/plugin-react/dist/index.mjs:236:40)
    at onRollupWarning (file:///home/../node_modules/vite/dist/node/chunks/dep-df561101.js:48171:9)
    at onwarn (file:///home/../node_modules/vite/dist/node/chunks/dep-df561101.js:47902:13)
    at file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:24194:13
    at Object.logger [as onLog] (file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:25867:9)
    at Graph.sortModules (file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:25766:26)
    at Graph.build (file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:25654:14)
    at async file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:26615:13
    at async catchUnfinishedHookActions (file:///home/../node_modules/rollup/dist/es/shared/node-entry.js:25827:16)
npm ERR! Lifecycle script `build` failed with error: 

[BUG] Authentication Loading State Issue with Vite

Describe the bug
I'm currently developing a sample app with Frontendegg's authentication, utilizing the React integration guide. However, I am using Vite instead of Create React App (CRA) for this project.

The authentication process works as expected, but I encountered an issue when trying to display a loading component during this process. It seems that the isLoading state from useAuth() consistently returns false.

I discovered the isLoading property by inspecting the return type of useAuth(). However, I found no mention of it in the existing documentation.

This leads me to two questions:

  1. Is there an API reference for the React SDK that might explain this isLoading property?
  2. How can I correctly obtain the loading state during the authentication process?

To Reproduce
Steps to reproduce the behavior:

  1. Go to integration guide for React
  2. Follow the instruction and build the app with Vite
  3. Change const { user, isAuthenticated } = useAuth() with const { user, isAuthenticated, isLoading } = useAuth()
  4. Return loading component when isLoading is true e.g. if (isLoading) return <div>Loading...</div>
  5. You can see it's not rendered.

Expected behavior
I expect the 'isLoading' state to consistently return 'true' during the entire authentication process.

Screenshots
n/a

import { useEffect } from "react";
import "./App.css";
import { ContextHolder, useAuth, useLoginWithRedirect } from "@frontegg/react";

function App() {
  const { user, isAuthenticated, isLoading } = useAuth();

  const loginWithRedirect = useLoginWithRedirect();

  useEffect(() => {
    if (!isAuthenticated) {
      loginWithRedirect();
    }
  }, [isAuthenticated, loginWithRedirect]);

  const logout = () => {
    const baseUrl = ContextHolder.getContext().baseUrl;
    window.location.href = `${baseUrl}/oauth/logout?post_logout_redirect_uri=${window.location}`;
  };

  // HERE: This div should be rendered but the 'Click me to login' button will be rendered 
  if (isLoading) return <div>Loading...</div>;

  return (
    <div className="App">
      {isAuthenticated ? (
        <div>
          <div>
            <img src={user?.profilePictureUrl || undefined} alt={user?.name} />
          </div>
          <div>
            <span>Logged in as: {user?.name}</span>
          </div>
          <div>
            <button onClick={() => alert(user?.accessToken)}>
              What is my access token?
            </button>
          </div>
          <button onClick={() => logout()}>Click to logout</button>
        </div>
      ) : (
        <div>
          <button onClick={() => loginWithRedirect()}>Click me to login</button>
        </div>
      )}
    </div>
  );
}

export default App;

Additional context
I am using

Vite: 4.4.5
React: 18.2.0
@frontegg/react: 5.0.46

Feel free to ask me anything if you guys need more information. Thanks.

Entering invalid phone number does not describe issue in admin portal

When a user enters an invalid phone number in their profile, there is no feedback to the user of what the issue is, it simply re-opens the modal with a blank phone number. A few of our users have reached out complaining that this is a bug.

Ideally, there would be some phone number formatting, but at least there should be an error message.

image

Issue with redirection from /oauth/callback

Hi all, I am trying to integrate the package in my application and I have a problem with the final redirection.

I have followed the steps for hosted login integration. Everything works fine until the redirection. Although I am eventually redirected to http://localhost:3000/oauth/callback then I see the frontegg loader (the 3 bars) which hang forever.

What is supposed to happen then? How can I redirect the user from /oauth/callback to another path?

What I've tried so far:

  • setting a redirect_uri query param
  • trying to catch the route in react-router but it seems frontegg provider catches it first

[BUG] Console errors on Team Management and Login pages

Describe the bug
Console errors on team management and login pages.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the above pages.
  2. Open the console and click the error tab.
  3. See the errors.

Expected behavior
Remove any errors and warnings from the console.

Screenshots
Screen Shot 2020-11-25 at 11 41 13

Screen Shot 2020-11-25 at 11 41 39

How to easily access the type of the user returned from `useAuth`?

Sorry for diverging from the issue template but IMO this isn't a bug but more of a question.

I'm using the useAuth hook to log in users in a React + TS app. I then want to process the user object further before returning it from my custom hook:

export function useCustomAuth() {
    const { user: fronteggUser } = useAuth();

    function mapUser(user: /* Which type to use here? */) {
        // do something with the user
    }

    return {
        user: fronteggUser ? mapUser(fronteggUser) : null,
    };
}

My problem is that accessing the type of the user returned from useAuth is hard. I can't easily get the type from the return type of useAuth directly due to useAuth being overloaded and TS not being able to pick the correct overload in this case AFAIU:

// In this case the type of userFromFrontegg is `unknown` ...
function mapUser(
  userFromFrontegg: Exclude<ReturnType<typeof useAuth>, null | undefined>
) {
  // do something with the user
}

type HookReturnType = ReturnType<typeof useAuth>; // ... because this is `unknown`

type HookType = typeof useAuth; // ... because this is `{ (): AuthState; <S>(stateMapper: AuthStateMapper<S>): S; }`

I can get the type from a variable but this seems suboptimal:

const { user: fronteggUser } = useAuth();

function mapUser(
  userFromFrontegg: Exclude<typeof fronteggUser, null | undefined>
) {
  // do something with the user
}

My suggestion is to export the types AuthState, the return type of useAuth, and User from @frontegg/react to allow users to easily type the data returned by this hook. What do you think? Is there an easier way make this work maybe?

Thanks in advance for the help :)

[BUG]Uncaught TypeError: Cannot read properties of null (reading 'store')

Describe the bug
Uncaught TypeError: Cannot read properties of null (reading 'store')

We are trying to migrate from webpack4 to vite and getting this error

To Reproduce
Steps to reproduce the behavior:

  1. Install vite, make inside esbuildOptions platform: "node"
  2. run vite
  3. See error

Expected behavior
run at least locally without errors

Screenshots
image

[BUG] TypeError: can't access property "store", _useReduxContext is null with UmiJS

Describe the bug
We are trying to integrate Frontegg into an Ant Design Pro boilerplate and running into an error when the library is imported. Ant Design Pro uses a plugin system that obscures the root component and makes wrapping it with the Frontegg provider rather circuitous.

You can see our Frontegg plugin below:
https://github.com/Network-Chimp/umi-plugin-access/blob/master/src/utils/getAccessProviderContent.ts#L49

The plugin generates the @frontegg provider wrapper code into the relevant directory - src/.umi/plugin-frontegg-access within the dashboard repository.

When we try initializing the dashboard, we get the following error.

TypeError: can't access property "store", _useReduxContext is null
useSelector
./node_modules/react-redux/es/hooks/useSelector.js:121

  118 |   }
  119 | }
  120 | 
> 121 | var _useReduxContext = useReduxContext(),
      | ^  122 |     store = _useReduxContext.store,
  123 |     contextSub = _useReduxContext.subscription;
  124 | 

To Reproduce
Steps to reproduce the behavior:

  1. Clone the boilerplate dashboard here: https://github.com/Network-Chimp/dashboard
  2. cd dashboard; npm i; npm start
  3. Navigate to http://localhost:8000/
  4. Observe the TypeError
  5. Inspect the provider file at src/.umi/plugin-frontegg-access

Expected behavior

The dashboard should load with the provided Frontegg data.

Screenshots
Screen Shot 2021-05-21 at 8 57 10 AM

[BUG] Error: useNavigate() may be used only in the context of a <Router> component.

Describe the bug
I get the following error:

Error: useNavigate() may be used only in the context of a <Router> component.

whether I am wrapping the FronteggProvider with BrowserRouter or not.

To Reproduce

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { FronteggProvider } from '@frontegg/react';
import App from './App';

const contextOptions = {
  baseUrl: 'https://***.frontegg.com'
};

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <FronteggProvider contextOptions={contextOptions}>
        <App />
      </FronteggProvider>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

App.tsx:

import { useAuth } from '@frontegg/react';

function App() {
  const { user, isAuthenticated } = useAuth();

  return (
    <div className="App">
      {isAuthenticated && (
        <div>
          <img src={user.profilePictureUrl} alt={user.name} />

          <span>{user.name}</span>
        </div>
      )}
    </div>
  );
}

export default App;

package.json:

{
  "name": "application",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@frontegg/react": "^4.0.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1"
  },
  "devDependencies": {
    "@types/react": "^17.0.33",
    "@types/react-dom": "^17.0.10",
    "@vitejs/plugin-react": "^1.0.7",
    "typescript": "^4.4.4",
    "vite": "^2.7.2"
  }
}

Additional context
I am using Vite. I don't think it is related but could be.

[BUG] - Cannot install using @frontegg/react-cli

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Run @frontegg/react-cli init

==> Fails with the following error:
npx: installed 48 in 11.23s
Cannot find module 'prompts'
Require stack:
/Users/aviadmizrachi/.npm/_npx/56349/lib/node_modules/@frontegg/react-cli/index.js

Screenshots
If applicable, add screenshots to help explain your problem.
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.