@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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #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: Feed.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
Feed = () => {
  const { user } = useAuth0();
  const { email } = user;

  const { data, loading, error } = useSubscription(QUERY_LOGGED_IN_USER, {
    variables: {
      userFilter: {
        email: {
          eq: email,
        },
      },
    },
  });

  if (loading) {
    return <Spinner />;
  }
  if (error) {
    return (
      <div>
        <Text size="large" color="red">
          {error.message}
        </Text>
      </div>
    );
  }
  console.log(data);
  return (
    <Box pad="large" direction="row" alignSelf="center">
      <Grid
        gap="large"
        rows="medium"
        columns={{ count: "fit", size: ["small", "medium"] }}
      >
        {data.queryUser.map((userInfo) =>
          userInfo.following.map((followedUser) =>
            followedUser.posts.map((post) => (
              <Card width="medium" key={post.id}>
                <CardHeader
                  pad={{ horizontal: "small", vertical: "small" }}
                  background="light-1"
                  width="medium"
                  justify="stretch"
                  gap="small"
                >
                  <Avatar
                    size="small"
                    src={post.postedBy.avatarImageURL}
                    a11yTitle="Generated avatar for the user from robohash.org"
                  />

                  <Heading level="4" margin="none">
                    {post.postedBy.username}
                  </Heading>
                </CardHeader>
                <CardBody height="medium">
                  <Image fit="cover" src={post.imageURL} />
                </CardBody>
                <CardFooter
                  pad={{ horizontal: "small" }}
                  height="xxsmall"
                  background="light-3"
                  justify="between"
                  gap="xxsmall"
                >
                  <Text size="small">{post.description}</Text>
                  <Heading level="5" margin="none">
                    {post.likes === 1
                      ? `${post.likes} like`
                      : `${post.likes} likes`}
                  </Heading>
                </CardFooter>
              </Card>
            ))
          )
        )}
      </Grid>
    </Box>
  );
}
Example #27
Source File: App.js    From wedding-planner with MIT License 5 votes vote down vote up
App = () => {
  const { isLoading } = useAuth0();

  if (isLoading) {
    return <Loading />;
  }

  return (
    <Router>
      <NavigationBar />
      <Route exact path="/" component={HomePage} />
      <PrivateRoute exact path="/events" component={EventsPage} />
      <PrivateRoute exact path="/profile" component={ProfilePage} />
      <PrivateRoute
        exact
        path="/events/:eventId/venue"
        component={VenuesPage}
      />
      <Route
        exact
        path="/events/:eventId/guests/:guestId/RSVP"
        component={RSVPPage}
      />
      <PrivateRoute
        exact
        path="/events/new"
        component={NewReservationPage}
      />
      <PrivateRoute
        exact
        path="/events/:eventId/guests"
        component={GuestsPage}
      />
      <PrivateRoute
        exact
        path="/events/:eventId/media"
        component={MediaPage}
      />
      <Footer />
    </Router>
  );
}
Example #28
Source File: AuthButtons.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
AuthButton = () => {
  const { isAuthenticated } = useAuth0();

  return isAuthenticated ? <LogOutButton /> : <LogInButton />;
}
Example #29
Source File: ApolloWrapper.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
ApolloWrapper = () => {
  const { isAuthenticated, getIdTokenClaims } = useAuth0();
  const [xAuthToken, setXAuthToken] = useState("");

  useEffect(() => {
    const getToken = async () => {
      const token = isAuthenticated ? await getIdTokenClaims() : "";
      setXAuthToken(token);
    };
    getToken();
  }, [getIdTokenClaims, isAuthenticated]);

  const httpLink = createHttpLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT,
  });

  const authLink = setContext((_, { headers, ...rest }) => {
    if (!xAuthToken) return { headers, ...rest };

    return {
      ...rest,
      headers: {
        ...headers,
        "X-Auth-Token": xAuthToken.__raw,
      },
    };
  });

  const wsLink = new WebSocketLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT.replace("https://", "wss://"),
    options: {
      reconnect: true,
      minTimeout: 30000,
      connectionParams: {
        "X-Auth-Token": xAuthToken.__raw,
      },
    },
  });

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
    wsLink,
    authLink.concat(httpLink)
  );

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: splitLink,
  });

  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}