@auth0/auth0-react#useAuth0 JavaScript Examples

The following examples show how to use @auth0/auth0-react#useAuth0. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PrivateRoute.component.js    From hiring-system with GNU General Public License v3.0 6 votes vote down vote up
PrivateRouteComponent = ({ children, ...rest }) => {
  const { isAuthenticated } = useAuth0();
  const isUser = isAuthenticated;

  return (
    <Route
      {...rest}
      render={() => {
        return isUser ? children : <Redirect to="/"></Redirect>;
      }}
    ></Route>
  );
}
Example #2
Source File: App.js    From React-JS with MIT License 6 votes vote down vote up
function App() {
  const {isLoading} = useAuth0();
  if(isLoading) return <div>Loading...</div>
  
  return (
    <React.Fragment>
      <LoginButton />
      <LogoutButton />
      <Profile />
    </React.Fragment>
  );
}
Example #3
Source File: LoginButton.jsx    From React-JS with MIT License 6 votes vote down vote up
LoginButton = () => {
    const {loginWithRedirect,isAuthenticated} = useAuth0();


    return ( 
        !isAuthenticated && (
        <div>
            <button onClick={()=>loginWithRedirect()}>Login</button>
        </div>
     )
    )
}
Example #4
Source File: LogoutButton.jsx    From React-JS with MIT License 6 votes vote down vote up
LogoutButton = () => {
  const { logout, isAuthenticated } = useAuth0();

  return (
    isAuthenticated && (
      <React.Fragment>
        <button onClick={() => logout()}>Logout</button>{" "}
      </React.Fragment>
    )
  );
}
Example #5
Source File: Profile.jsx    From React-JS with MIT License 6 votes vote down vote up
Profile = () => {
  const { user, isAuthenticated } = useAuth0();

  return (
    <React.Fragment>
      {isAuthenticated && (
        <React.Fragment>
          <h2>User Profile</h2>
          <img src={user.picture} alt={user.name} />
          <JSONPretty data={user} />
        </React.Fragment>
      )}
    </React.Fragment>
  );
}
Example #6
Source File: Layout.jsx    From simplQ-frontend with GNU General Public License v3.0 6 votes vote down vote up
function Layout() {
  const { isLoading, isAuthenticated } = useAuth0();
  const dispatch = useDispatch();
  const getUserQueues = useGetUserQueues();

  useEffect(() => {
    // All the backend API calls that should happen at the start goes here.
    // They will the dispached as soon as Auth0 has initilised.
    if (isLoading === false) {
      dispatch(getUserQueues());
    }
  }, [isLoading, isAuthenticated, getUserQueues, dispatch]);

  return (
    <div className={styles['box']}>
      <div className={styles['content']}>
        {/* We load the main app content only after Auth0 has been initilised. 
        This helps ensure that no backend API calls are made before auth the initilisation */}
        <Loading isLoading={isLoading}>
          <Routes />
        </Loading>
      </div>
      <div className={styles['footer']}>
        <Footer />
      </div>
    </div>
  );
}
Example #7
Source File: LoginButton.jsx    From simplQ-frontend with GNU General Public License v3.0 6 votes vote down vote up
LoginButton = () => {
  const { user, isAuthenticated, logout, loginWithRedirect } = useAuth0();

  if (isAuthenticated) {
    return (
      <Button
        color="primary"
        onClick={() => logout({ returnTo: window.location.origin })}
        variant="outlined"
      >
        <Avatar id={styles.avatar} alt={user.name} src={user.picture} />
        &nbsp;&nbsp;Logout
      </Button>
    );
  }
  return (
    <Button color="primary" onClick={loginWithRedirect} variant="outlined">
      <Avatar id={styles.avatar} alt="user">
        {' '}
        <AccountCircleIcon />
      </Avatar>
      &nbsp;&nbsp;Login
    </Button>
  );
}
Example #8
Source File: Auth0.jsx    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
Auth0 = ({ children }) => {
    const { logoutRedirectUrl } = React.useContext(configContext);
    const { loginWithRedirect, getAccessTokenSilently, logout } = useAuth0();

    return (
        <AuthProvider
            onLogin={() => loginWithRedirect()}
            onLoginCallback={async () => {
                return await getAccessTokenSilently({
                    ignoreCache: true,
                });
            }}
            onLogout={() =>
                logout({
                    returnTo: logoutRedirectUrl,
                })
            }
            onLogoutCallback={async () => {}}
        >
            {children}
        </AuthProvider>
    );
}
Example #9
Source File: loginButton.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
LoginButton = () => {
  const { loginWithRedirect } = useAuth0();
  return (
    <Button
      onClick={() => loginWithRedirect()}
      variant="contained"
      color="secondary"
      className="btn-margin"
      startIcon={<VpnKeyIcon/>}
    >
      Log In
    </Button>
  );
}
Example #10
Source File: logoutButton.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
LogoutButton = () => {
  const { logout } = useAuth0();
  return (
      <Button 
        variant="contained"
        color="secondary"
        startIcon={<ExitToAppIcon/>}
        onClick={() => logout({returnTo: window.location.origin})}
      > 
        Logout 
      </Button>
  );
}
Example #11
Source File: signupButton.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
SignupButton = () => {
  const { loginWithRedirect } = useAuth0();
  return (
    <Button
      onClick={() =>
        loginWithRedirect({
          screen_hint: "signup",
        })
      }
      variant="contained"
      color="secondary"
      className="btn-margin"
    >
      Sign Up
    </Button>
  );
}
Example #12
Source File: index.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
AuthNav = ({ history }) => {
  const { user, isAuthenticated, loginWithRedirect } = useAuth0();
  const location = useLocation();
  const classes = useStyles();
  return (
    <div className={classes.navRight}>
      {location && location.pathname !== '/create' ? (
        <Button
          onClick={() => {isAuthenticated? history.push("/create"): loginWithRedirect()}}
          variant="contained"
          color="secondary"
          className="btn-margin"
          startIcon={<AddIcon />}
        >
          Create
        </Button>
      ) : null}
      &nbsp;
      {isAuthenticated ? (
        <IconButton onClick={() => history.push('/profile')}>
          <Avatar alt={user.name} src={user.picture} />
        </IconButton>
      ) : (
        <span className={classes.login}>
          <LoginButton />
        </span>
      )}
    </div>
  );
}
Example #13
Source File: LogInButton.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
LogInButton = () => {
  const { loginWithRedirect } = useAuth0();

  return (
    <GenericButton
      color="status-ok"
      secondary
      plain={true}
      label="Log in"
      style={{ margin: 10 }}
      onClick={loginWithRedirect}
    />
  );
}
Example #14
Source File: LogOutButton.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
LogOutButton = () => {
  const { logout } = useAuth0();

  return (
    <GenericButton
      color="status-warning"
      plain={true}
      label="Log out"
      style={{ margin: 10 }}
      onClick={() =>
        logout({
          returnTo: window.location.origin,
        })
      }
    />
  );
}
Example #15
Source File: ProtectedRoute.js    From TalkTrack with MIT License 6 votes vote down vote up
export default function ProtectedRoute({ children }) {
  const { loading, isAuthenticated } = useAuth0();

  if (loading) return <p>Loading...</p>;
  const isBrowser = typeof window !== 'undefined';

  if (!isAuthenticated && isBrowser) {
    navigate('/');
  }
  return { ...children };
}
Example #16
Source File: navbar.js    From TalkTrack with MIT License 6 votes vote down vote up
Navbar = () => {
  const { isAuthenticated, loginWithRedirect, logout } = useAuth0();

  return (
    <header>
      <nav id="navbar">
        <p id="brand">
          <Link to="/">Talk Track</Link>
        </p>
        <div className="nav-items">
          {isAuthenticated && (
            <>
              <Link to="/addTalk" className="nav-item">
                Add Talk
              </Link>
              <button
                className="linkBtn nav-item"
                onClick={() => logout({ returnTo: window.location.origin })}
              >
                Logout
              </button>
            </>
          )}
          {!isAuthenticated && (
            <button
              className="linkBtn nav-item"
              onClick={() =>
                loginWithRedirect({ appState: `${window.location.pathname}` })
              }
            >
              Login
            </button>
          )}
        </div>
      </nav>
    </header>
  );
}
Example #17
Source File: Profile.js    From willow-grandstack with Apache License 2.0 6 votes vote down vote up
Profile = () => {
  const { user, isAuthenticated } = useAuth0()

  return (
    isAuthenticated && (
      <Paper style={{ padding: '20px' }}>
        <Avatar src={user.picture} alt={user.name}></Avatar>
        <Typography>{user.name}</Typography>
        <Typography>{user.email}</Typography>
      </Paper>
    )
  )
}
Example #18
Source File: index.js    From willow-grandstack with Apache License 2.0 6 votes vote down vote up
AppWithApollo = () => {
  const [accessToken, setAccessToken] = useState()
  const { getAccessTokenSilently, loginWithRedirect } = useAuth0()

  const getAccessToken = useCallback(async () => {
    try {
      const token = await getAccessTokenSilently()
      console.log(token)
      setAccessToken(token)
    } catch (err) {
      //loginWithRedirect()
    }
  }, [getAccessTokenSilently, loginWithRedirect])

  useEffect(() => {
    getAccessToken()
  }, [getAccessToken])

  const client = new ApolloClient({
    uri: process.env.REACT_APP_GRAPHQL_URI || '/graphql',
    request: async (operation) => {
      if (accessToken) {
        operation.setContext({
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        })
      }
    },
  })

  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  )
}
Example #19
Source File: useAccount.js    From os-league-tools with MIT License 6 votes vote down vote up
// Basic wrapper around useAuth0 with login state caching for now, more will be added with backend user auth changes
export default function useAccount({ redirectReturnToUrl }) {
    const { isLoading, isAuthenticated, loginWithRedirect, logout: logoutWithRedirect } = useAuth0();
    const isLoginCache = useSelector(state => state.account.accountCache.isLoggedIn);
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(updateAccountCache({ isAuthenticated }));
    }, [isAuthenticated]);

    const isLoggedIn = isLoginCache || isAuthenticated;
    const isAuthenticating = isLoading;

    const login = () => {
        loginWithRedirect({ redirect_uri: redirectReturnToUrl });
    };
    const logout = () => {
        logoutWithRedirect({ returnTo: redirectReturnToUrl });
    };

    return { isLoggedIn, isAuthenticating, login, logout };
}
Example #20
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
LoginLink = () => {
  const { loginWithRedirect } = useAuth0();
  return (
    <OverlayTrigger
      placement="bottom"
      overlay={<Tooltip id="tooltip-login">Log In</Tooltip>}
    >
      <Nav.Link onClick={() => loginWithRedirect()}>
        <FontAwesomeIcon icon={faSignInAlt} size="lg" />
      </Nav.Link>
    </OverlayTrigger>
  );
}
Example #21
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
LogoutLink = () => {
  const { logout } = useAuth0();
  return (
    <OverlayTrigger
      placement="bottom"
      overlay={<Tooltip id="tooltip-logout">Sign Out</Tooltip>}
    >
      <Nav.Link
        onClick={() =>
          logout({
            returnTo: window.location.origin,
          })
        }
      >
        <FontAwesomeIcon icon={faSignOutAlt} size="lg" />
      </Nav.Link>
    </OverlayTrigger>
  );
}
Example #22
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
/**
 *  Navbar Component using {Link}
 */
function NavigationBar() {
  const { isAuthenticated } = useAuth0();

  return (
    <Navbar bg="light" shadow="lg" expand="lg">
      <Navbar.Brand href="/">
        <Image src={logo} className="custom-img" />
      </Navbar.Brand>
      <Navbar.Toggle aria-controls="navbar-nav" />
      <Navbar.Collapse>
        {isAuthenticated ? (
          <Nav className="ml-auto color-link">
            <NavDropdown title="Events" id="basic-nav-dropdown">
              <NavDropdown.Item href="/events">
                Your Events
              </NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="/events/new">
                Create New
              </NavDropdown.Item>
            </NavDropdown>
            <ProfileLink />
            <LogoutLink />
          </Nav>
        ) : (
          <Nav className="ml-auto color-link">
            <LoginLink />
            <SignupLink />
          </Nav>
        )}
      </Navbar.Collapse>
    </Navbar>
  );
}
Example #23
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
SignupLink = () => {
  const { loginWithRedirect } = useAuth0();
  return (
    <OverlayTrigger
      placement="bottom"
      overlay={<Tooltip id="tooltip-signup">Sign Up</Tooltip>}
    >
      <Nav.Link
        onClick={() => loginWithRedirect({ screen_hint: 'signup' })}
      >
        <FontAwesomeIcon icon={faUserPlus} size="lg" />
      </Nav.Link>
    </OverlayTrigger>
  );
}
Example #24
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
ProfilePage = () => {
  const { user } = useAuth0();
  const { name, picture, email } = user;

  return (
    <Container fluid className="pt-5">
      <Row>
        <Col className="col-lg-6 col-sm-12 m-auto">
          <Card className="bgProfileComponent custom-style-profile bg-light">
            <Card.Header className="profile-title-style bg-light">
              <h3>Profile</h3>
            </Card.Header>
            <Card.Body className="d-flex flex-column">
              <Col className="center">
                <Card.Img
                  className="profile-img-style"
                  variant="top"
                  src={picture}
                />
              </Col>
              <Col className="text-style">
                <h5>{name}</h5>
                <p className="head text-muted">{email}</p>
              </Col>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}
Example #25
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
VenuesPage = (props) => {
  const { getAccessTokenSilently } = useAuth0();
  // used to send user to next page on create success

  return (
    <VenuesPageComponent
      getAccessToken={getAccessTokenSilently}
      eventId={props.match.params.eventId}
    />
  );
}
Example #26
Source File: auth.js    From simplQ-frontend with GNU General Public License v3.0 5 votes vote down vote up
useMakeAuthedRequest = () => {
  const auth = useAuth0();

  /**
   * Async function for sending request authorized with Auth0
   *
   * @param {Object} request object created by requestFactory.
   * @returns {Object} request response data as a Promise.
   */
  const makeAuthedRequest = async (request) => {
    const { data } = await axios({
      baseURL,
      ...request,
      headers: {
        ...request.headers,
        // Add the Authorization header to the existing headers
        Authorization: await getAuthHeaderValue(auth),
      },
    }).catch((error) => {
      // log error to sentry for alerting
      let eventId;
      Sentry.withScope((scope) => {
        scope.setTag('Caught-at', 'API request');
        eventId = Sentry.captureException(error);
      });
      // eslint-disable-next-line no-console
      console.log(`Sentry exception captured, event id is ${eventId}`);
      // In case of request failure, extract error from response body
      if (error.response) {
        // Response has been received from the server
        const message = error.response.data.message;
        throw new Error(message || 'Unknown error occured. We are looking into this.');
      } else {
        // No response from server, should be a network issue
        throw new Error('Are you offline? Check your internet connection and try again.');
      }
    });

    return data;
  };

  return makeAuthedRequest;
}
Example #27
Source File: AdminPage.jsx    From simplQ-frontend with GNU General Public License v3.0 5 votes vote down vote up
AdminPageView = (props) => {
  const { queueId } = props;
  const queueName = useSelector(selectQueueName);
  const description = queueName && 'Ready to share';
  const dispatch = useDispatch();
  const getSelectedQueue = useGetSelectedQueue();
  const getSelectedQueueHistory = useGetSelectedQueueHistory();

  const [toursteps, setToursteps] = useState(getToursteps(window.innerHeight));
  const { isAuthenticated } = useAuth0();
  const update = useCallback(() => {
    clearTimeout(timeoutId);
    dispatch(getSelectedQueue({ queueId }));
    dispatch(getSelectedQueueHistory({ queueId }));
    timeoutId = setTimeout(update, TIMEOUT);
    // TODO: Check if this is good solution.
    /* eslint-disable-next-line */
  }, [queueId]);

  const resize = () => setToursteps(getToursteps(window.innerWidth));

  useEffect(() => {
    window.addEventListener('resize', resize);
    return () => window.removeEventListener('resize', resize);
  });

  useEffect(() => {
    update();
    return () => clearTimeout(timeoutId);
  }, [update]);

  return (
    <div className={styles['admin-content']}>
      <Tour toursteps={toursteps} />
      <HeaderSection queueId={queueId} queueName={queueName} description={description} />
      {isAuthenticated ? null : (
        <Ribbon
          title="Temporary queue warning!"
          subTitle="Please sign up to make your queue permanent."
        />
      )}
      <div className={styles['main-body']}>
        <TokenList queueName={queueName} queueId={queueId} />
        <SidePanel queueId={queueId} />
      </div>
    </div>
  );
}
Example #28
Source File: App.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
function App() {
  
  const [idToken, setIdToken] = useState("");

  const classes = useStyles();
  const { isLoading, isAuthenticated, getIdTokenClaims } = useAuth0();

  useEffect(() => {
    const initAuth0 = async () => {
      if (isAuthenticated) {
        const idTokenClaims = await getIdTokenClaims();
        setIdToken(idTokenClaims.__raw);
      }
    };
    initAuth0();
  }, [isAuthenticated, getIdTokenClaims]);

  useEffect(() => {
    ReactGA.initialize('UA-177248464-1');
    ReactGA.pageview(window.location.pathname);
  }, [])

  if (isLoading) {
    return <Loading />;
  }
  
  const client = createApolloClient(idToken);
 
  return (
    <ApolloProvider client={client}>
    <div className={classes.root}>
      <CssBaseline />
      <Router history={history}>
        <Suspense fallback={<div />}>
          <ModalSwitch />
        </Suspense>
      </Router>
    </div>
    </ApolloProvider>
  )
}
Example #29
Source File: profile.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
Profile = () => {
  const [role, setRole] = useState('USER');
  const { user, isAuthenticated, getIdTokenClaims } = useAuth0();
  const history = useHistory();
  const classes = useStyles();
  useEffect(() => {
    const initAuth0 = async () => {
      if (isAuthenticated) {
        const idTokenClaims = await getIdTokenClaims();
        setRole(idTokenClaims['https://dgraph.io/jwt/claims']['ROLE']);
      }
    };
    initAuth0();
  }, [isAuthenticated, getIdTokenClaims]);

  return (
    <>
      <Navbar title="Profile" color="primary" />
      <div className={classes.content}>
        <div className={classes.profile}>
          <img
            className={classes.profileImg}
            src={user.picture}
            alt="Profile"
            style={{ 'max-width': '100%' }}
          />
          <p>
            Name: <strong>{user.name}</strong>
          </p>
          <p>
            Email: <strong>{user.email}</strong>
          </p>
        </div>
        <div className={classes.logout}>
          <LogoutButton />
        </div>
        {role === 'ADMIN' ? (
          <div className={classes.admin}>
            <Button
              onClick={() => history.push('/approve')}
              variant="contained"
              color="secondary"
              className="btn-margin"
              startIcon={<CheckCircleIcon />}
            >
              Approve
            </Button>
            &nbsp;
            <Button
              onClick={() => history.push('/flagged')}
              variant="contained"
              color="secondary"
              className="btn-margin"
              startIcon={<FlagIcon />}
            >
              Flagged
            </Button>
          </div>
        ) : null}
      </div>
    </>
  );
}