Skip to content

Commit

Permalink
fix: update seerverside module prop
Browse files Browse the repository at this point in the history
  • Loading branch information
lionelB committed Jun 3, 2020
1 parent 74bef5f commit 5af9ef9
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 67 deletions.
3 changes: 3 additions & 0 deletions .env.development
Expand Up @@ -3,6 +3,9 @@
##
ACCOUNT_EMAIL_WEBHOOK_URL=http://host.docker.internal:3000/api/webhooks/account

PORT=3000


##
## frontend secrets
##
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
@@ -1,3 +1,4 @@
.next
*.DS_Store
node_modules
node_modules
.env.production
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -20,7 +20,7 @@
"http-proxy-middleware": "^1.0.3",
"jsonwebtoken": "^8.5.1",
"next": "^9.4.0",
"next-urql": "^0.3.7",
"next-urql": "^0.3.8",
"nodemailer": "^6.4.6",
"polished": "^3.6.3",
"react": "^16.13.1",
Expand Down
11 changes: 6 additions & 5 deletions src/components/CustomUrqlClient.js
@@ -1,15 +1,16 @@
import { dedupExchange, cacheExchange, fetchExchange } from "@urql/core";
import { cacheExchange, dedupExchange, fetchExchange } from "@urql/core";
import { withUrqlClient } from "next-urql";
import { refreshToken } from "src/lib/auth";
import { authExchange } from "src/lib/authTokenExchange";
export const withCustomUrqlClient = (Component) =>
withUrqlClient(
(ctx) => {
const url = ctx?.req
? `http://localhost:${process.env.PORT}/api/graphql`
: `/api/graphql`;
console.log("[ withUrqlClient ]", { url });
return {
url:
ctx && ctx.req
? `http://localhost:${process.env.PORT}/api/graphql`
: "/api/graphql",
url,
fetchOptions: {
refreshToken: () => refreshToken(ctx),
},
Expand Down
44 changes: 4 additions & 40 deletions src/hooks/useAuth.js
@@ -1,9 +1,8 @@
import React, { createContext, useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import { getToken, setToken, refreshToken } from "src/lib/auth";
import { useQuery } from "urql";
import React, { createContext, useContext, useEffect, useState } from "react";
import { getToken, setToken } from "src/lib/auth";
import { request } from "src/lib/request";
import { getDisplayName } from "next/dist/next-server/lib/utils";
import { useQuery } from "urql";

export const AuthContext = createContext({
user: null,
Expand Down Expand Up @@ -59,7 +58,7 @@ export function useAuth() {
} catch (error) {
console.error("[ client logout ] failed", error);
}
window.location.reload();
window.location.reload(true);
}

const isAuth = Boolean(user);
Expand All @@ -69,38 +68,3 @@ export function useAuth() {
logout,
};
}

export function withAuthProvider(WrappedComponent) {
return class extends React.Component {
static displayName = `withAuthSync(${getDisplayName(WrappedComponent)})`;
static async getInitialProps(ctx) {
console.log(
"[withAuthProvider] getInitialProps",
ctx.req ? "server" : "client",
getToken() ? "found token" : "no token"
);

const jwt_token = getToken();
if (!jwt_token) {
try {
await refreshToken(ctx);
} catch {
console.error("[withAuthProvider] no token");
}
}

const componentProps =
WrappedComponent.getInitialProps &&
(await WrappedComponent.getInitialProps(ctx));

return { ...componentProps };
}
render() {
return (
<AuthProvider>
<WrappedComponent {...this.props} />
</AuthProvider>
);
}
};
}
58 changes: 54 additions & 4 deletions src/lib/auth.js
@@ -1,10 +1,14 @@
import { parse, serialize } from "cookie";
import { getDisplayName } from "next/dist/next-server/lib/utils";
import Router from "next/router";
import React from "react";
import { AuthProvider } from "../hooks/useAuth";
import { request } from "./request";
import { parse, serialize } from "cookie";
import { setRefreshTokenCookie } from "./setRefreshTokenCookie";

let token = null;

console.log("[ AUTHJS ]", { token });
function getToken() {
return token ? token.jwt_token : null;
}
Expand Down Expand Up @@ -38,7 +42,7 @@ async function refreshToken(ctx) {
credentials: "include",
mode: "same-origin",
headers,
body: { refresh_token: token?.refresh_token },
body: {},
}
);

Expand All @@ -52,7 +56,6 @@ async function refreshToken(ctx) {
} catch (error) {
console.error("[ auth.refreshToken error ]", { error });
console.log("[auth.refreshToken error]", token);
setToken(null);
if (ctx && ctx.res) {
ctx.res.writeHead(302, { Location: "/login" });
ctx.res.end();
Expand All @@ -70,4 +73,51 @@ function setToken(tokenData) {
token = tokenData;
}

export { getToken, getUserId, isTokenExpired, refreshToken, setToken };
function withAuthProvider(WrappedComponent) {
return class extends React.Component {
static displayName = `withAuthSync(${getDisplayName(WrappedComponent)})`;
static async getInitialProps(ctx) {
console.log(
"[withAuthProvider] getInitialProps",
ctx.req ? "server" : "client",
getToken() ? "found token" : "no token"
);

if (ctx?.req) {
console.log("init page context for server");
setToken(null);
}

const jwt_token = getToken();
if (!jwt_token) {
try {
await refreshToken(ctx);
} catch {
console.error("[withAuthProvider] no token");
}
}

const componentProps =
WrappedComponent.getInitialProps &&
(await WrappedComponent.getInitialProps(ctx));

return { ...componentProps };
}
render() {
return (
<AuthProvider>
<WrappedComponent {...this.props} />
</AuthProvider>
);
}
};
}

export {
getToken,
getUserId,
isTokenExpired,
refreshToken,
setToken,
withAuthProvider,
};
2 changes: 1 addition & 1 deletion src/lib/jwt.js
@@ -1,6 +1,6 @@
import jwt, { verify } from "jsonwebtoken";

const { HASURA_GRAPHQL_JWT_SECRET, JWT_TOKEN_EXPIRES = 15 } = process.env;
console.log({ HASURA_GRAPHQL_JWT_SECRET });
const jwtSecret = JSON.parse(HASURA_GRAPHQL_JWT_SECRET);

export function generateJwtToken(user) {
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/logout.js
Expand Up @@ -37,6 +37,7 @@ export default async function logout(req, res) {
console.error(e);
// let this error pass. Just log out the user by sending https status code 200 back
}
console.log("[ logout ]", { refresh_token });
res.setHeader(
"Set-Cookie",
cookie.serialize("refresh_token", "deleted", {
Expand Down
5 changes: 2 additions & 3 deletions src/pages/index.js
@@ -1,10 +1,9 @@
/** @jsx jsx */
import { jsx, Text } from "theme-ui";
import Head from "next/head";

import { withCustomUrqlClient } from "src/components/CustomUrqlClient";
import { withAuthProvider } from "src/hooks/useAuth";
import { Layout } from "src/components/layout/auth.layout";
import { withAuthProvider } from "src/lib/auth";
import { jsx, Text } from "theme-ui";

export function IndexPage() {
return (
Expand Down
11 changes: 5 additions & 6 deletions src/pages/users/index.js
@@ -1,14 +1,13 @@
/** @jsx jsx */
import { jsx, Flex, Heading } from "theme-ui";
import Head from "next/head";

import Link from "next/link";
import { IoIosAdd } from "react-icons/io";
import { Button } from "src/components/button";
import { withCustomUrqlClient } from "src/components/CustomUrqlClient";
import { withAuthProvider } from "src/hooks/useAuth";
import { Layout } from "src/components/layout/auth.layout";
import { UserList } from "src/components/UserList";
import Link from "next/link";
import { Button } from "src/components/button";
import { IoIosAdd } from "react-icons/io";
import { withAuthProvider } from "src/lib/auth";
import { Flex, Heading, jsx } from "theme-ui";

export function UserPage() {
return (
Expand Down
9 changes: 4 additions & 5 deletions src/pages/users/new.js
@@ -1,12 +1,11 @@
/** @jsx jsx */
import { jsx, Heading, NavLink, Field } from "theme-ui";
import Head from "next/head";

import { withCustomUrqlClient } from "src/components/CustomUrqlClient";
import { withAuthProvider } from "src/hooks/useAuth";
import { Layout } from "src/components/layout/auth.layout";
import Link from "next/link";
import { Button } from "src/components/button";
import { withCustomUrqlClient } from "src/components/CustomUrqlClient";
import { Layout } from "src/components/layout/auth.layout";
import { withAuthProvider } from "src/lib/auth";
import { Field, Heading, jsx, NavLink } from "theme-ui";

export function UserPage() {
return (
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Expand Up @@ -7007,7 +7007,7 @@ next-tick@~1.0.0:
resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz#ca86d1fe8828169b0120208e3dc8424b9db8342c"
integrity sha1-yobR/ogoFpsBICCOPchCS524NCw=

next-urql@^0.3.7:
next-urql@^0.3.8:
version "0.3.8"
resolved "https://registry.yarnpkg.com/next-urql/-/next-urql-0.3.8.tgz#b9af59be9bcf037558fc78b26ddbb51e26bcea0b"
integrity sha512-i0fOKI4tUmGh/4n8F+7r1UedyLDtDdaei+e6RC6eR0wPkcF04S4bX5N+JBLkvzVRONO5XRNcIBgo5UEmQS5YfQ==
Expand Down

0 comments on commit 5af9ef9

Please sign in to comment.