Thanks Tom, here’s the code from home, getAccount in helpers and a segment of the app.js
// app.js
function customAuthHandler({ history }) {
history.push(`/`);
}
class App extends Component {
render() {
return (
<Router history={history} i18n={ i18n }>
<Security
issuer={config.oidc.issuer}
client_id={config.oidc.clientId}
redirect_uri={config.oidc.redirectUri}
onAuthRequired={customAuthHandler}
>
<Header i18n={ i18n }/>
<div>
<Route path="/implicit/callback" component={ImplicitCallback} />
<Route exact path="/" component={Home} />
<Route exact path="/signup" component={SignupPage} />
<SecureRoute exact path="/lessons/all" component={ListLessons} />
</div>
</Security>
</Router>
);
}
}
export default App;
/////////////////////
// home.js
import React from 'react';
import moment from 'moment';
import {Container, Row, Col, Badge} from 'reactstrap';
import { Link } from 'react-router-dom';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import { withAuth } from '@okta/okta-react';
import { getAccount } from './../helpers';
import LoginPage from './okta/LoginPage';
export default withAuth(class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
filteredData: [],
resetDate: false,
empty: [],
hide: false,
authenticated: null,
userinfo: null,
ready: false
};
this.getPage = this.getPage.bind(this);
this.getAccount = getAccount.bind(this);
}
async componentDidMount() {
await this.getAccount();
}
async componentDidUpdate() {
await this.getAccount();
}
getPage() {
if (this.state.ready) {
switch (this.state.userinfo.role) {
case 'teacher': {
return (<DashTeacher userinfo={this.state.userinfo} />)
}
case 'admin': {
return (<DashAdmin userinfo={this.state.userinfo} />)
}
default: {
return (<DashTeacher userinfo={this.state.userinfo} />)
}
}
} else {
return (<div></div>)
}
}
render() {
return (
<div>
{ this.state.authenticated !== null &&
<Container>
<Col lg={12}>
{ this.state.authenticated &&
this.getPage()
}
{ !this.state.authenticated &&
(<LoginPage auth={this.props.auth} />)
}
</Col>
</Container>
}
</div>
)
}
});
/////////////////////
// helpers.js
import history from './history';
import config from './.config';
import request from 'superagent';
import uuidv4 from 'uuid/v4';
import { translate } from 'react-i18next';
async function getUserProfile(id, accessToken) {
return await request
.get(`/v1/okta/sub/${id}`)
.set({ Authorization: `Bearer ${accessToken}` })
.set('accept', 'json')
.then(function(res) {
return res.body
});
}
function verifyAccountRole(current_role, allowed) {
try {
const allowed_array = allowed.replace(/ +(?= )/g,'').split(' ')
if (!allowed.includes(current_role)) {
goTo('/') // if you don't have rights to see this page, go back to root url
}
} catch (err) {
console.log(err, current_role, allowed)
}
}
async function getAccount(roles = null) {
const authenticated = await this.props.auth.isAuthenticated();
// if authenticated does not equal this.state.authenticated
if (authenticated !== this.state.authenticated) {
// if authenticated and userinfo does not exist?
if (authenticated && !this.state.userinfo) {
console.log("getAccount", "authenticated", authenticated)
// get accessToken, if none available, logout
const accessToken = await this.props.auth.getAccessToken();
if (!accessToken) { this.props.auth.logout() }
console.log("getAccount", "accessToken", accessToken)
// try to generate userinfo
try {
let userinfo = await this.props.auth.getUser(accessToken);
console.log("getAccount", "userinfo", userinfo)
let userProfile = await getUserProfile(userinfo.sub, accessToken)
console.log("getAccount", "userProfile")
userinfo.role = userProfile.role
userinfo.user_id = userProfile._id
userinfo.classrooms = userProfile.classrooms || []
// with userinfo generated, save it to state
this.setState({ authenticated, accessToken, userinfo, ready: true
}, () => {
console.log("getAccount", "setState")
if (roles !== null) { // if role given, verify role
verifyAccountRole(userinfo.role, roles);
}
})
} catch (err) {
console.log("getAccount", "logout")
this.props.auth.logout()
// window.location.href = '/'
}
} else {
this.setState({ authenticated })
}
}
}
export {
verifyAccountRole,
getUserProfile,
getAccount,
}