Skip to content

Instantly share code, notes, and snippets.

@jermsam
Created April 10, 2019 03:33
Show Gist options
  • Select an option

  • Save jermsam/2f55e0216923b02205c186c43a46bfcd to your computer and use it in GitHub Desktop.

Select an option

Save jermsam/2f55e0216923b02205c186c43a46bfcd to your computer and use it in GitHub Desktop.
// ....
export default class MyApp extends App {
state = { };
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
render() {
const { Component, pageProps } = this.props;
return (
<AuthProvider>
<Container>
{/* Here we call NextSeo and pass our default configuration to it */}
<AuthConsumer>
{
({ authUser }) => <Component {...pageProps} {...{authUser}} /> //let all page component reflect the update in this.props.authUsr
}
</AuthConsumer>
</Container>
</AuthProvider>
);
}
}
import React from 'react';
import { app, bucket } from './feathers';
/* eslint-disable no-console */
const AuthContext = React.createContext();
class AuthProvider extends React.Component {
state = {
authUser: null
};
_isMounted = false;
componentDidMount() {
this._isMounted = true;
this.handleAuth();
}
componentWillUnmount() {
this._isMounted = false;
}
handleAuth = async () => {
try {
const token = localStorage.getItem('feathers-jwt'); // get jwt token from localStorage
if (token) {// if it's available
const { accessToken } = await app.authenticate(); // reauthenticate
const { userId } = await app.passport.verifyJWT(accessToken);// get userId from jwt token
const authUser = await app.service('users').get(userId); //get authUser from there
if (this._isMounted) {
this.setState({ authUser }); //update state
}
}
} catch (err) {
console.log('Error: ', err);
}
};
render() {
const { authUser } = this.state;
const { children } = this.props;
return (
<AuthContext.Provider
value={{
authUser
}}
>
{children}
</AuthContext.Provider>
);
}
}
AuthProvider.getInitialProps = ({ children }) => ({
children
});
const AuthConsumer = AuthContext.Consumer;
export { AuthProvider, AuthConsumer, bucket };
//.....
doAuth = async data => {
try {
const res = await app.authenticate({strategy: 'local',...data });
if (this._isMounted) {
this.setState({ isSubmitting: true });
}
const { userId } = await app.passport.verifyJWT(res.accessToken);
await Router.push(`/dashboard?userId=${userId}`); // redirect when authentication succeeds
if (this._isMounted) {
this.setState({ isSubmitting: false });
}
window.location.reload(); // i want to avoid this
return userId;
} catch ({ message }) {
if (this._isMounted) {
this.setState(prevState => ({
isSubmitting: false ,
errors: {
...prevState.errors,
general: { message }
}
}));
}
return null;
}
};
//.....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment