Skip to content

Instantly share code, notes, and snippets.

@vinodsobale
Created December 13, 2018 06:06
Show Gist options
  • Save vinodsobale/1c06d46e80ba693f8cadaeaacbf1ba26 to your computer and use it in GitHub Desktop.
Save vinodsobale/1c06d46e80ba693f8cadaeaacbf1ba26 to your computer and use it in GitHub Desktop.
HOC wrapper to redirect and provide token to all pages that need to be protected
import React from "react";
import Router from "next/router";
import universalCookie from "cookie";
import authApi from "../api/authApi";
import { redirectToLogin } from "../lib/utils";
export default function withAuth(AuthComponent) {
return class Authenticated extends React.Component {
static async getInitialProps(ctx) {
const { auth_token } = universalCookie.parse(ctx.req.headers.cookie);
const response = await authApi.validateToken(auth_token);
// Check if Page has a `getInitialProps`; if so, call it.
const pageProps =
AuthComponent.getInitialProps &&
(await AuthComponent.getInitialProps(ctx));
if (response.success) {
return { ...pageProps, auth_token };
} else {
redirectToLogin(ctx.res);
}
return { ...pageProps };
}
constructor(props) {
super(props);
this.state = {
isLoading: true
};
}
componentDidMount() {
const { auth_token } = this.props;
if (auth_token === undefined) {
Router.push("/login");
}
this.setState({ isLoading: false });
}
render() {
return (
<div>
{this.state.isLoading ? (
<div>LOADING....</div>
) : (
<AuthComponent {...this.props} />
)}
</div>
);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment