Hi. I’ve got an issue here with my code. What happens is that I can log in and out and see the login screen correctly using this code except for when I create a new user, get email confirmation link which opens new tab with the modal that says I’m logged in, except I am still on the log in route. I cannot figure out how to hook up the code to redirect the user so that when they click the confirmation link they get to see the protected
page instead of log in.
Here’s my code:
import React from 'react'
import Button from 'react-bootstrap/Button';
import Protected from '../Protected';
import netlifyIdentity from 'netlify-identity-widget'
import AppHeader from '../../components/AppHeader'
import {
BrowserRouter as Router,
Route,
// Link,
Redirect,
withRouter
} from 'react-router-dom'
const netlifyAuth = {
isAuthenticated: false,
user: null,
authenticate(callback) {
this.isAuthenticated = true;
netlifyIdentity.open();
netlifyIdentity.on('login', user => {
this.user = user;
callback(user);
});
},
signout(callback) {
this.isAuthenticated = false;
netlifyIdentity.logout();
netlifyIdentity.on('logout', () => {
this.user = null;
callback();
});
}
};
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
netlifyIdentity.currentUser() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
}
/>
);
}
const AuthButton = withRouter(
({ history }) =>
netlifyIdentity.currentUser() ? (
<p className='d-flex justify-content-between'>
<span className='capitalize'>Welcome {netlifyIdentity.currentUser().user_metadata.full_name}!</span>
<Button className='ml-3'
onClick={() => {
netlifyAuth.signout(() => history.push('/'));
}}
>
Sign out
</Button>
</p>
) : (
<div className='mt-5'>
<p>You are not logged in.</p>
<Redirect to={'/protected'} />
</div>
)
);
class Login extends React.Component {
state = { redirectToReferrer: false };
login = () => {
netlifyAuth.authenticate(() => {
this.setState({ redirectToReferrer: true });
});
};
render() {
let { from } = this.props.location.state || { from: { pathname: '/protected' } };
let { redirectToReferrer } = this.state;
if (redirectToReferrer) return <Redirect to={from} />;
return (
<div>
<p className='mb-4'>Log in to {this.props.appName}</p>
<hr></hr>
<Button className='mt-2' onClick={this.login}>Log in</Button>
</div>
);
}
}
export default function Auth(props) {
let appName = props.appName
return (
<Router>
<div>
<AppHeader authButton={<AuthButton />}/>
<Route path="/login" render={(props) => <Login {...props} appName={appName} />}/>
<PrivateRoute path="/protected" component={Protected} />
<Redirect to={'/login'} />
</div>
</Router>
);
}`