Skip to content

Instantly share code, notes, and snippets.

@alenthomas
Last active September 17, 2018 18:16
Show Gist options
  • Save alenthomas/5880c901d795a31bc27d8543baf5bb4a to your computer and use it in GitHub Desktop.
Save alenthomas/5880c901d795a31bc27d8543baf5bb4a to your computer and use it in GitHub Desktop.
// src/OktaAuthComponent.js
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { withAuth } from '@okta/okta-react';
export const OktaAuthComponent = withAuth(class Auth extends Component {
constructor(props) {
super(props);
this.state = { authenticated: null };
this.checkAuthentication = this.checkAuthentication.bind(this);
this.checkAuthentication();
this.login = this.login.bind(this);
}
async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
this.setState({ authenticated });
}
}
componentDidUpdate() {
this.checkAuthentication();
}
async login() {
// Redirect to '/' after login
this.props.auth.login('/');
}
render() {
if (this.state.authenticated === null) return null;
const childrenWithProps = React.Children.map(this.props.children, child =>
React.cloneElement(child, { passedProps: { auth: this.props.auth } }));
return (this.state.authenticated ?
childrenWithProps :
<button onClick={this.login}>Login</button>); // component which initiates login i.e invokes the okta login function
}
});
export const OktaLogout = withAuth(class Logout extends Component {
async logout() {
this.props.auth.logout();
}
render() {
this.logout()
return <Redirect to='/' />
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment